93 lines
2.3 KiB
Plaintext
93 lines
2.3 KiB
Plaintext
// ============================================================================
|
|
// Demo parser for four operator calculator
|
|
// ============================================================================
|
|
unit calcParser;
|
|
|
|
parser TcalcParser;
|
|
options
|
|
{
|
|
importVocab = calcLexer;
|
|
exportVocab = calcParser;
|
|
}
|
|
memberdecl
|
|
{
|
|
value : integer;
|
|
}
|
|
|
|
// ============================================================================
|
|
// calc
|
|
// ============================================================================
|
|
calc
|
|
: (expression SEMI {writeln(value);} )+
|
|
;
|
|
|
|
|
|
// ============================================================================
|
|
// expression
|
|
// ============================================================================
|
|
expression
|
|
: simpleExpression
|
|
;
|
|
|
|
// ============================================================================
|
|
// simpleExpression
|
|
// ============================================================================
|
|
simpleExpression
|
|
local
|
|
{
|
|
temp: integer;
|
|
}
|
|
: term { temp := value; }
|
|
(
|
|
PLUS term { temp := temp + value; }
|
|
| MINUS term { temp := temp - value; }
|
|
)* { value := temp; }
|
|
;
|
|
|
|
// ============================================================================
|
|
// term
|
|
// ============================================================================
|
|
term
|
|
local
|
|
{
|
|
temp: integer;
|
|
}
|
|
: factor { temp := value; }
|
|
(
|
|
STAR factor { temp := temp * value; }
|
|
| SLASH factor { temp := temp div value; }
|
|
)* { value := temp; }
|
|
;
|
|
|
|
// ============================================================================
|
|
// factor
|
|
// ============================================================================
|
|
factor
|
|
local
|
|
{
|
|
s: integer;
|
|
}
|
|
{
|
|
s := 1;
|
|
}
|
|
:
|
|
(
|
|
PLUS { s := 1; }
|
|
| MINUS { s := -1; }
|
|
)?
|
|
(
|
|
uInt
|
|
| LPAREN expression RPAREN
|
|
)
|
|
{
|
|
value := s * value;
|
|
}
|
|
;
|
|
|
|
// ============================================================================
|
|
// uInt
|
|
// ============================================================================
|
|
uInt
|
|
: x:INT { value := StrToInt( x.TokenText); }
|
|
;
|