JavaCC LOOKAHEAD option

What's LOOKAHEAD ?


It's used to resolve conflict. For example:

PARSER_BEGIN(Parser)import java.io.*;import java.util.*;public class Parser{    public static void main(String[] args) throws ParseException, FileNotFoundException     {        Parser parser = new Parser(new FileInputStream(args[0]));        parser.Input();    }    public static boolean yes() {        return true;    }    public static boolean no() {        return false;    }}PARSER_END(Parser)TOKEN:{      | }void Input() :{}{  LOOKAHEAD(…) AB() | A() B()}void A() :{}{    }void B() :{}{    }void AB() :{}{     }



The input "a b" can match both

Choice 1: AB() and

Choice 2: (A() B())

So we must use LOOKAHEAD to distinguish them.


Two types of LOOKAHEAD

Global LOOKAHEAD


Set a global LOOKAHEAD specification by using the option "LOOKAHEAD" either from the command line or at the beginning of the grammar files in the options section. The value of this option is an integer which is the number of tokens to look ahead when making choice decisions.



Local LOOKAHEAD

Set a local LOOKAHEAD specification that affects only a specific choice point.



When a LOOKAHEAD is required?



There are 4 different kinds of choicepoints in JavaCC where a LOOKAHEAD can be used:

1.      ( exp1 | exp2 | ... )

2.      [ exp ], or ( exp )?

3.      ( exp )*

4.      ( exp )+



The LOOKAHEAD is not needed when there is no choice, such as

void P() :

{}

{

   LOOKAHEAD(...)

}


LOOKAHEAD syntax



The general structure of a LOOKAHEADspecification is:

LOOKAHEAD( amount, expansion, { boolean_expression } )


l  amount: an integer specifies the number of tokens to LOOKAHEAD

l  expansion: specifies the expansion to use to perform syntacticLOOKAHEAD

l  boolean_expression: is the Boolean expression to use for semanticLOOKAHEAD; for example it can be a simple Boolean java function.


It means look ahead amount token, if it prefix match the expansion, and boolean_expressionreturn true, then use the choice.


Among the 3 entries, at least one of themmust be present; and others will have default value:

"mount":

2147483647        - if"expansion" is present

0                 - if "boolean_expression" ispresent

Note: When"amount" is 0, no syntactic LOOKAHEAD is performed.  Also, "amount" does not affect thesemantic LOOKAHEAD.

"expansion":          - defaults to theexpansion being considered.

"boolean_expression": - defaultsto true.



Samples for above grammar case




你可能感兴趣的:(JavaCC)