S-Expressions
The org.jfuncmachine.sexprlang.parser package provides a Parser
class that reads a file or string containing one or more
S-expressions and returns an SexprItem representing its contents.
By default, the parser only reads the first S-expression, so if you
want to parse a whole file of S-expressions, you need to call the
parser with the parseMultipleSexprs value set to true.
SexprItem and Subclasses
The SexprItem class is the base class for the possibly values
in an S-expression. Its subclasses are:
| Class | Description |
|---|---|
SexprString |
A string value |
SexprInt |
An int value |
SexprDouble |
A floating-point value |
SexprSymbol |
A symbol |
SecprList |
A list of SexprItems |
Symbols
One place where there is some variation in S-expressions is in
what constitutes a symbol. You can provide the parser with
a class that implements SymbolMatcher, which defines a method
to determine whether a character can appear as the first character
in a symbol (isSymbolFirstCharacter) and a method to
determine if a character can appear anywhere after the first
character in a symbol (isSymbolChar). JFuncMachine provides
a default matcher named JavaSymbolMatcher that uses the same
rules as Java for symbols, and also JavaExtSymbolMatcher which
allows ‘.’ to appear in a symbol, so that a symbol could
represent a fully-qualified Java class name.
Example
Here is a snippet of Java code that parses a simple
program expressed in an S-expression using its own
custom matcher. The null is the name of the file that
was parsed. The parser will embed the filename and line number
where an S-expression starts in each SexprItem, which can be
useful when interacting with JFuncMachine since it also allows
filename and line number to be associated with expressions:
SexprItem item = Parser.parseString("""
(define fact (n acc)
(if (< n 2) acc
(fact (- n 1) (* acc n))))
(print "10! is %d" (fact 10 1))
""", null, true, new IntlangSymbolMatcher());