Writing recursive descent for epsilon (ε) parsing in Java

For instance,

EBNF

A :: = B c;

B :: = T1 | T2 | ε

T1 :: = a

T2 :: = b

parseA()
{
switch(currentToken.kind){
case Token.a :
    parseT1();
case Token.b :
    parseT2();
break;

case <epsilon> :

break;
default:
    // report error
break;
}
}

How to write epsilon parser parser (empty string set) in Java?

+3
source share
4 answers

epsilonis just a marker for the "empty string allowed here", so you don't need to parse anything; the descent is complete. It seems unlikely that you actually have a token for this; you need to determine if there is an available token or if the next token can be used in another release.

, c. , A ::= B c;, B epsilon - epsilon, , B , c A

+4

Java - , , . "" , . "" , , "" .

. ?

"", "".
" ", "".
"".

, ParseA ParseB.

B .
"", .
"b", .
ParseA ( ).

ParseA .
"c", .
.

?

, , . , . , , .

+4

, , . : "[ab]? C". , , :

Boolean parseA() { 
    // an A is a B followed by a `c`:
    return parseB() && (get_token() == Token.c);
}

Boolean parseB  {
    // Get a token. 
    //     If it an `a` or a `b`, consume it. 
    //     Otherwise, throw it back (match null string by consuming nothing).
    // Either way, return true (successful match).
    //
    token current_token = get_token();
    if (token != Token.a && token != Token.b)
        push_back(current_token);
    return true;
}

( ): , B, Token.c. B, : "a", "b" . , A, , B, Token.c.

, - :

A:: = B C

B:: = a | b | ε

C:: = c |

"B" , , . , , () B, C.

+3

"", - FOLLOW . FOLLOW (B) = {'c'}, case Token.c: parseB

0

Source: https://habr.com/ru/post/1757485/


All Articles