-
Notifications
You must be signed in to change notification settings - Fork 0
/
46_18406.pl
61 lines (46 loc) · 1.87 KB
/
46_18406.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
% Define grammar rules
s(Tree) --> (assignment(Tree); conditional(Tree)).
conditional(if_else(If, Else)) --> if_statement(If), ['else'], s(Else).
conditional(if(If)) --> if_statement(If).
conditional(while(While,Body)) --> ['while'], ['('], boolean(While), [')'], s(Body).
if_statement((Expr, Body)) --> ['if'], ['('], boolean(Expr), [')'], s(Body).
boolean(boolean(Left,Op,Right)) --> expr(Left), operator_Compare(Op),expr(Right).
assignment(assign(Id, Expr,End)) --> identifier(Id), ['='], expr(Expr),semi_colon(End).
assignment(assign(Id, Expr,End,Body)) --> identifier(Id), ['='], expr(Expr),semi_colon(End),s(Body).
identifier_tail([Char|Tail]) -->
[Char], {
( catch(number(Char), _, fail), Char >= 0, Char =< 9 )
},
identifier_tail(Tail).
identifier_tail([Char|Tail]) -->
[Char], {
( catch(code_type(Char, alnum) , _, fail));
Char = '_';
Char = '$'
},
identifier_tail(Tail).
identifier_tail([]) --> [].
identifier(id(X)) -->
[First], { catch(code_type(First, alpha), _, fail) ; First = '_' ; First='$'},
identifier_tail(Tail),
{ append([First|Tail], [], X) }.
expr(expr(Term)) --> term(Term).
expr(expr(Left, Op, Right)) --> term(Left), operator(Op), expr(Right).
term(term(Factor)) --> factor(Factor).
term(term(Left, Op, Right)) --> factor(Left), operator(Op), term(Right).
factor(factor(Num)) --> num(Num).
factor(factor(Id)) --> identifier(Id).
factor(factor(Expr)) --> ['('], expr(Expr), [')'].
operator(add) --> ['+'].
operator(sub) --> ['-'].
operator(mul) --> ['*'].
operator(div) --> ['/'].
operator(mod) --> ['%'].
operator_Compare(equal) --> ['=='].
operator_Compare(inequality) --> ['!='].
operator_Compare(less_equal) --> ['<='].
operator_Compare(less) --> ['<'].
operator_Compare(greater_equal) --> ['>='].
operator_Compare(greater) --> ['>'].
semi_colon(end) -->[';'].
num(num(X)) --> [X], {number(X)}.