parsing - How to represent recursive EBNF grammar in Rust data structures? -


let's have following example ebnf grammar. not perfect grammar, should demonstrate problem correctly.

statement = functiondefinition | assignment | expr ; expr = { term | "(" , expr , ")" } ;  assignment = word , "=" , expr ; functiondefinition = word , { word } , "=" , expr ;  term = word | number 

where word number of letters , numbers , number valid numeric literal.

i can start represent in rust so:

enum statement {     functiondefinition {         name: string,         params: vec<string>,         body: expr,     },     assignment {         name: string,         body: expr,     },     //todo: expr } 

there problem here though. how add expr? expr should have own definition since used in several other places well. giving expr own separate definition , adding enum redefine it.

if continue anyway , start trying define expr, run more problems:

type expr = vec<...?...>; // or maybe... struct expr {     terms: vec<expr>, // term?? } 

i tried use type because expr not need own struct or enum since collection of terms or other exprs. difficult recursively define though. if try use enum emulate union type expr , term, have redefine expr in enum , define term within enum makes term unavailable in other structures need.

expr can type alias, need define enum represent alternation. term needs separate enum.

enum statement {     functiondefinition {         name: string,         params: vec<string>,         body: expr,     },     assignment {         name: string,         body: expr,     },     expr(expr), }  type expr = vec<expritem>;  enum expritem {     term(term),     parenthesized(expr), }  enum term {     word(string),     number(f64), } 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo