Files
bds.mr.dpg/doc/grammars/calc/calcParser.g
T
2026-01-03 18:31:15 +01:00

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); }
;