  
 : 'rule' ( -- parser )
   [
-    'non-terminal' [ ebnf-non-terminal-symbol ] action  ,
+    'non-terminal' [ symbol>> ] action  ,
     "=" syntax  ,
     'choice'  ,
   ] seq* [ first2 <ebnf-rule> ] action ;

USING: kernel compiler.units parser words arrays strings math.parser sequences 
       quotations vectors namespaces math assocs continuations peg
       peg.parsers unicode.categories multiline combinators.lib 
       splitting ;
IN: peg.ebnf

TUPLE: ebnf-non-terminal symbol ;

  H{ } clone dup dup [ parser set swap (transform) main set ] bind ;

M: ebnf (transform) ( ast -- parser )
  rules>> [ (transform) ] map peek ;
  
M: ebnf-rule (transform) ( ast -- parser )
  dup elements>> (transform) [
    swap symbol>> set
  ] keep ;

M: ebnf-sequence (transform) ( ast -- parser )
  elements>> [ (transform) ] map seq ;

M: ebnf-choice (transform) ( ast -- parser )
  options>> [ (transform) ] map choice ;

M: ebnf-any-character (transform) ( ast -- parser )
  drop any-char ;

M: ebnf-range (transform) ( ast -- parser )
  pattern>> range-pattern ;

: transform-group ( ast -- parser ) 
  #! convert a ast node with groups to a parser for that group
  group>> (transform) ;

M: ebnf-ensure (transform) ( ast -- parser )
  transform-group ensure ;

M: ebnf-ensure-not (transform) ( ast -- parser )
  transform-group ensure-not ;

M: ebnf-repeat0 (transform) ( ast -- parser )
  transform-group repeat0 ;

M: ebnf-repeat1 (transform) ( ast -- parser )
  transform-group repeat1 ;

M: ebnf-optional (transform) ( ast -- parser )
  transform-group optional ;

M: ebnf-action (transform) ( ast -- parser )
  [ parser>> (transform) ] keep
  code>> string-lines [ parse-lines ] with-compilation-unit action ;

M: ebnf-terminal (transform) ( ast -- parser )
  symbol>> token sp ;

M: ebnf-non-terminal (transform) ( ast -- parser )
  symbol>>  [
    , parser get , \ at ,  
  ] [ ] make delay sp ;

