diff --git a/packages/interpreter/src/components/visitor/assignmentExpression.ts b/packages/interpreter/src/components/visitor/assignmentExpression.ts index 8fc09cf7..cb21aeca 100644 --- a/packages/interpreter/src/components/visitor/assignmentExpression.ts +++ b/packages/interpreter/src/components/visitor/assignmentExpression.ts @@ -1,50 +1,50 @@ import Visitor from "."; import { ASTNode } from "bhai-lang-parser"; - import InvalidStateException from "../../exceptions/invalidStateException"; import NallaPointerException from "../../exceptions/nallaPointerException"; import RuntimeException from "../../exceptions/runtimeException"; import { getOperationValue } from "../../helpers"; import InterpreterModule from "../../module/interpreterModule"; - export default class AssignmentExpression implements Visitor { visitNode(node: ASTNode) { - if (!node.left) + this.validateNode(node); + + const identifier = node.left.name; + const value = node.right + ? InterpreterModule.getVisitor(node.right.type).visitNode(node.right) + : undefined; + + this.handleAssignment(identifier, node.operator, value); + + return InterpreterModule.getCurrentScope().get(identifier); + } + + private validateNode(node: ASTNode) { + if (!node.left) { throw new InvalidStateException( - `left node not present while executing: ${node.type}` + `Left node not present while executing: ${node.type}` ); + } + } - let identifier = node.left.name; - let value: unknown; + private handleAssignment(identifier: string, operator: string, value: unknown) { const currentScope = InterpreterModule.getCurrentScope(); + const currentValue = currentScope.get(identifier); - if (node.right) { - value = InterpreterModule.getVisitor(node.right.type).visitNode( - node.right + if (currentValue === null && operator !== "=") { + throw new NallaPointerException( + `Nalla operand ni jamta "${operator}" ke sath` ); } - if (identifier && node.operator) { - const left = currentScope.get(identifier); - - if (left === null && node.operator !== "=") - throw new NallaPointerException( - `Nalla operand ni jamta "${node.operator}" ke sath` - ); - - if ((left === true || left === false) && node.operator !== "=") - throw new RuntimeException( - `Boolean operand ni jamta "${node.operator}" ke sath` - ); - - const newValue = getOperationValue( - { left: currentScope.get(identifier), right: value }, - node.operator + if ((currentValue === true || currentValue === false) && operator !== "=") { + throw new RuntimeException( + `Boolean operand ni jamta "${operator}" ke sath` ); - currentScope.assign(identifier, newValue); - - return currentScope.get(identifier); } + + const newValue = getOperationValue({ left: currentValue, right: value }, operator); + currentScope.assign(identifier, newValue); } }