Recent

Author Topic: Plex/Pyacc example with AST generation  (Read 1425 times)

Anonimista

  • New Member
  • *
  • Posts: 19
Plex/Pyacc example with AST generation
« 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

avra

  • Hero Member
  • *****
  • Posts: 2514
    • Additional info
ct2laz - Conversion between Lazarus and CodeTyphon
bithelpers - Bit manipulation for standard types
pasettimino - Siemens S7 PLC lib

Anonimista

  • New Member
  • *
  • Posts: 19
Re: Plex/Pyacc example with AST generation
« Reply #2 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!

Leledumbo

  • Hero Member
  • *****
  • Posts: 8747
  • Programming + Glam Metal + Tae Kwon Do = Me
Re: Plex/Pyacc example with AST generation
« Reply #3 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.
« Last Edit: August 29, 2019, 01:03:01 pm by Leledumbo »

Anonimista

  • New Member
  • *
  • Posts: 19
Re: Plex/Pyacc example with AST generation
« Reply #4 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