small medium large xlarge

Generic-user-small
01 Dec 2016, 20:34
Lin Zhang (8 posts)

On page 210, there is a code as follows:

keyIF : {_input.LT(1).getText().equals("if")}? ID ;

Can you tell me what’s the meaning of _input.LT(1)?

Generic-user-small
08 Dec 2016, 20:19
Lin Zhang (8 posts)

I was told LT(1) means next token.

Can you please tell me whether my understanding is correct towards what next token means here for this grammar as follows:

grammar PredKeyword;

prog: stat+ ;

stat: keyIF expr stat
    | keyCALL ID ';'
    | ';'
    ;

expr: ID
    ;

keyIF : {_input.LT(1).getText().equals("if")}? ID ;

keyCALL : {_input.LT(1).getText().equals("call")}? ID ;

ID : 'a'..'z'+ ;
WS : (' '|'\n')+ {setChannel(HIDDEN);} ;

The _input.LT(1).getText() is getting the text for “expr”, right? If yes, then the parser rule says: if the text for “expr” is “if”, then keyIF is ID; otherwise, keyIF is null. Am I correct? Thank you for your time and help!

Ter-brew-pub_pragsmall
08 Dec 2016, 20:21
Terence Parr (52 posts)

_input.LT(1).getText() is getting the 1st token of lookahead’s text not expr. The point is to decide if the ID is “if” or “call”.

Generic-user-small
08 Dec 2016, 20:40
Lin Zhang (8 posts)

Dear Terence, thank you very much for your reply. I still have two questions awaiting your clarification:

i) So the parser rule “keyIF” means: if the text for “keyIF” is “if”, then it is an ID; otherwise the text for “keyIF” should be null. Am I correct? ii) What’s the difference between LA(1) and LT(1)? In page 162, you said LA(1) marks the first token of lookahead (the current token). This seems the same as LT(1).

Ter-brew-pub_pragsmall
08 Dec 2016, 21:25
Terence Parr (52 posts)

nope. keyIF is a rule that means match an ID token but only if it has “if” text.

Ter-brew-pub_pragsmall
08 Dec 2016, 21:25
Terence Parr (52 posts)

LA(1) is the token type of the token object returned from LT(1)

Generic-user-small
08 Dec 2016, 22:24
Lin Zhang (8 posts)

Dear Terrence, thank you for your quick reply. So the “keyIF” rule means if the current token is not “if”, it is not playing any role or the grammar will pass/ignore this rule. Am I right now? Thank you for your time and help.

You must be logged in to comment