class Parser {
private tokens: Array<ITokenized>
private token_index: number;
private current_token: ITokenized | undefined;
constructor(tokens: Array<ITokenized>) {
// console.log(tokens);
this.tokens = tokens
this.token_index = -1;
this.current_token = undefined
this.next()
}
next() {
this.token_index += 1;
if (this.token_index < this.tokens.length) {
this.current_token = this.tokens[this.token_index]
}
return this.current_token
}
public parse(): any {
let result = this.expression();
return result;
}
private factor() {
let token = this.current_token
if ([TOK_INT, TOK_FLOAT].includes(token?.dataType)) {
this.next();
return new NumberNode(token?.value).represent();
}
}
private term() {
return this.binaryOperation(this.factor, [TOK_MULTI, TOK_DIVI])
}
private expression() {
return this.binaryOperation(this.term, [TOK_PLUS, TOK_MINUS])
}
public binaryOperation(func: Function, operator: Array<string>) {
let leftNode, operationToken, rightNode;
leftNode = func()
while (operator.includes(this.current_token?.dataType)) {
operationToken = this.current_token;
this.next();
rightNode = func()
leftNode = new BinaryOperator(leftNode, operationToken?.dataType, rightNode).represent();
}
return leftNode;
}
}
export default Parser;
F:\ Programming-Files \ hello-world \ dev-projects \ puCpp-programming-language \ src \ parser \ Parser.ts:69返回this.binaryOperation(this.factor,[TOK_MULTI,TOK_DIVI])^ TypeError:无法读取未定义的属性“ binaryOperation”在Parser.term(F:\ Programming-Files \ hello-world \ dev-projects \ puCpp-programming-language \ src \ parser \ Parser.ts:69:15)在Parser.binaryOperation(F:\ Programming-Files \ hello-world \ dev-projects \ puCpp-programming-language \ src \ parser \ Parser.ts:78:14)在Parser.expression(F:\ Programming-Files \ hello-world \ dev-projects \ puCpp-programming-language \ src \ parser \ Parser.ts:73:15)在Parser.parse(F:\ Programming-Files \ hello-world \ dev-projects \ puCpp-programming-language \ src \ parser \ Parser.ts:56:21)在Runner.start上(F:\ Programming-Files \ hello-world \ dev-projects \ puCpp-programming-language \ src \ lexer \ Runner.ts:21:26)在F:\ Programming-Files \ hello-world \ dev-projects \ puCpp-programming-language \ src \ index.ts:25:46在Interface._onLine(readline.js:306:5)在Interface._line(readline.js:656:8)在Interface._ttyWrite(readline.js:937:14)在Socket.onkeypress(readline.js:184:10)
尝试显式绑定您的函数参数:
private term() {
return this.binaryOperation(this.factor.bind(this), [TOK_MULTI, TOK_DIVI])
}
private expression() {
return this.binaryOperation(this.term.bind(this), [TOK_PLUS, TOK_MINUS])
}