开发者

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 man开发者_StackOverflow社区ipulation, 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?


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.


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 Learning to write a compiler

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜