What is the most optimal way to create an if statement, or logic in general, in Nearley?

43 views Asked by At

Using the Nearley module for NodeJS I want to create an if statement that looks like this:

if condition: /* code */ endif;

And so in Nearley, I wrote:

# grammar.ne
@builtin "whitespace.ne"

# Condition -> etc etc

IfStatement -> "if" __ Condition __ ":" (_ Logic:*):? __ "endif;"

I don't know what to define Logic as. I want it to be used to describe any instance of variable declaration, an if statement (so probably using recursion, but I don't know how), or calling a function.

Note that my project is not intended to be primarily a scripting language. I'm drifting it towards the style of Infocom's ZIL. Logic as mentioned above can only be used in a function, so it would look like this:

(FunctionName OptionalParameter1 OptionalParameter2)
<Logic>
[Conclude]

/* Example:
 * (AddDigits x y z)
 * <set a = x + y + z;
 * return a;>
 * [Conclude]
 *
 * Functions begin with a header including its Name and Parameters (if any);
 * They include any code encased with <>;
 * They end with the [Conclude] tag.
 */
ConcludeTag -> "[Conclude]"
FunctionDeclare -> FunctionHeader "\n" FunctionBody ConcludeTag
FunctionHeader -> "(" [a-zA-Z0-9_]:* ((__ [a-zA-Z0-9_]:*):*):? ")" 
FunctionBody -> # Logic needs to be defined first!!

My intial idea was to use recursion. However I am unsure if this is a good or even valid method. I wrote this:

# Define integers, strings and booleans as valid Value types
Value -> [0-9]:* 
       | "\"" . "\""
       | ("true" | "false")

# Define an extended Value type as anything listed above PLUS function calling e.g. myfunc()
ExtendedValue -> Value
               | [a-zA-Z0-9_]:* _ "(" (_ (Value | (Value "," _):* Value) _):? ")"

# I stopped here because I was stuck. There might be more to add but I do not know yet
Logic -> IfStatement 
       | [a-zA-Z0-9_]:* _ "=" _ ExtendedValue _ ";"
0

There are 0 answers