1

Can I replace indent_loop[3] in following grammar with the the group of 3 INDENT? Where INDENT is lexical rule for indentation.

I just want to write number of INDENT based on the number.

match_node
        :   match_node_name (tree_operator) (NEW_LINE (indent_loop[3]) ( moduleCall | literals ))*
            { match_node_list.push($match_node_name.text); }
        |   SINGLE_QUOTE POINTE SINGLE_QUOTE 
        ;


    match_node_name
        :   IDENT_SMALL_LETTERS
        ;

    indent_loop[int scope]
        :   {scope == 3}? INDENT INDENT INDENT  
        |   {scope == 4}? INDENT INDENT INDENT INDENT   
        ;

    INDENT :  '\t';

When I did this I was not able to come back to my calling rule and was not able to return this group of indentation? Means, ( moduleCall | literals ))* was not called.

Where I am wrong? I am just begining.

Or is there any other way to do this?

manan shah
  • 11
  • 1

1 Answers1

1

You can do that by using a semantic predicate1:

grammar T;

parse
 : digit[1] digit[2] digit[3] EOF
 ;

digit[int amount]
 : ({amount > 0}?=> DIGIT {amount--;})*
 ;

DIGIT
 : '0'..'9'
 ;

Parsing "456789" with a parser generated from the grammar above, would result in the following parse:

enter image description here

Note that in your case, you're simply matching a tab, not necessarily an indentation (i.e. one or more tabs from the start of a line). If you only want to match indentations from the start of the line, the (IMHO) easiest way would be to handle them in the lexer2.


1 What is a 'semantic predicate' in ANTLR?
2 ANTLR What is simpliest way to realize python like indent-depending grammar?

Community
  • 1
  • 1
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288