{"version":3,"file":"case.mjs","names":[],"sources":["../../../src/expression/definitions/case.ts"],"sourcesContent":["import {BooleanType} from '../types';\n\nimport type {Expression} from '../expression';\nimport type {ParsingContext} from '../parsing_context';\nimport type {EvaluationContext} from '../evaluation_context';\nimport type {Type} from '../types';\n\ntype Branches = Array<[Expression, Expression]>;\n\nexport class Case implements Expression {\n    type: Type;\n\n    branches: Branches;\n    otherwise: Expression;\n\n    constructor(type: Type, branches: Branches, otherwise: Expression) {\n        this.type = type;\n        this.branches = branches;\n        this.otherwise = otherwise;\n    }\n\n    static parse(args: ReadonlyArray<unknown>, context: ParsingContext): Expression {\n        if (args.length < 4)\n            return context.error(\n                `Expected at least 3 arguments, but found only ${args.length - 1}.`\n            ) as null;\n        if (args.length % 2 !== 0)\n            return context.error('Expected an odd number of arguments.') as null;\n\n        let outputType: Type;\n        if (context.expectedType && context.expectedType.kind !== 'value') {\n            outputType = context.expectedType;\n        }\n\n        const branches = [];\n        for (let i = 1; i < args.length - 1; i += 2) {\n            const test = context.parse(args[i], i, BooleanType);\n            if (!test) return null;\n\n            const result = context.parse(args[i + 1], i + 1, outputType);\n            if (!result) return null;\n\n            branches.push([test, result]);\n\n            outputType = outputType || result.type;\n        }\n\n        const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n        if (!otherwise) return null;\n\n        if (!outputType) throw new Error(\"Can't infer output type\");\n        return new Case(outputType as any, branches, otherwise);\n    }\n\n    evaluate(ctx: EvaluationContext) {\n        for (const [test, expression] of this.branches) {\n            if (test.evaluate(ctx)) {\n                return expression.evaluate(ctx);\n            }\n        }\n        return this.otherwise.evaluate(ctx);\n    }\n\n    eachChild(fn: (_: Expression) => void) {\n        for (const [test, expression] of this.branches) {\n            fn(test);\n            fn(expression);\n        }\n        fn(this.otherwise);\n    }\n\n    outputDefined(): boolean {\n        return (\n            this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined()\n        );\n    }\n}\n"],"mappings":";;AASA,IAAa,OAAb,MAAa,K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