Recursive Descent Parser Tutorial

From Progzoo
Revision as of 09:05, 8 March 2011 by Andr3w (Talk | contribs) (Allow Empty Lists)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Parsing JSON

Consider the production rules for N

N -> number
N -> [ N Z ]
N -> { word : N Y }
Z -> , N Z
Z -> ε
Y -> , word : N Y
Y -> ε

As it stands the function ParseN does not cope with lists. Notice that it fails to parse [1,2] but it does parse [

The case when (st.ttype=='[') should include:

    ParseN(st);
    ParseZ(st);
    if (st.nextToken()!=']')
      throw new Exception("Was expecting ]");
    return null;



[Font] [Default] [Show] [Resize] [History] [Profile]

Allow Empty Lists

As it stands the productions do not permit empty lists, the string [] will not parse. You can update the rewrite rules Consider the production rules for N

N -> number
N -> [ W
N -> { word : N Y }
W -> N Z ]
W -> ]
Z -> , N Z
Z -> ε
Y -> , word : N Y
Y -> ε

You must create a new method ParseW. In ParseN, if [ is read then you must call ParseW and return null.

In ParseW you must decide which rule to apply.

  • If the next input indicates an N is to follow ([ or { or number) then you must call ParseN and ParseZ then read the ] then return null.
  • If the next input is ] then simply return null.



[Font] [Default] [Show] [Resize] [History] [Profile]