3

I have developed a interpreted programming language. It is strongly based on C. The problem is, I want to add a foreach directive and have no clue how to.

I am using Bison and Flex as the parser and lexer generator.

Lesmana
  • 25,663
  • 9
  • 82
  • 87
The Big Spark
  • 327
  • 1
  • 4
  • 8
  • 1
    Your language will need to support the ability to get a containers size simply knowing the containers name. In C, arrays do not carry their size with them. So your language needs to make sure it supports this first. – GManNickG Sep 10 '09 at 21:34
  • General compiler (and interpreter) resources: http://stackoverflow.com/questions/1669/learning-to-write-a-compiler – dmckee --- ex-moderator kitten Sep 11 '09 at 03:33

1 Answers1

4

In your grammar, you'd want an expression that is something like the following:

foreach := foreach ( name in name ) { statements }

When you parse this, you should be able to translate it directly into a while loop in your AST with an additional statement that assigns a variable at the beginning.

This seems to me the simplest way to do it, but will probably have limitations with multiple iterable data-types (e.g. a list vs. an array). In this case, you may want to consider consolidating all iterables so that they have a consistent method to obtain the next element.

Fragsworth
  • 33,919
  • 27
  • 84
  • 97