javascript 中 antlr4 访问者中的自定义上下文变量
Custom context variables in antlr4 visitor in javascript
我想用 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
中很明显我想要 return object.property
的值.
任何提示表示赞赏。
它可能有点被黑了,但是文档中描述的函数 getParent()
在 ctx
-object 中不可用。但是我发现ctx.parentCtx
。现在我只是分配 ctx.customValue = 'somevalue'
并且可以从 children 和 ctx.parentCtx.customValue
.
访问它
我想用 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
中很明显我想要 return object.property
的值.
任何提示表示赞赏。
它可能有点被黑了,但是文档中描述的函数 getParent()
在 ctx
-object 中不可用。但是我发现ctx.parentCtx
。现在我只是分配 ctx.customValue = 'somevalue'
并且可以从 children 和 ctx.parentCtx.customValue
.