Search code examples
phpparsingprogramming-languagesinterpreterlanguage-design

Statement hierarchy in programming languages


I quickly wrote an interpreter for some sort of experimental programing language i came up with, in PHP (yes, in PHP). The language itself doesn't have anything really special, I just wanted to give it a try.

I got the basic things working (Hello World, input to output, string manipulation, arithmetics) but I'm getting stuck with the management of blocks and grouped statements.

What I mean is: PHP and most other languages let you do this: ((2+2)*(8+2)+2), of course not only with mathematical computations.

My program structure currently consists of a multidimensional array built like this:

ID => Type (Identifier, String, Int, Newline, EOF, Comma, ...)
      Contents (If identifier, int or string)
  • How could I allow statements to be executed in a defined order like in the PHP example above?

Solution

  • I suggest reading an introductory article or book on writing compilers / interpreters. There are a number of excellent books and articles on the subject online and at the library. I'd give links, but I don't know what your background is.

    In general, the first step of making an interpreter is to use a tree structure (not an array). Example:

            +
           / \
          *   2
        /   \
      +       +
     / \     / \
    2   2   8   2
    

    This part is more or less the same no matter what language you're using and what language you're trying to parse. From there, you can directly evaluate the tree or you can transform it into a different structure.