0

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

Chris
  • 514
  • 6
  • 22

1 Answers1

1

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() "
               ]
            ]
         }
      ]
   }
Bob
  • 13,867
  • 1
  • 5
  • 27
  • Sorry about the vagueness. What you've given above has given me a good starting point. Basically I wanted to do is actively check if x === y, then run the function. The use case is a roundabout way to write some javascript inside json. If the expression is valid, some global function can be called. – Chris Jul 06 '21 at 17:45
  • The [JavaScript example](https://github.com/peggyjs/peggy/blob/main/examples/javascript.pegjs) will give you some more ideas to work with. – Joe Hildebrand Nov 29 '21 at 21:02