Skip to content

Commit

Permalink
feat: add semiliteral operator for expressions inside arrays and objects
Browse files Browse the repository at this point in the history
  • Loading branch information
sargunv committed Dec 22, 2024
1 parent 93a8cd3 commit eac3d59
Show file tree
Hide file tree
Showing 10 changed files with 293 additions and 3 deletions.
1 change: 1 addition & 0 deletions build/generate-style-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ export type ExpressionSpecification =
| ['format', ...(string | ['image', ExpressionSpecification] | ExpressionSpecification | {'font-scale'?: number | ExpressionSpecification, 'text-font'?: string[] | ExpressionSpecification, 'text-color'?: ColorSpecification | ExpressionSpecification})[]] // string
| ['image', unknown | ExpressionSpecification] // image
| ['literal', unknown]
| ['semiliteral', unknown]
| ['number', unknown | ExpressionSpecification, ...(unknown | ExpressionSpecification)[]] // number
| ['number-format', number | ExpressionSpecification, {'locale'?: string | ExpressionSpecification, 'currency'?: string | ExpressionSpecification, 'min-fraction-digits'?: number | ExpressionSpecification, 'max-fraction-digits'?: number | ExpressionSpecification}] // string
| ['object', unknown | ExpressionSpecification, ...(unknown | ExpressionSpecification)[]] // object
Expand Down
2 changes: 2 additions & 0 deletions src/expression/definitions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {ImageExpression} from './image';
import {Length} from './length';
import {Within} from './within';
import {Distance} from './distance';
import {Semiliteral} from './semiliteral';

import type {ExpressionRegistry} from '../expression';

Expand Down Expand Up @@ -59,6 +60,7 @@ export const expressions: ExpressionRegistry = {
'number': Assertion,
'number-format': NumberFormat,
'object': Assertion,
'semiliteral': Semiliteral,
'slice': Slice,
'step': Step,
'string': Assertion,
Expand Down
109 changes: 109 additions & 0 deletions src/expression/definitions/semiliteral.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import {
ObjectType,
ValueType,
array,
} from '../types';

import type {Expression} from '../expression';
import type {ParsingContext} from '../parsing_context';
import type {EvaluationContext} from '../evaluation_context';
import type {Type} from '../types';
import {typeOf, Value, isValue} from '../values';
import {Literal} from './literal';
import exp from 'constants';

Check warning on line 13 in src/expression/definitions/semiliteral.ts

View workflow job for this annotation

GitHub Actions / Code Hygiene

'exp' is defined but never used

export abstract class Semiliteral implements Expression {
type: Type;

constructor(type: Type) {
this.type = type;
}

static parse(args: ReadonlyArray<unknown>, context: ParsingContext): Expression {
if (args.length !== 2)
return context.error(`'semiliteral' expression requires exactly one argument, but found ${args.length - 1} instead.`) as null;

if (!isValue(args[1]))
return context.error('invalid value') as null;

const value = args[1] as Value;
const type = typeOf(value);

if (type.kind === 'array') {
const arr = value as Array<unknown>;
const parsed = arr.map(item => context.parse(item, null, ValueType));
return new ArraySemiliteral(parsed);
} else if (type.kind === 'object') {
const obj = value as Record<string, unknown>;
const parsed = Object.keys(obj).reduce((acc, key) => {
acc[key] = context.parse(obj[key], null, ValueType);
return acc;
}, {} as Record<string, Expression>);
return new ObjectSemiliteral(parsed);
} else {
return new Literal(type, value);
}
}

abstract evaluate(ctx: EvaluationContext): Value;

abstract eachChild(fn: (_: Expression) => void): void;

abstract outputDefined(): boolean;
}

class ArraySemiliteral extends Semiliteral {
arr: Array<Expression>;

constructor(arr: Array<Expression>) {
let elementType: Type | null = null;
for (const expr of arr) {
if (!elementType) {
elementType = expr.type;
} else if (elementType === expr.type) {
continue;
} else {
elementType = ValueType;
break;
}
}
super(array(elementType ?? ValueType, arr.length));
this.arr = arr;
}

evaluate(ctx: EvaluationContext): Array<Value> {
return this.arr.map(arg => arg.evaluate(ctx));
}

eachChild(fn: (_: Expression) => void) {
this.arr.forEach(fn);
}

outputDefined() {
return this.arr.every(arg => arg.outputDefined());
}
}

class ObjectSemiliteral extends Semiliteral {
obj: Record<string, Expression>;

constructor(obj: Record<string, Expression>) {
super(ObjectType);
this.obj = obj;
}

evaluate(ctx: EvaluationContext): Record<string, Value> {
return Object.keys(this.obj).reduce((acc, key) => {
acc[key] = this.obj[key].evaluate(ctx);
return acc;
}, {} as Record<string, Value>);
}

eachChild(fn: (_: Expression) => void) {
Object.values(this.obj).forEach(fn);
}

outputDefined() {
return Object.values(this.obj).every(arg => arg.outputDefined());
}
}
2 changes: 1 addition & 1 deletion src/expression/expression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export interface Expression {

export type ExpressionParser = (args: ReadonlyArray<unknown>, context: ParsingContext) => Expression;
export type ExpressionRegistration = {
new (...args: any): Expression;
prototype: Expression;
} & {
readonly parse: ExpressionParser;
};
Expand Down
19 changes: 17 additions & 2 deletions src/reference/v8.json
Original file line number Diff line number Diff line change
Expand Up @@ -2830,7 +2830,7 @@
}
},
"literal": {
"doc": "Provides a literal array or object value.\n\n - [Display and style rich text labels](https://maplibre.org/maplibre-gl-js/docs/examples/display-and-style-rich-text-labels/)",
"doc": "Provides a literal array or object value, treating nested values as literals themselves.\n\n - [Display and style rich text labels](https://maplibre.org/maplibre-gl-js/docs/examples/display-and-style-rich-text-labels/)",
"example": {
"syntax": {
"method": ["JSON object or array"],
Expand All @@ -2847,6 +2847,21 @@
}
}
},
"semiliteral": {
"doc": "Provides an array or object value, evaluating expressions in the elements of the array or values of the object.",
"example": {
"syntax": {
"method": ["JSON object or array"],
"result": "array | object"
},
"value": ["semiliteral",[["get", "label_x"], ["get", "label_y"]]]
},
"group": "Types",
"sdk-support": {
"basic functionality": {
}
}
},
"array": {
"doc": "Asserts that the input is an array (optionally with a specific item type and length). If, when the input expression is evaluated, it is not of the asserted type, then this assertion will cause the whole expression to be aborted.",
"example": {
Expand Down Expand Up @@ -6660,4 +6675,4 @@
"doc": "A name of a feature property to use as ID for feature state."
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"expression": [
"semiliteral",
[
["round", ["*", ["cos", ["get", "direction"]], ["get", "magnitude"]]],
["round", ["*", ["sin", ["get", "direction"]], ["get", "magnitude"]]]
]
],
"inputs": [
[
{
},
{
"properties": {
"direction": 0,
"magnitude": 10
}
}
]
],
"expected": {
"compiled": {
"result": "success",
"isFeatureConstant": false,
"isZoomConstant": true,
"type": "array<number, 2>"
},
"outputs": [
[
10,
0
]
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"expression": [
"semiliteral",
[
["number", ["get", "x"]],
["number", ["get", "y"]]
]
],
"inputs": [
[
{},
{
"properties": {
"x": 1,
"y": 2
}
}
]
],
"expected": {
"compiled": {
"result": "success",
"isFeatureConstant": false,
"isZoomConstant": true,
"type": "array<number, 2>"
},
"outputs": [
[
1,
2
]
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"expression": [
"semiliteral",
[
1,
2
]
],
"inputs": [
[
{},
{}
]
],
"expected": {
"compiled": {
"result": "success",
"isFeatureConstant": true,
"isZoomConstant": true,
"type": "array<number, 2>"
},
"outputs": [
[
1,
2
]
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"expression": [
"let",
"dp_per_em",
12,
[
"semiliteral",
[
["/", 6, ["var", "dp_per_em"]],
["/", 18, ["var", "dp_per_em"]]
]
]
],
"inputs": [
[
{
},
{
}
]
],
"expected": {
"compiled": {
"result": "success",
"isFeatureConstant": true,
"isZoomConstant": true,
"type": "array<number, 2>"
},
"outputs": [
[
0.5,
1.5
]
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"expression": [
"semiliteral",
[
"x",
"y"
]
],
"inputs": [
[
{},
{}
]
],
"expected": {
"compiled": {
"result": "success",
"isFeatureConstant": true,
"isZoomConstant": true,
"type": "array<string, 2>"
},
"outputs": [
[
"x",
"y"
]
]
}
}

0 comments on commit eac3d59

Please sign in to comment.