How to Implement If-Else and Variables in PEG.js Parser?

32 views Asked by At

I need example about write my own parser using pegjs which supports variable declaration as well as if else and print statement like below.

$var = 6.5;
    print ("value is @var");
    if(@var == 6){
    print("wrong");
    }
    else{
    print("correct");
    }

I request you please can you write the grammar with line by line commenting?

P.S: I am a very beginner

I tried the following code but it's not working and I lose my hope

{
  const vars = {};

  function evaluateExpression(expression) {
    return eval(expression.replace(/@(\w+)/g, (match, varName) => vars[varName] || 0));
  }
}

start = statement*

statement = variable_assignment
          / print_statement
          / if_statement

variable_assignment = "$" varName:identifier "=" value:number ";"
{
  vars[varName] = value;
}

print_statement = "print" "(" string:quoted_string ")" ";"
{
  console.log(string);
}

if_statement = "if" condition:expression "{" trueBlock:statement* "}" "else" "{" falseBlock:statement* "}"
{
  if (evaluateExpression(condition) === 1) {
    for (const stmt of trueBlock) {
      stmt;
    }
  } else {
    for (const stmt of falseBlock) {
      stmt;
    }
  }
}

expression = left:identifier op:("==" / "!=" / "===" / "!==" / "<" / "<=" / ">" / ">=") right:expression
{
  return evaluateExpression(left + op + right);
}
/ "(" expr:expression ")"
{
  return expr;
}
/ left:expression "+" right:expression
{
  return evaluateExpression(left + "+" + right);
}
/ left:expression "-" right:expression
{
  return evaluateExpression(left + "-" + right);
}
/ left:expression "*" right:expression
{
  return evaluateExpression(left + "*" + right);
}
/ left:expression "/" right:expression
{
  return evaluateExpression(left + "/" + right);
}
/ number

number "number" = value:[0-9]+
{
  return parseInt(value.join(''));
}

identifier = name:$(letter (letter / digit)*) { return name; }

letter = [a-zA-Z]

digit = [0-9]

quoted_string = '"' string:([^"]*) '"'
{
  return string.join('');
}

0

There are 0 answers