Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add semiliteral operator for expressions inside arrays and objects #951

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
108 changes: 108 additions & 0 deletions src/expression/definitions/semiliteral.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
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';

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;
Copy link
Author

@sargunv sargunv Dec 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tweaked this because my Semiliteral class is abstract and therefore doesn't have a constructor. If we split semiliteral into two different classes with their own parse like the []/{} proposal, we can revert this line.

} & {
readonly parse: ExpressionParser;
};
Expand Down
22 changes: 20 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,24 @@
}
}
},
"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": {
"js": "https://github.com/maplibre/maplibre-style-spec/issues/950",
"android": "https://github.com/maplibre/maplibre-style-spec/issues/950",
"ios": "https://github.com/maplibre/maplibre-style-spec/issues/950"
}
}
},
"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 +6678,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,25 @@
{
"expression": [
"semiliteral",
[]
],
"inputs": [
[
{},
{
}
]
],
"expected": {
"compiled": {
"result": "success",
"isFeatureConstant": true,
"isZoomConstant": true,
"type": "array<value, 0>"
},
"outputs": [
[
]
]
}
}
22 changes: 22 additions & 0 deletions test/integration/expression/tests/semiliteral/empty/test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"expression": ["semiliteral"],
"inputs": [
[
{
},
{
}
]
],
"expected": {
"compiled": {
"result": "error",
"errors": [
{
"key": "",
"error": "'semiliteral' expression requires exactly one argument, but found 0 instead."
}
]
}
}
}
22 changes: 22 additions & 0 deletions test/integration/expression/tests/semiliteral/extra-arg/test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"expression": ["semiliteral", [], []],
"inputs": [
[
{
},
{
}
]
],
"expected": {
"compiled": {
"result": "error",
"errors": [
{
"key": "",
"error": "'semiliteral' expression requires exactly one argument, but found 2 instead."
}
]
}
}
}
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",
[
["*", 2, 3],
["concat", "x", "y"]
]
],
"inputs": [
[
{},
{}
]
],
"expected": {
"compiled": {
"result": "success",
"isFeatureConstant": true,
"isZoomConstant": true,
"type": "array<value, 2>"
},
"outputs": [
[
6,
"xy"
]
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"expression": [
"semiliteral",
[
"x",
1
]
],
"inputs": [
[
{},
{}
]
],
"expected": {
"compiled": {
"result": "success",
"isFeatureConstant": true,
"isZoomConstant": true,
"type": "array<value, 2>"
},
"outputs": [
[
"x",
1
]
]
}
}
Loading
Loading