简体   繁体   中英

How to resolve this indirect first set conflict in grammar?

The following is a small section of the grammar that I'm trying to simplify to LL(1):

A -> B 
   | C 
   | intnum 
   | floatnum 
   | lpar D rpar 
   | not A 
   | E A .

B -> F I .

C -> G lpar rpar .

F -> id H F 
   | id .

G -> id H G 
   | id .

I know that both F and G have first set conflicts and that they can be solved the following way:

F  -> id F'
F' -> H F
    | .
G  -> id G'
G' -> H G
    | .

But I'm lost as to how to resolve the indirect first set conflict with A . Both B and C point to different symbols, but F and G are both pointing to id . I've been using this tool to help, but it cannot handle this type of conflict.

Since F and G are identical, a top-down parser won't be able to handle a grammar in which both are possible predictions. (Here, we can't see the definition of I , but if it happens to be the case that lpar ∈ FIRST(I) then even a bottom-up parser will have problems.)

The simple solution is to eliminate the redundancy by using only one of those productions in both contexts.

For a top-down parser, you will still need to left-factor since B and C still have the same FIRST sets. A simple solution might be:

A ⇒ B'
  | intnum 
  | floatnum 
  | lpar D rpar 
  | not A 
  | E A .

B' ⇒ F C' .

C' ⇒ I
   | lpar rpar .

Provided that lpar ∉ FIRST(I) (and similar assurances for E ), this fragment is LL(1).

How applicable that is to your full grammar depends on how much of a simplification this fragment was. There are variations on this problem which are extremely difficult to solve for an LL(1) parser, but relatively simple for an LR(1) parser (or an LR(k) parser for small k). In particular, your original grammar, even with the redundancy of F and G , is LALR(1) (tested with Bison).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM