开发者

Building Lisp/Scheme-like parse tree with flex/bison

开发者 https://www.devze.com 2023-01-05 00:36 出处:网络
I was trying to parse simple Lisp/scheme-like code E.g. (func a (b c d) ) and build a tree from it, I could do the parsing in C without usin开发者_运维知识库g bison (i.e, using only

I was trying to parse simple Lisp/scheme-like code

E.g. (func a (b c d) )

and build a tree from it, I could do the parsing in C without usin开发者_运维知识库g bison (i.e, using only flex to return tokens and building the tree with recursion). But, with bison grammar, I am not sure where to add the code to build the list (i.e, which rule to associate with accumulating terminal symbols and where to link a built list to parent node).

My grammar is similar to the one here: Lisp grammar in yacc the grammar is correct and can recognize the code.


Have you tried placing the code to add an element to the current list in each atom, and code to manage a tree of lists when you process the brackets? It seems the easiest way unless you run into other problems:

listend: members ')'        { cur = cur->parent; }
       | ')'                { cur = cur->parent; }
       ;

list: '(' listend           { cur = newList(cur);}
    ;

atom: ID                    { appendAtom(cur, "ID"); }
    | NUM                   { appendAtom(cur, "NUM");}
    | STR                   { appendAtom(cur, "STR");}
    ;

This assumes that you are keep a parent point in each list struct.

0

精彩评论

暂无评论...
验证码 换一张
取 消