Posted to tcl by abc at Mon Oct 22 10:00:56 GMT 2018view raw

  1. #!/usr/bin/tclsh
  2. #
  3. # abc @irc.freenode.net
  4. #
  5. # aycock parser following example in
  6. # http://core.tcl.tk/tcllib/doc/trunk/embedded/www/tcllib/files/modules/grammar_aycock/aycock.html
  7. #
  8. # modified to output instantiated syntax tree
  9. #
  10.  
  11. package require grammar::aycock
  12.  
  13. ## modified grammar, symbolic syntax tree output
  14. set p [grammar::aycock::parser {
  15. start ::= E {}
  16. E ::= E + T {list [lindex $_ 0] [lindex $_ 2] ADD}
  17. E ::= T {}
  18. T ::= T * F {list [lindex $_ 0] [lindex $_ 2] MUL}
  19. T ::= F {}
  20. F ::= NUMBER {}
  21. F ::= ( E ) {lindex $_ 1}
  22. }]
  23.  
  24. puts [$p parse {( NUMBER + NUMBER ) * ( NUMBER + NUMBER ) } \
  25. {{} 2 {} 3 {} {} {} 7 {} 1 {}}]
  26.  
  27. $p destroy
  28.  
  29.  
  30.