Reputation: 23
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 return this.binaryOperation(this.factor, [TOK_MULTI, TOK_DIVI]) ^ TypeError: Cannot read property 'binaryOperation' of undefined at Parser.term (F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\parser\Parser.ts:69:15) at Parser.binaryOperation (F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\parser\Parser.ts:78:14) at Parser.expression (F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\parser\Parser.ts:73:15) at Parser.parse (F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\parser\Parser.ts:56:21) at Runner.start (F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\lexer\Runner.ts:21:26) at F:\Programming-Files\hello-world\dev-projects\puCpp-programming-language\src\index.ts:25:46 at Interface._onLine (readline.js:306:5) at Interface._line (readline.js:656:8) at Interface._ttyWrite (readline.js:937:14) at Socket.onkeypress (readline.js:184:10)
Upvotes: 2
Views: 34
Reputation: 958
Try explicitly binding your function arguments:
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])
}
Upvotes: 1