Jack Murrow
Jack Murrow

Reputation: 426

How to implement a "return" number with statements in EBNF?

Here is my current grammar:

program         -> stmt-sequence
stmt-sequence   -> statement { TT_NEWLINE statement }
assign-stmt     -> var identifier TT_EQ factor
print-stmt      -> print factor
add-stmt        -> add factor TT_COMMA factor
sub-stmt        -> sub factor TT_COMMA factor
mul-stmt        -> mul factor TT_COMMA factor
div-stmt        -> div factor TT_COMMA factor
factor          -> number | identifier

For my math statements (add-stmt, sub-stmt, mul-stmt, div-stmt), I want those statements to return a number, like as if they were functions.

If you don't understand what I mean by "return", then here is one example:

print add 2, 4

I want for the math statement to be "replaced" with the number, the result of the statement from adding.

print 6

^ Basically, becoming like this.

factor          -> number | identifier | add-stmt | sub-stmt | mul-stmt | div-stmt

I do not know if adding alternations of the math statements in the factor is appropriate.

How can I basically be able allow these math statements to "return" in the EBNF grammar?

Upvotes: 0

Views: 176

Answers (1)

Progman
Progman

Reputation: 19555

The math statements should not contain the return terminal, it's not their part to define the return terminal/statement. Instead you define a new symbol like

return-stmt  -> TT_RETURN expr

After that you define what expr is. It is something which results in a value:

expr         -> factor | add-stmt | sub-stmt | mul-stmt | div-stmt

Be careful in how you define return-stmt and how you use the existing statements/expressions you have. You shouldn't be able to generate text/code like:

return return 4 + return 2 * 3

Upvotes: 1

Related Questions