import { AstCreator, Stmt } from "../ast.ts";
import { AstVisitor, VisitRes, visitStmt, visitStmts } from "../ast_visitor.ts";

export class CompoundAssignDesugarer implements AstVisitor {
    public constructor(private astCreator: AstCreator) {}

    public desugar(stmts: Stmt[]) {
        visitStmts(stmts, this);
    }

    visitAssignStmt(stmt: Stmt): VisitRes {
        if (stmt.kind.type !== "assign") {
            throw new Error();
        }
        switch (stmt.kind.assignType) {
            case "=":
                return;
            case "+=": {
                stmt.kind = {
                    type: "assign",
                    assignType: "=",
                    subject: stmt.kind.subject,
                    value: this.astCreator.expr({
                        type: "binary",
                        binaryType: "+",
                        left: stmt.kind.subject,
                        right: stmt.kind.value,
                    }, stmt.kind.value.pos),
                };
                visitStmt(stmt, this);
                return "stop";
            }
            case "-=": {
                stmt.kind = {
                    type: "assign",
                    assignType: "=",
                    subject: stmt.kind.subject,
                    value: this.astCreator.expr({
                        type: "binary",
                        binaryType: "-",
                        left: stmt.kind.subject,
                        right: stmt.kind.value,
                    }, stmt.kind.value.pos),
                };
                visitStmt(stmt, this);
                return "stop";
            }
        }
    }
}
