Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a foreach keyword with yacc or Bison and Flex

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.

like image 426
The Big Spark Avatar asked Nov 25 '25 02:11

The Big Spark


1 Answers

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.

like image 157
Fragsworth Avatar answered Nov 27 '25 17:11

Fragsworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!