views:

62

answers:

2

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?
A: 

Firstly, you need to give your language some idea of operator precedence. Then you give the ( operator a very low precedence, and the ) operator a very high one. But this topic is really too complicated for an SO answer - you need to read up on ways of evaluating expressions. Take a look at the SO compiler & interpreter resources at http://stackoverflow.com/questions/1669/learning-to-write-a-compiler

anon
+4  A: 

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.

Dietrich Epp
If he just wants to evaluate expressions, there is no need to construct a tree explicitly. Same if he uses a recursive descent approach for a fuller language - no explicit tree needed.
anon
@Neil: yep, the Dragon book calls it "syntax directed translation"
Eli Bendersky