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

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

    public desugar(items: Item[]) {
        visitItems(items, 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";
            }
        }
    }
}