views:

166

answers:

1

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.

+3  A: 

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