JavaScript中的antlr4访问者中的自定义上下文变量

时间:2019-04-12 09:47:11

标签: javascript antlr antlr4 visitor

我想用来自javascript变量的值替换输入中的变量。变量名可能是对象的路径,其中函数位于中间或末尾:object.property.someFunction().propertyOfFunctionResult

其语法如下:

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

variable的访问者功能(涉及customValue的一切正是我想像的如何实现):

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;
}

问题是,我不知道如何将JS变量的当前值传递给解析树。当评估object时,我需要向下传递访问者中的JS对象,以便在下一个visitVariable中,很明显我想返回object.property的值。 任何提示表示赞赏。

1 个答案:

答案 0 :(得分:0)

它可能有点被黑,但是文档中描述的功能getParent()ctx对象中不可用。但是我发现了ctx.parentCtx。现在,我只是分配ctx.customValue = 'somevalue',可以使用ctx.parentCtx.customValue从孩子那里访问它。