1
votes

I want to replace variables in an input with it's value from javascript variables. It's possible that the variable name is a path of an object with functions in the middle or at the end: object.property.someFunction().propertyOfFunctionResult.

The grammar for this looks like:

funParameter: '(' value? (', ' value)*  ')' ;
value: INT | BOOL | STRING | variable;
varname: VAR ;
variable: (varname | '{' value '}') funParameter? ('.' variable)* ;

The visitor-function for variable (everything involving customValue is just how I would imagine how to do it):

visitVariable(ctx) {
  var key, val;
  if(ctx.value()) {
    key = this.visit(ctx.value());
  } else if(ctx.varname()) {
    key = ctx.varname().getText();
  }
  if(ctx.funParameter()) {
    //idea:
    val = this.callFunction(key, this.visit(ctx.funParameter()), ctx.customValue); //pass value to function call
  } else {
    //idea:
    if(ctx.customValue) {
      val = ctx.customValue[key]; //Get value from parent
    } else {
      val = this.vars[key]; //Get value from JS-variables
    }
  }
  if(ctx.variable()) {
     //idea:
    val = this.visit(ctx.variable(), {customValue:val});
  } 
  return val;
}

The problem is, that I don't know how to pass the current value of the JS-variable down the parse tree. When object is evaluated I would need to pass the JS-object in the visitor down so that in the next visitVariable it's clear that I want to return the value of object.property. Any hints are appreciated.

1

1 Answers

0
votes

It's probably kind of hacked, but the function getParent(), that is described in the docs, was not available in the ctx-object. But I found ctx.parentCtx. Now I'm just assigning ctx.customValue = 'somevalue' and can access it from the children with ctx.parentCtx.customValue.