A for statement in PyJ has the syntax:
<for statement> ::= “for” <identifier> “=” <expression> “:” <expression> <statement>+ “end”
Once again, we know that a for statement is coming because the current symbol is forSy, which is to say that we say the identifier “for.” Recall that each non-terminal is implemented by a function in the parser, so in this case we require the functions identifier, expression, and statement. The basic code is as follows:
Error detection in this parser is lacking, because that takes a large amount of error unrelated to the basic task. If the for is not followed by an identifier, then an error will be indicated. There are many others that could have been tested for.
This code is only a parser, though. In the real language, there are code generation and other issues. This is a pretty simple for statement as languages go. There are semantic (meaning) issues that should be addressed, but that are not related to parsing. Here is the final code for the for loop with the code generation:
Error detection in this parser is lacking, because that takes a large amount of error unrelated to the basic task. If the for is not followed by an identifier, then an error will be indicated. There are many others that could have been tested for.
This code is only a parser, though. In the real language, there are code gen-eration and other issues. This is a pretty simple for statement as languages go.
There are semantic (meaning) issues that should be addressed, but that are not related to parsing. Here is the final code for the for loop with the code generation:
if sy == forSy: # FOR statement
sy = nextSy()
if sy == identSy: # Loop control variable
defineIdent(ident, FLOAT) # define it – symbol
# table stuff
lcvr = ident # remember it
sy = nextSy() # skip it
if sy == assignSy: # Equals, skip
sy = nextSy()
lcv = convertIdent(ident) # symbol table stuff
gen1n(“for (“+lcv+”=”)
expression() # Start value
gen1n(“; “+lcv+”<=”) # Terminal condition
if sy == colonSy: # : skip it
sy = nextSy()
expression()
gen1(“; “+lcv+”=”+lcv+”+1) {“) # Increment
while sy != endSy: # Statements until
# the END
statement()
sy = nextSy()
gen1(“}”)
undefine(lcvr) # symbol table stuff
else:
println(“Syntax error in FOR”)
The PyJ for loop vs. the C for loop is as follows:
Here’s how that translates:
There are places in the commentary where it references the “symbol table.” That is where we look up user defined symbols to see it they are defined and what they are. In PyJ, a symbol can be defined or not. If defined, it can be a floating point number or a function. A for loop control variable is defined in the for statement and is undefined at the end of the loop, so that it cannot be used outside of the loop.
Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.