-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
literal.js
80 lines (66 loc) · 2.5 KB
/
literal.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// @flow
import assert from 'assert';
import { isValue, typeOf, Color } from '../values';
import { Formatted } from './formatted';
import type { Type } from '../types';
import type { Value } from '../values';
import type { Expression } from '../expression';
import type ParsingContext from '../parsing_context';
class Literal implements Expression {
type: Type;
value: Value;
constructor(type: Type, value: Value) {
this.type = type;
this.value = value;
}
static parse(args: Array<mixed>, context: ParsingContext) {
if (args.length !== 2)
return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`);
if (!isValue(args[1]))
return context.error(`invalid value`);
const value = (args[1]: any);
let type = typeOf(value);
// special case: infer the item type if possible for zero-length arrays
const expected = context.expectedType;
if (
type.kind === 'array' &&
type.N === 0 &&
expected &&
expected.kind === 'array' &&
(typeof expected.N !== 'number' || expected.N === 0)
) {
type = expected;
}
return new Literal(type, value);
}
evaluate() {
return this.value;
}
eachChild() {}
possibleOutputs() {
return [this.value];
}
serialize() {
if (this.type.kind === 'array' || this.type.kind === 'object') {
return ["literal", this.value];
} else if (this.value instanceof Color) {
// Constant-folding can generate Literal expressions that you
// couldn't actually generate with a "literal" expression,
// so we have to implement an equivalent serialization here
return ["rgba"].concat(this.value.toArray());
} else if (this.value instanceof Formatted) {
// Constant-folding can generate Literal expressions that you
// couldn't actually generate with a "literal" expression,
// so we have to implement an equivalent serialization here
return this.value.serialize();
} else {
assert(this.value === null ||
typeof this.value === 'string' ||
typeof this.value === 'number' ||
typeof this.value === 'boolean' ||
typeof this.value === 'formatted');
return (this.value: any);
}
}
}
export default Literal;