-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathprotofier.ts
552 lines (513 loc) · 18.1 KB
/
protofier.ts
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright 2021 Google Inc. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import {OrderedMap} from 'immutable';
import {create} from '@bufbuild/protobuf';
import * as proto from './vendor/embedded_sass_pb';
import * as utils from './utils';
import {FunctionRegistry} from './function-registry';
import {SassArgumentList} from './value/argument-list';
import {KnownColorSpace, SassColor} from './value/color';
import {SassFunction} from './value/function';
import {ListSeparator, SassList} from './value/list';
import {SassMap} from './value/map';
import {SassNumber} from './value/number';
import {SassString} from './value/string';
import {Value} from './value';
import {sassNull} from './value/null';
import {sassFalse, sassTrue} from './value/boolean';
import {
CalculationInterpolation,
CalculationOperation,
CalculationOperator,
CalculationValue,
SassCalculation,
} from './value/calculations';
import {SassMixin} from './value/mixin';
/**
* A class that converts [Value] objects into protobufs.
*
* A given [Protofier] instance is valid only within the scope of a single
* custom function call.
*/
export class Protofier {
/** All the argument lists returned by `deprotofy()`. */
private readonly argumentLists: SassArgumentList[] = [];
/**
* Returns IDs of all argument lists passed to `deprotofy()` whose keywords
* have been accessed.
*/
get accessedArgumentLists(): number[] {
return this.argumentLists
.filter(list => list.keywordsAccessed)
.map(list => list.id as number);
}
constructor(
/**
* The registry of custom functions that can be invoked by the compiler.
* This is used to register first-class functions so that the compiler may
* invoke them.
*/
private readonly functions: FunctionRegistry<'sync' | 'async'>,
) {}
/** Converts `value` to its protocol buffer representation. */
protofy(value: Value): proto.Value {
const result = create(proto.ValueSchema, {});
if (value instanceof SassString) {
const string = create(proto.Value_StringSchema, {
text: value.text,
quoted: value.hasQuotes,
});
result.value = {case: 'string', value: string};
} else if (value instanceof SassNumber) {
result.value = {case: 'number', value: this.protofyNumber(value)};
} else if (value instanceof SassColor) {
const channels = value.channelsOrNull;
const color = create(proto.Value_ColorSchema, {
channel1: channels.get(0) as number,
channel2: channels.get(1) as number,
channel3: channels.get(2) as number,
alpha: value.isChannelMissing('alpha') ? undefined : value.alpha,
space: value.space,
});
result.value = {case: 'color', value: color};
} else if (value instanceof SassList) {
const list = create(proto.Value_ListSchema, {
separator: this.protofySeparator(value.separator),
hasBrackets: value.hasBrackets,
contents: value.asList.map(element => this.protofy(element)).toArray(),
});
result.value = {case: 'list', value: list};
} else if (value instanceof SassArgumentList) {
if (value.compileContext === this.functions.compileContext) {
const list = create(proto.Value_ArgumentListSchema, {
id: value.id,
});
result.value = {case: 'argumentList', value: list};
} else {
const list = create(proto.Value_ArgumentListSchema, {
separator: this.protofySeparator(value.separator),
contents: value.asList
.map(element => this.protofy(element))
.toArray(),
});
for (const [key, mapValue] of value.keywordsInternal) {
list.keywords[key] = this.protofy(mapValue);
}
result.value = {case: 'argumentList', value: list};
}
} else if (value instanceof SassMap) {
const map = create(proto.Value_MapSchema, {
entries: value.contents.toArray().map(([key, value]) => ({
key: this.protofy(key),
value: this.protofy(value),
})),
});
result.value = {case: 'map', value: map};
} else if (value instanceof SassFunction) {
if (value.id !== undefined) {
if (value.compileContext !== this.functions.compileContext) {
throw utils.compilerError(
`Value ${value} does not belong to this compilation`,
);
}
const fn = create(proto.Value_CompilerFunctionSchema, value);
result.value = {case: 'compilerFunction', value: fn};
} else {
const fn = create(proto.Value_HostFunctionSchema, {
id: this.functions.register(value.callback!),
signature: value.signature!,
});
result.value = {case: 'hostFunction', value: fn};
}
} else if (value instanceof SassMixin) {
if (value.compileContext !== this.functions.compileContext) {
throw utils.compilerError(
`Value ${value} does not belong to this compilation`,
);
}
const mixin = create(proto.Value_CompilerMixinSchema, value);
result.value = {case: 'compilerMixin', value: mixin};
} else if (value instanceof SassCalculation) {
result.value = {
case: 'calculation',
value: this.protofyCalculation(value),
};
} else if (value === sassTrue) {
result.value = {case: 'singleton', value: proto.SingletonValue.TRUE};
} else if (value === sassFalse) {
result.value = {case: 'singleton', value: proto.SingletonValue.FALSE};
} else if (value === sassNull) {
result.value = {case: 'singleton', value: proto.SingletonValue.NULL};
} else {
throw utils.compilerError(`Unknown Value ${value}`);
}
return result;
}
/** Converts `number` to its protocol buffer representation. */
private protofyNumber(number: SassNumber): proto.Value_Number {
return create(proto.Value_NumberSchema, {
value: number.value,
numerators: number.numeratorUnits.toArray(),
denominators: number.denominatorUnits.toArray(),
});
}
/** Converts `separator` to its protocol buffer representation. */
private protofySeparator(separator: ListSeparator): proto.ListSeparator {
switch (separator) {
case ',':
return proto.ListSeparator.COMMA;
case ' ':
return proto.ListSeparator.SPACE;
case '/':
return proto.ListSeparator.SLASH;
case null:
return proto.ListSeparator.UNDECIDED;
default:
throw utils.compilerError(`Unknown ListSeparator ${separator}`);
}
}
/** Converts `calculation` to its protocol buffer representation. */
private protofyCalculation(
calculation: SassCalculation,
): proto.Value_Calculation {
return create(proto.Value_CalculationSchema, {
name: calculation.name,
arguments: calculation.arguments
.map(this.protofyCalculationValue.bind(this))
.toArray(),
});
}
/** Converts a CalculationValue that appears within a `SassCalculation` to
* its protocol buffer representation. */
private protofyCalculationValue(
value: Object,
): proto.Value_Calculation_CalculationValue {
const result = create(proto.Value_Calculation_CalculationValueSchema, {});
if (value instanceof SassCalculation) {
result.value = {
case: 'calculation',
value: this.protofyCalculation(value),
};
} else if (value instanceof CalculationOperation) {
result.value = {
case: 'operation',
value: create(proto.Value_Calculation_CalculationOperationSchema, {
operator: this.protofyCalculationOperator(value.operator),
left: this.protofyCalculationValue(value.left),
right: this.protofyCalculationValue(value.right),
}),
};
} else if (value instanceof CalculationInterpolation) {
result.value = {case: 'interpolation', value: value.value};
} else if (value instanceof SassString) {
result.value = {case: 'string', value: value.text};
} else if (value instanceof SassNumber) {
result.value = {case: 'number', value: this.protofyNumber(value)};
} else {
throw utils.compilerError(`Unknown CalculationValue ${value}`);
}
return result;
}
/** Converts `operator` to its protocol buffer representation. */
private protofyCalculationOperator(
operator: CalculationOperator,
): proto.CalculationOperator {
switch (operator) {
case '+':
return proto.CalculationOperator.PLUS;
case '-':
return proto.CalculationOperator.MINUS;
case '*':
return proto.CalculationOperator.TIMES;
case '/':
return proto.CalculationOperator.DIVIDE;
default:
throw utils.compilerError(`Unknown CalculationOperator ${operator}`);
}
}
/** Converts `value` to its JS representation. */
deprotofy(value: proto.Value): Value {
switch (value.value.case) {
case 'string': {
const string = value.value.value;
return string.text.length === 0
? SassString.empty({quotes: string.quoted})
: new SassString(string.text, {quotes: string.quoted});
}
case 'number': {
return this.deprotofyNumber(value.value.value);
}
case 'color': {
const color = value.value.value;
const channel1 = color.channel1 ?? null;
const channel2 = color.channel2 ?? null;
const channel3 = color.channel3 ?? null;
const alpha = color.alpha ?? null;
const space = color.space as KnownColorSpace;
switch (color.space.toLowerCase()) {
case 'rgb':
case 'srgb':
case 'srgb-linear':
case 'display-p3':
case 'a98-rgb':
case 'prophoto-rgb':
case 'rec2020':
return new SassColor({
red: channel1,
green: channel2,
blue: channel3,
alpha,
space,
});
case 'hsl':
return new SassColor({
hue: channel1,
saturation: channel2,
lightness: channel3,
alpha,
space,
});
case 'hwb':
return new SassColor({
hue: channel1,
whiteness: channel2,
blackness: channel3,
alpha,
space,
});
case 'lab':
case 'oklab':
return new SassColor({
lightness: channel1,
a: channel2,
b: channel3,
alpha,
space,
});
case 'lch':
case 'oklch':
return new SassColor({
lightness: channel1,
chroma: channel2,
hue: channel3,
alpha,
space,
});
case 'xyz':
case 'xyz-d65':
case 'xyz-d50':
return new SassColor({
x: channel1,
y: channel2,
z: channel3,
alpha,
space,
});
default:
throw utils.compilerError(`Unknown color space "${color.space}".`);
}
}
case 'list': {
const list = value.value.value;
const separator = this.deprotofySeparator(list.separator);
if (separator === null && list.contents.length > 1) {
throw utils.compilerError(
`Value.List ${list} can't have an undecided separator because it ` +
`has ${list.contents.length} elements`,
);
}
return new SassList(
list.contents.map(element => this.deprotofy(element)),
{separator, brackets: list.hasBrackets},
);
}
case 'argumentList': {
const list = value.value.value;
const separator = this.deprotofySeparator(list.separator);
if (separator === null && list.contents.length > 1) {
throw utils.compilerError(
`Value.List ${list} can't have an undecided separator because it ` +
`has ${list.contents.length} elements`,
);
}
const result = new SassArgumentList(
list.contents.map(element => this.deprotofy(element)),
OrderedMap(
Object.entries(list.keywords).map(([key, value]) => [
key,
this.deprotofy(value),
]),
),
separator,
list.id,
this.functions.compileContext,
);
this.argumentLists.push(result);
return result;
}
case 'map':
return new SassMap(
OrderedMap(
value.value.value.entries.map(entry => {
const key = entry.key;
if (!key) throw utils.mandatoryError('Value.Map.Entry.key');
const value = entry.value;
if (!value) throw utils.mandatoryError('Value.Map.Entry.value');
return [this.deprotofy(key), this.deprotofy(value)];
}),
),
);
case 'compilerFunction':
return new SassFunction(
value.value.value.id,
this.functions.compileContext,
);
case 'hostFunction':
throw utils.compilerError(
'The compiler may not send Value.host_function.',
);
case 'compilerMixin':
return new SassMixin(
value.value.value.id,
this.functions.compileContext,
);
case 'calculation':
return this.deprotofyCalculation(value.value.value);
case 'singleton':
switch (value.value.value) {
case proto.SingletonValue.TRUE:
return sassTrue;
case proto.SingletonValue.FALSE:
return sassFalse;
case proto.SingletonValue.NULL:
return sassNull;
}
// eslint-disable-next-line no-fallthrough
default:
throw utils.mandatoryError('Value.value');
}
}
/** Converts `number` to its JS representation. */
private deprotofyNumber(number: proto.Value_Number): SassNumber {
return new SassNumber(number.value, {
numeratorUnits: number.numerators,
denominatorUnits: number.denominators,
});
}
/** Converts `separator` to its JS representation. */
private deprotofySeparator(separator: proto.ListSeparator): ListSeparator {
switch (separator) {
case proto.ListSeparator.COMMA:
return ',';
case proto.ListSeparator.SPACE:
return ' ';
case proto.ListSeparator.SLASH:
return '/';
case proto.ListSeparator.UNDECIDED:
return null;
default:
throw utils.compilerError(`Unknown separator ${separator}`);
}
}
/** Converts `calculation` to its Sass representation. */
private deprotofyCalculation(
calculation: proto.Value_Calculation,
): SassCalculation {
switch (calculation.name) {
case 'calc':
if (calculation.arguments.length !== 1) {
throw utils.compilerError(
'Value.Calculation.arguments must have exactly one argument for calc().',
);
}
return SassCalculation.calc(
this.deprotofyCalculationValue(calculation.arguments[0]),
);
case 'clamp':
if (
calculation.arguments.length === 0 ||
calculation.arguments.length > 3
) {
throw utils.compilerError(
'Value.Calculation.arguments must have 1 to 3 arguments for clamp().',
);
}
return SassCalculation.clamp(
this.deprotofyCalculationValue(calculation.arguments[0]),
calculation.arguments.length > 1
? this.deprotofyCalculationValue(calculation.arguments[1])
: undefined,
calculation.arguments.length > 2
? this.deprotofyCalculationValue(calculation.arguments[2])
: undefined,
);
case 'min':
if (calculation.arguments.length === 0) {
throw utils.compilerError(
'Value.Calculation.arguments must have at least 1 argument for min().',
);
}
return SassCalculation.min(
calculation.arguments.map(this.deprotofyCalculationValue),
);
case 'max':
if (calculation.arguments.length === 0) {
throw utils.compilerError(
'Value.Calculation.arguments must have at least 1 argument for max().',
);
}
return SassCalculation.max(
calculation.arguments.map(this.deprotofyCalculationValue),
);
default:
throw utils.compilerError(
`Value.Calculation.name "${calculation.name}" is not a recognized calculation type.`,
);
}
}
/** Converts `value` to its Sass representation. */
private deprotofyCalculationValue(
value: proto.Value_Calculation_CalculationValue,
): CalculationValue {
switch (value.value.case) {
case 'number':
return this.deprotofyNumber(value.value.value);
case 'calculation':
return this.deprotofyCalculation(value.value.value);
case 'string':
return new SassString(value.value.value, {quotes: false});
case 'operation':
return new CalculationOperation(
this.deprotofyCalculationOperator(value.value.value.operator),
this.deprotofyCalculationValue(
value.value.value.left as proto.Value_Calculation_CalculationValue,
),
this.deprotofyCalculationValue(
value.value.value.right as proto.Value_Calculation_CalculationValue,
),
);
case 'interpolation':
return new CalculationInterpolation(value.value.value);
default:
throw utils.mandatoryError('Calculation.CalculationValue.value');
}
}
/** Converts `operator` to its Sass representation. */
private deprotofyCalculationOperator(
operator: proto.CalculationOperator,
): CalculationOperator {
switch (operator) {
case proto.CalculationOperator.PLUS:
return '+';
case proto.CalculationOperator.MINUS:
return '-';
case proto.CalculationOperator.TIMES:
return '*';
case proto.CalculationOperator.DIVIDE:
return '/';
default:
throw utils.compilerError(`Unknown CalculationOperator ${operator}`);
}
}
}