Lazarus

Programming => Packages and Libraries => Topic started by: Anonimista on August 28, 2019, 08:35:04 am

Title: Plex/Pyacc example with AST generation
Post by: Anonimista on August 28, 2019, 08:35:04 am
Hello!

I am looking into using Plex and Pyacc to create a simple interpreter. Unfortunately there are few examples on how to use there tools and I was not able to find any that show how to create an abstract syntax tree using them.

I would appreciate if anybody can link such an example. I have a basic knowledge of the original Lex and Yacc tools
Title: Re: Plex/Pyacc example with AST generation
Post by: avra on August 28, 2019, 09:46:07 am
Starting point:
https://wiki.freepascal.org/Make_your_own_compiler,_interpreter,_parser,_or_expression_analyzer#Lex_and_Yacc
Title: Re: Plex/Pyacc example with AST generation
Post by: Anonimista on August 28, 2019, 10:28:05 am
I've read that page. Also this example:

https://wiki.freepascal.org/Plex_and_Pyacc

But I am looking for an example that constructs an abstract syntax tree, like here:

http://web.eecs.utk.edu/~bvanderz/cs461/notes/parse_tree/

Unfortunately, there are only a couple of Pyacc examples.

Thanks!
Title: Re: Plex/Pyacc example with AST generation
Post by: Leledumbo on August 29, 2019, 02:43:02 am
Just make the actions on .y files to create AST nodes. e.g. from the wiki example (intentionally stripped down for brevity), instead of:
Code: Pascal  [Select][+][-]
  1. expressao
  2.     : expressao '+' termo   { $$ := $1 + $3; }
  3.     | termo                 { $$ := $1; }
  4.     ;
  5. termo
  6.     : termo '*' fator       { $$ := $1 * $3; }
  7.     | fator                 { $$ := $1; }
  8.     ;
  9. fator
  10.     : NUMBER                { $$ := $1; }
  11.     ;
  12.  
you can do:
Code: Pascal  [Select][+][-]
  1. expressao
  2.     : expressao '+' termo   { Root := BinaryExpressionNode($1,'+',$3); }
  3.     | termo                 { Root := $1; }
  4.     ;
  5. termo
  6.     : termo '*' fator       { $$ := BinaryExpressionNode($1,'*',$3); }
  7.     | fator                 { $$ := $1; }
  8.     ;
  9. fator
  10.     : NUMBER                { $$ := NumberNode($1); }
  11.     ;
  12.  
Now if you pass 1+2*3, you will get Root as if you do:
Code: Pascal  [Select][+][-]
  1. Root := BinaryExpressionNode(NumberNode(1),'+',BinaryExpressionNode(NumberNode(2),'*',NumberNode(3)));
  2.  
Certainly the AST structure design is your call. Feel free to figure out the node structure how the above could work.
Title: Re: Plex/Pyacc example with AST generation
Post by: Anonimista on August 29, 2019, 06:42:58 am
Yes that makes sense. I was hoping for a 'canonical' example like you can find in the Bison documentation but what you say should certainly work. Thanks!
TinyPortal © 2005-2018