{"version":3,"file":"parsing_context.mjs","names":[],"sources":["../../src/expression/parsing_context.ts"],"sourcesContent":["import {Scope} from './scope';\nimport {checkSubtype} from './types';\nimport {ExpressionParsingError} from './parsing_error';\nimport {Literal} from './definitions/literal';\nimport {Assertion} from './definitions/assertion';\nimport {Coercion} from './definitions/coercion';\nimport {EvaluationContext} from './evaluation_context';\n\nimport type {Expression, ExpressionRegistry} from './expression';\nimport type {Type} from './types';\n\n/**\n * State associated parsing at a given point in an expression tree.\n * @private\n */\nexport class ParsingContext {\n    registry: ExpressionRegistry;\n    path: Array<number>;\n    readonly key: string;\n    scope: Scope;\n    errors: Array<ExpressionParsingError>;\n\n    // The expected type of this expression. Provided only to allow Expression\n    // implementations to infer argument types: Expression#parse() need not\n    // check that the output type of the parsed expression matches\n    // `expectedType`.\n    expectedType: Type;\n\n    /**\n     * Internal delegate to inConstant function to avoid circular dependency to CompoundExpression\n     */\n    private _isConstant: (expression: Expression) => boolean;\n\n    constructor(\n        registry: ExpressionRegistry,\n        isConstantFunc: (expression: Expression) => boolean,\n        path: Array<number> = [],\n        expectedType?: Type | null,\n        scope: Scope = new Scope(),\n        errors: Array<ExpressionParsingError> = []\n    ) {\n        this.registry = registry;\n        this.path = path;\n        this.key = path.map((part) => `[${part}]`).join('');\n        this.scope = scope;\n        this.errors = errors;\n        this.expectedType = expectedType;\n        this._isConstant = isConstantFunc;\n    }\n\n    /**\n     * @param expr the JSON expression to parse\n     * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed\n     * @param options\n     * @param options.omitTypeAnnotations set true to omit inferred type annotations.  Caller beware: with this option set, the parsed expression's type will NOT satisfy `expectedType` if it would normally be wrapped in an inferred annotation.\n     * @private\n     */\n    parse(\n        expr: unknown,\n        index?: number,\n        expectedType?: Type | null,\n        bindings?: Array<[string, Expression]>,\n        options: {\n            typeAnnotation?: 'assert' | 'coerce' | 'omit';\n        } = {}\n    ): Expression {\n        if (index != null) {\n            return this.concat(index, expectedType, bindings)._parse(expr, options);\n        }\n        return this._parse(expr, options);\n    }\n\n    _parse(\n        expr: unknown,\n        options: {\n            typeAnnotation?: 'assert' | 'coerce' | 'omit';\n        }\n    ): Expression {\n        if (\n            expr === null ||\n            typeof expr === 'string' ||\n            typeof expr === 'boolean' ||\n            typeof expr === 'number'\n        ) {\n            expr = ['literal', expr];\n        }\n\n        const key = this.key;\n        function annotate(parsed, type, typeAnnotation: 'assert' | 'coerce' | 'omit') {\n            if (typeAnnotation === 'assert') {\n                return new Assertion(type, [parsed], key);\n            } else if (typeAnnotation === 'coerce') {\n                return new Coercion(type, [parsed], key);\n            } else {\n                return parsed;\n            }\n        }\n\n        if (Array.isArray(expr)) {\n            if (expr.length === 0) {\n                return this.error(\n                    'Expected an array with at least one element. If you wanted a literal array, use [\"literal\", []].'\n                ) as null;\n            }\n\n            const op = expr[0];\n            if (typeof op !== 'string') {\n                this.error(\n                    `Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use [\"literal\", [...]].`,\n                    0\n                );\n                return null;\n            }\n\n            const Expr = this.registry[op];\n            if (Expr) {\n                let parsed = Expr.parse(expr, this);\n                if (!parsed) return null;\n\n                if (this.expectedType) {\n                    const expected = this.expectedType;\n                    const actual = parsed.type;\n\n                    // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion.\n                    // When we expect a color or formatted string, but have a string or value, wrap it in a coercion.\n                    // Otherwise, we do static type-checking.\n                    //\n                    // These behaviors are overridable for:\n                    //   * The \"coalesce\" operator, which needs to omit type annotations.\n                    //   * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion.\n                    //\n                    if (\n                        (expected.kind === 'string' ||\n                            expected.kind === 'number' ||\n                            expected.kind === 'boolean' ||\n                            expected.kind === 'object' ||\n                            expected.kind === 'array') &&\n                        actual.kind === 'value'\n                    ) {\n                        parsed = annotate(parsed, expected, options.typeAnnotation || 'assert');\n                    } else if (\n                        ('projectionDefinition' === expected.kind &&\n                            ['string', 'array', 'value'].includes(actual.kind)) ||\n                        (['color', 'formatted', 'resolvedImage'].includes(expected.kind) &&\n                            ['value', 'string'].includes(actual.kind)) ||\n                        (['padding', 'numberArray'].includes(expected.kind) &&\n                            ['value', 'number', 'array'].includes(actual.kind)) ||\n                        ('colorArray' === expected.kind &&\n                            ['value', 'string', 'array'].includes(actual.kind)) ||\n                        ('variableAnchorOffsetCollection' === expected.kind &&\n                            ['value', 'array'].includes(actual.kind))\n                    ) {\n                        parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce');\n                    } else if (this.checkSubtype(expected, actual)) {\n                        return null;\n                    }\n                }\n\n                // If an expression's arguments are all literals, we can evaluate\n                // it immediately and replace it with a literal value in the\n                // parsed/compiled result. Expressions that expect an image should\n                // not be resolved here so we can later get the available images.\n                if (\n                    !(parsed instanceof Literal) &&\n                    parsed.type.kind !== 'resolvedImage' &&\n                    this._isConstant(parsed)\n                ) {\n                    const ec = new EvaluationContext();\n                    try {\n                        parsed = new Literal(parsed.type, parsed.evaluate(ec));\n                    } catch (e) {\n                        this.error(e.message);\n                        return null;\n                    }\n                }\n\n                return parsed;\n            }\n\n            return this.error(\n                `Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`,\n                0\n            ) as null;\n        } else if (typeof expr === 'undefined') {\n            return this.error(\"'undefined' value invalid. Use null instead.\") as null;\n        } else if (typeof expr === 'object') {\n            return this.error('Bare objects invalid. Use [\"literal\", {...}] instead.') as null;\n        } else {\n            return this.error(`Expected an array, but found ${typeof expr} instead.`) as null;\n        }\n    }\n\n    /**\n     * Returns a copy of this context suitable for parsing the subexpression at\n     * index `index`, optionally appending to 'let' binding map.\n     *\n     * Note that `errors` property, intended for collecting errors while\n     * parsing, is copied by reference rather than cloned.\n     * @private\n     */\n    concat(index: number, expectedType?: Type | null, bindings?: Array<[string, Expression]>) {\n        const path = typeof index === 'number' ? this.path.concat(index) : this.path;\n        const scope = bindings ? this.scope.concat(bindings) : this.scope;\n        return new ParsingContext(\n            this.registry,\n            this._isConstant,\n            path,\n            expectedType || null,\n            scope,\n            this.errors\n        );\n    }\n\n    /**\n     * Push a parsing (or type checking) error into the `this.errors`\n     * @param error The message\n     * @param keys Optionally specify the source of the error at a child\n     * of the current expression at `this.key`.\n     * @private\n     */\n    error(error: string, ...keys: Array<number>) {\n        const key = `${this.key}${keys.map((k) => `[${k}]`).join('')}`;\n        this.errors.push(new ExpressionParsingError(key, error));\n    }\n\n    /**\n     * Returns null if `t` is a subtype of `expected`; otherwise returns an\n     * error message and also pushes it to `this.errors`.\n     * @param expected The expected type\n     * @param t The actual type\n     * @returns null if `t` is a subtype of `expected`; otherwise returns an error message\n     */\n    checkSubtype(expected: Type, t: Type): string {\n        const error = checkSubtype(expected, t);\n        if (error) this.error(error);\n        return error;\n    }\n}\n"],"mappings":";;;;;;;;;;;;AAeA,IAAa,iBAAb,MAAa,eAAe;CAkBxB,YACI,UACA,gBACA,OAAsB,CAAC,GACvB,cACA,QAAe,IAAI,MAAM,GACzB,SAAwC,CAAC,GAC3C;EACE,KAAK,WAAW;EAChB,KAAK,OAAO;EACZ,KAAK,MAAM,KAAK,KAAK,SAAS,IAAI,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE;EAClD,KAAK,QAAQ;EACb,KAAK,SAAS;EACd,KAAK,eAAe;EACpB,KAAK,cAAc;CACvB;;;;;;;;CASA,MACI,MACA,OACA,cACA,UACA,UAEI,CAAC,GACK;EACV,IAAI,SAAS,MACT,OAAO,KAAK,OAAO,OAAO,cAAc,QAAQ,CAAC,CAAC,OAAO,MAAM,OAAO;EAE1E,OAAO,KAAK,OAAO,MAAM,OAAO;CACpC;CAEA,OACI,MACA,SAGU;EACV,IACI,SAAS,QACT,OAAO,SAAS,YAChB,OAAO,SAAS,aAChB,OAAO,SAAS,UAEhB,OAAO,CAAC,WAAW,IAAI;EAG3B,MAAM,MAAM,KAAK;EACjB,SAAS,SAAS,QAAQ,MAAM,gBAA8C;GAC1E,IAAI,mBAAmB,UACnB,OAAO,IAAI,UAAU,MAAM,CAAC,MAAM,GA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