AST
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

84 wiersze
2.2 KiB

%{
/* compile: leg -o calc.c calc.leg
* cc -o calc calc.c
*
* run: ( echo a=2*3; echo b=3+4; echo c=a*b ) | ./calc
*/
#define SYMBOL_PAYLOAD \
oop value; \
int defined
#define SYMBOL_INITIALISE(S) \
S.value = null; \
S.defined = false
#include "object.c"
// this should stay out of object.c because it manipulates Symbol members defined in this file
oop update_symbol_value(oop symbol, oop integer)
{
//_checkType(symbol, Symbol);
// For now it will fail with assigning to null
// because for now we can write "a=2 b=a" because everything is passed by value
//_checkType(integer, Integer);
set(symbol, Symbol,value, integer); // checktyype is implicit, and it's ok for symbols to store any object value?
return symbol;
}
#define YYSTYPE oop
YYSTYPE yylval;
%}
start = e:exp { yylval = e }
exp = - (a:assign { $$ = a }
| s:sum { $$ = s }
)
assign = l:IDENT EQUAL n:sum { $$ = update_symbol_value(l, n) }
sum = l:prod ### removed PLUS* from beginning and made + a prefix operator just like - instead
( PLUS+ r:prod { get(l, Integer, value) += get(r, Integer, value) }
| MINUS r:prod { get(l, Integer, value) -= get(r, Integer, value) }
)* { $$ = l }
prod = l:neg
( MULTI r:neg { get(l, Integer, value) *= get(r, Integer, value) }
| DIVIDE r:neg { get(l, Integer, value) /= get(r, Integer, value) }
| MODULO r:neg { get(l, Integer, value) %= get(r, Integer, value) }
)* { $$ = l }
neg = MINUS n:neg { set(n, Integer, value, -get(n, Integer, value)); $$ = n }
| PLUS n:neg { $$ = n } ### moved from sum
| n:value { $$ = n }
value = n:NUMBER { $$ = n }
| NULL { $$ = null; /* For now it doesn't work because of _checktype in update_symbol_value() */ }
| l:IDENT { $$ = get(l, Symbol, value); // Will result in an assertion failed if ident is undefined }
- = [ \t\n\r]* ### added newline and carriage return to allow multi-line `programs'
NUMBER = < [0-9]+ > - { $$ = makeInteger(atoi(yytext)) }
IDENT = < [a-zA-Z][a-zA-Z0-9_]* > - { $$ = intern(yytext) }
PLUS = '+' -
MINUS = '-' -
MULTI = '*' -
DIVIDE = '/' -
MODULO = '%' -
EQUAL = '=' -
NULL = 'null' -
%%
int main(int argc, char **argv)
{
while (yyparse()) {
println(yylval);
}
return 0;
}