Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using antlr4 and define my own expression grammer it work fine ... But when I add a rule then the rule not match ... my grammer is work fine :


/**
 * Define a grammar called Hello
 */
grammar Hello;

@parser::header{


    import java.util.Map;
    import java.util.HashMap;
    import java.util.List;
    import java.util.ArrayList;
    import ast.*;


}


@parser::members{
    Map<String,Object> symbolTable=new HashMap<String,Object>();
}
r  : PROGRAM ID BRACKET_OPEN 
    {
      List<ASTNode> body= new ArrayList<ASTNode>();
    }
  (sentence{body.add($sentence.node);})*
 BRACKET_CLOSE 
 {
    for(ASTNode n: body )
    {
        n.excute();
    }
 }

 ;         // match keyword hello followed by an identifier


 sentence returns [ASTNode node]:println{$node=$println.node;};

 println returns [ASTNode node]:PRINTLN  expression SEMICOLON {$node=new Println($expression.node);System.out.println($PRINTLN.getLine());};
 expression returns [ASTNode node]:
  t1=factor {$node=$t1.node;}
  (PLUS t2=factor{$node= new Addition($node,$t2.node);}
    |MINUS t2=factor{$node= new Sub($node,$t2.node);}
  )*
  ;

  factor returns [ASTNode node]: t1=term {$node=$t1.node;}
  (MULT t2=term{$node= new Multiplication($node,$t2.node);}
    | DIV t2=term{$node= new Div($node,$t2.node);}
  )*
  ;

 term returns [ASTNode node]:
  NUMBER {$node=new Constant(Integer.parseInt($NUMBER.text));}
   | ID {$node=new VarRef($ID.text);}
   | PAR_OPEN expression {$node=$expression.node;} PAR_CLOSE
   ;


PROGRAM:'program';
VAR:'var';
PRINTLN:'println';
INT :'int';
DOUBLE :'double';
STRING :'string';
MULT :'*';
PLUS :'+';
DOT : '.';
MINUS:'-';
DIV:'/' ;
ASSIGN:'=';
BRACKET_OPEN : '{';
BRACKET_CLOSE : '}';

PAR_OPEN :'(';
PAR_CLOSE :')';

SEMICOLON:';';




ID : [a-zA-Z_][a-zA-Z0-9_]* ;             // match lower-case identifiers
IDM : [a-zA-Z_][a-zA-Z0-9_]* ; 
NUMBER :[0-9]+;

WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines



when I write the input :

program test{println class1.get()+y/m;}

then the output is : [1:27] mismatched input 'get' expecting IDM

and $ID.text and $IDM.text not print on consol

so what wrong ?

What I have tried:

I put my try in my question But it not work ... can any body help me ?
Posted
Updated 17-Sep-16 0:19am
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900