-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJs2Py.g4
136 lines (102 loc) · 2.24 KB
/
Js2Py.g4
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
grammar Js2Py;
/*
* Parser Rules
*/
// Note : scopes must be NEWLINED
program: (line | function)+ EOF;
line: (ternary_statement | statement | conditional_statement) ';'? NEWLINE+;
// Statement
statement: (
assignment
| array_ops
| array_concat
| function_return
| function_call
| arithmetic
| console_log
| while_loop
);
condition: expression (relop expression)*;
conditional_statement:
IF '(' condition ')' '{' NEWLINE* line+ '}';
ternary_statement: expression '?' statement ':' statement;
// Assignment
value: (
VARIABLE
| NUMBER
| TEXT
| function_call
| array_item
| array_length
| array
);
assignment: ( VAR | CONST | LET) VARIABLE '=' value;
// Function
function: (
FUNCTION VARIABLE? '(' value* ')' '{' NEWLINE* line+ '}' ';'? NEWLINE+
);
function_call: VARIABLE '(' value* ')';
function_return: RETURN (value | array_concat);
// Arithmetic
op: (ADD_OP | SUB_OP | MUL_OP | DIV_OP);
unary_arithmetic: VARIABLE (UNARY_ADD | UNARY_MINUS);
arithmetic: ( (value op value (op value)*) | unary_arithmetic);
// Relational
relop: (LT | LTE | GT | GTE | EQ | NEQ);
expression: (value | arithmetic) relop (value | arithmetic);
// Array
array_item: VARIABLE '[' (value | arithmetic) ']';
array_length: VARIABLE '.' 'length';
array: '[' value? ( ',' value)* ']';
array_ops:
VARIABLE '.' ('push' | 'pop') '(' (value | array_item)+ ')';
array_concat:
value '.' 'concat' '(' (value | array_item) (
',' (value | array_item)
)* ')';
// Console
console_log: CONSOLE '.log' '(' value ( ',' value)* ')';
// Loop
while_loop:
WHILE '(' condition ')' '{' NEWLINE* (
line+
| (BREAK NEWLINE)
) '}';
/*
* Lexer Rules
*/
fragment LOWERCASE: [a-z];
fragment UPPERCASE: [A-Z];
fragment DIGIT: [0-9];
FUNCTION: 'function';
RETURN: 'return';
WHILE: 'while';
VAR: 'var';
CONST: 'const';
LET: 'let';
IF: 'if';
ELSE: 'else';
LT: '<';
LTE: '<=';
GT: '>';
GTE: '>=';
EQ: '==';
NEQ: '!=';
CONSOLE: 'console';
BREAK: 'break';
ADD_OP: '+';
SUB_OP: '-';
MUL_OP: '*';
DIV_OP: '/';
UNARY_ADD: '++';
UNARY_MINUS: '--';
VARIABLE: (LOWERCASE | UPPERCASE) (
LOWERCASE
| UPPERCASE
| DIGIT
| '_'
)*;
NUMBER: DIGIT+ ([.,] DIGIT+)?;
WHITESPACE: (' ' | '\t')+ -> skip;
NEWLINE: ('\r'? '\n' | '\r')+;
TEXT: ('"' | '\'') ~['"]+ ('\'' | '"');