[antlr-interest] Tree walking

Jeff Dahl jddahl at micron.com
Wed Jun 29 15:26:52 PDT 2005


Why does SAMPLE.TREE.G not walk the entire tree?  Instead of

    ROOT
    |-- A
    |   `-- B
    |       |-- C
    |       |   |-- attribute1
    |       |   |   `-- value 1
    |       |   |-- attribute2
    |       |   |   `-- value 2
    |       |   `-- attribute3
    |       |       `-- value 3
    |       `-- D
    |           `-- attribute4
    |               `-- value 4
    |-- E
    |   `-- attribute5
    |       `-- value 5
    `-- F
        `-- attribute6
            `-- value 6

SAMPLE.TREE.G outputs

    ROOT
    |-- A
    |   `-- B
    |       |-- C
    |       `-- D
    |-- E
    `-- F

Also, once I can walk the entire tree, how do I change SAMPLE.TREE.G to 
transform the tree into

    A
    |-- B
    |   |-- C
    |   |   |-- attribute1
    |   |   |   `-- value 1
    |   |   |-- attribute2
    |   |   |   `-- value 2
    |   |   `-- attribute3
    |   |       `-- value 3
    |   `-- D
    |       `-- attribute4
    |           `-- value 4
    |-- E
    |   `-- attribute5
    |       `-- value 5
    `-- F
        `-- attribute6
            `-- value 6

Or in other words, how do I replace the ROOT node with its first child?

Thanks,
Jeff Dahl
------------------------------------------------------
SAMPLE.TXT

    $$_begin_A
       $$_begin_B
          $$_begin_C
             attribute1: value 1
             attribute2: value 2
             attribute3: value 3
          $$_end_C
          $$_begin_D
             attribute4: value 4
          $$_end_D
       $$_end_B
    $$_end_A
    $$_begin_E
       attribute5: value 5
    $$_end_E
    $$_begin_F
       attribute6: value 6
    $$_end_F

SAMPLE.TREE.G

    class SampleTreeParser extends TreeParser;
    options { buildAST=true; defaultErrorHandler=false; k=3; }
    tokens  { ROOT; }

    parse       : #(ROOT (section)+) ;

    section     : #(O_SECTION (key_value|section)*) ;

    key_value   : #(KEYWORD VALUE) ;

SAMPLE.G

    class SampleParser extends Parser;
    options { buildAST=true; defaultErrorHandler=false; k=3; }
    tokens  { ROOT; }

    parse       : (section)+ {#parse = #([ROOT, "ROOT"], #parse); } EOF! ;

    section     : O_SECTION^ (key_value|section)* C_SECTION! ;

    key_value   : KEYWORD^ VALUE ;

    class SampleLexer extends Lexer;
    options { defaultErrorHandler=false; caseSensitive=false; k=6; }

    SECTION     :
    "$$_"!("begin_"!{$setType(O_SECTION);}|"end_"!{$setType(C_SECTION);})
    ('a'..'z'|'_')+ NEWLINE! ;

    KEYWORD     : {getColumn()==1}? CHARS ((' '|'-'|'/') CHARS)* (':'!)? ;

    VALUE       : WS! (~'\n')* NEWLINE!;

    protected
    CHARS       : (options{greedy=true;}:'a'..'z'|'0'..'9'|'_')+ ;

    protected
    WS          : (options{greedy=true;}:' '|'\t')+ ;

    protected
    NEWLINE     : ((WS)? '\n'{newline();}|'\r')+ ;




More information about the antlr-interest mailing list