My grammar is Calc. it calc regular number and binary number. regular number has
ID: 3853848 • Letter: M
Question
My grammar is Calc. it calc regular number and binary number.
regular number has its grammar and binary has its grammar
regular number has 0 and 1 also binary number has 0 and 1
so my problem is I want write regular number 0 or 1 like 1+1 or 0+1 but it is not work
grammar Expr;
// Program is a sequence of statements
prog :'<' bi+ '>'
| stat+
;
bi : '<' binary '>'
| NEWLINE
;
binary : binary ('+' | '-' ) binary
| binary ('*' | '/' ) binary
| Binary_digit
;
stat : expr NEWLINE #print
| CLEAR #clear
| ID '=' expr NEWLINE #assign
| INT '=' expr NEWLINE #assign
| NEWLINE #blank
;
expr : '-' expr #uminus // Unary minus
| expr op=('*' | '/' ) expr #MulDiv
| expr op=('+' | '-' ) expr #AddSub
| INT #int
| ID #id
| '(' expr ')' #parens
;
MUL : '*';
DIV : '/';
ADD : '+';
SUB : '-';
EQ : '=' ;
GT : '>' ;
LT : '<' ;
// Keywords
CLEAR : 'clear';
Binary_digit : [01]+ ;
INT : ('0' .. '9')+ ('0' .. '1')+
;
DIGIT
: ('0' .. '1')+
;
ID : [a-zA-Z]+ ;
NEWLINE : [ ]+;
WS : [ ]+ -> skip;
rerror :
C:UsersFDesktopPL>grun Expr prog -gui
1+1
^Z
line 1:0 mismatched input '1' expecting {'(', '-', '<', 'clear', INT, ID, NEWLINE}
Explanation / Answer
I think the mistake you are doing is that you are giving the input as a string without any spaces, so just add spaces in between and program should work fine. So, effectively input should be 1 + 1. Please feel free to ask if you have any more doubts!!
Here is a much better grammar available, you can check it for your reference:
https://github.com/antlr/grammars-v4/tree/master/calculator
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.