views:

109

answers:

4

I am trying to understand how a language interpreter works. Can you guys point me the general lines on how an interpreter works?

I mean, suppose I have some lines written like this

10  x = 200;
20  for r = x to 1000 step 1
25  z = r + 32;
30  print z;
40  next r;
50  end;

what's the best way to build an interpreter that could run something like that?

Having a large matrix containing all functions allowed and searching for a match? The first line, for example: it is assigning 200 to a variable x, but these are symbols that does not exist.

If you guys can give me the direction...

Thanks for any help.

+1  A: 

Perhaps you are talking about creating a DSL. You might find this helpful (if you are ok with spending $$)

http://gilesbowkett.blogspot.com/2010/03/create-your-own-programming-language.html

rmk
thanks!!!!!!!!!!
Digital Robot
+2  A: 

Compiler creation is a complex topic (an interpreter can be seen as a special compiler).

You have to first parse it - try to understand the syntax and then create some internal representation (abstract syntax tree) and then create some execution logic.

Wikpedia suggests http://mcs.une.edu.au/~comp319/

johannes
thanks!!!!!!!!!!
Digital Robot
An AST is certainly the way to go for a full service compiler or interpreter, but it is *not* required.
dmckee
right an AST isn't needed but some understanding is needed ... at least for the current line/statement.
johannes
+1  A: 

Learn about tools such as lex/flex http://flex.sourceforge.net/ and yacc/bison http://www.gnu.org/software/bison/. These are most popular tools for building compilers in open software world. Many well known open source programs are written using them (including PHP, gcc, doxygen). You'll find a lot of free books and tutorials. They not only show how to use lex and yacc tools, but also explain general ideas behind compilers.

doc
Don't forget ANTLR (http://www.antlr.org/) a tat more sophisticated than lex or bison but quite relevant.
mjv
Yes ANTLR is worth mentioning.
doc
I think lex/yacc is much easier for a beginner.Plus, shift-reduce parsing is a little easier to understand.The OP wants to learn, so maybe lex/yacc is much better for that purpose; I have used both and find that lex/yacc is much better as a beginner.
rmk
+1  A: 

I'm interested in learning more about this as well. I found Douglas Crockford's JavaScript parser interesting, though from what I understand he's using a different method than is typical for parsing languages. It's not the full picture for interpreting and compiling, but I found it helpful to see some actual parsing implementation and the resulting restructuring of the code.

Bob