Reputation: 514
Trying to parse a single line conditional where code tries to test the left hand is equal to the right hand.
{
user = {id: 'abc123'}
function_name() {...}
}
if (user.id === 'abc123...') { function_name() }
I've so far looked at these posts PEG-php parsing if statement and How to describe conditional statement (if-then-else) using PEG
PEG syntax is very alien to me, and I'm sure if it's even the right methodology for my needs. Might be overkill.
Currently using peg.js/peggy.js
Upvotes: 0
Views: 465
Reputation: 14664
Your question is very vague, I will try to give you a starting point,
this is a grammar that would consume your example intput.
Code = (Condition / Curly / Statement)+
Curly = '{' code: Code+ '}' { return {nested: code}}
Statement = $([^{}]+)
Condition = _ 'if' _ '(' lhs:term '===' rhs:term ')' _ body: Code {
return {condition: {lhs, rhs}, body}
}
term = $[^{}()=]+
_ "whitespace"
= [ \t\n\r]*
For the condition part it will produce
{
"condition": {
"lhs": "user.id ",
"rhs": " 'abc123...'"
},
"body": [
{
"nested": [
[
" function_name() "
]
]
}
]
}
Upvotes: 1