-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathparser.js
2596 lines (2308 loc) · 97.7 KB
/
parser.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
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import LessError from '../less-error';
import tree from '../tree';
import visitors from '../visitors';
import getParserInput from './parser-input';
import * as utils from '../utils';
import functionRegistry from '../functions/function-registry';
import { ContainerSyntaxOptions, MediaSyntaxOptions } from '../tree/atrule-syntax';
import logger from '../logger';
import Selector from '../tree/selector';
import Anonymous from '../tree/anonymous';
//
// less.js - parser
//
// A relatively straight-forward predictive parser.
// There is no tokenization/lexing stage, the input is parsed
// in one sweep.
//
// To make the parser fast enough to run in the browser, several
// optimization had to be made:
//
// - Matching and slicing on a huge input is often cause of slowdowns.
// The solution is to chunkify the input into smaller strings.
// The chunks are stored in the `chunks` var,
// `j` holds the current chunk index, and `currentPos` holds
// the index of the current chunk in relation to `input`.
// This gives us an almost 4x speed-up.
//
// - In many cases, we don't need to match individual tokens;
// for example, if a value doesn't hold any variables, operations
// or dynamic references, the parser can effectively 'skip' it,
// treating it as a literal.
// An example would be '1px solid #000' - which evaluates to itself,
// we don't need to know what the individual components are.
// The drawback, of course is that you don't get the benefits of
// syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
// and a smaller speed-up in the code-gen.
//
//
// Token matching is done with the `$` function, which either takes
// a terminal string or regexp, or a non-terminal function to call.
// It also takes care of moving all the indices forwards.
//
const Parser = function Parser(context, imports, fileInfo, currentIndex) {
currentIndex = currentIndex || 0;
let parsers;
const parserInput = getParserInput();
function error(msg, type) {
throw new LessError(
{
index: parserInput.i,
filename: fileInfo.filename,
type: type || 'Syntax',
message: msg
},
imports
);
}
/**
*
* @param {string} msg
* @param {number} index
* @param {string} type
*/
function warn(msg, index, type) {
if (!context.quiet) {
logger.warn(
(new LessError(
{
index: index ?? parserInput.i,
filename: fileInfo.filename,
type: type ? `${type.toUpperCase()} WARNING` : 'WARNING',
message: msg
},
imports
)).toString()
);
}
}
function expect(arg, msg) {
// some older browsers return typeof 'function' for RegExp
const result = (arg instanceof Function) ? arg.call(parsers) : parserInput.$re(arg);
if (result) {
return result;
}
error(msg || (typeof arg === 'string'
? `expected '${arg}' got '${parserInput.currentChar()}'`
: 'unexpected token'));
}
// Specialization of expect()
function expectChar(arg, msg) {
if (parserInput.$char(arg)) {
return arg;
}
error(msg || `expected '${arg}' got '${parserInput.currentChar()}'`);
}
function getDebugInfo(index) {
const filename = fileInfo.filename;
return {
lineNumber: utils.getLocation(index, parserInput.getInput()).line + 1,
fileName: filename
};
}
/**
* Used after initial parsing to create nodes on the fly
*
* @param {String} str - string to parse
* @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
* @param {Number} currentIndex - start number to begin indexing
* @param {Object} fileInfo - fileInfo to attach to created nodes
*/
function parseNode(str, parseList, callback) {
let result;
const returnNodes = [];
const parser = parserInput;
try {
parser.start(str, false, function fail(msg, index) {
callback({
message: msg,
index: index + currentIndex
});
});
for (let x = 0, p; (p = parseList[x]); x++) {
result = parsers[p]();
returnNodes.push(result || null);
}
const endInfo = parser.end();
if (endInfo.isFinished) {
callback(null, returnNodes);
}
else {
callback(true, null);
}
} catch (e) {
throw new LessError({
index: e.index + currentIndex,
message: e.message
}, imports, fileInfo.filename);
}
}
//
// The Parser
//
return {
parserInput,
imports,
fileInfo,
parseNode,
//
// Parse an input string into an abstract syntax tree,
// @param str A string containing 'less' markup
// @param callback call `callback` when done.
// @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
//
parse: function (str, callback, additionalData) {
let root;
let err = null;
let globalVars;
let modifyVars;
let ignored;
let preText = '';
// Optionally disable @plugin parsing
if (additionalData && additionalData.disablePluginRule) {
parsers.plugin = function() {
var dir = parserInput.$re(/^@plugin?\s+/);
if (dir) {
error('@plugin statements are not allowed when disablePluginRule is set to true');
}
}
}
globalVars = (additionalData && additionalData.globalVars) ? `${Parser.serializeVars(additionalData.globalVars)}\n` : '';
modifyVars = (additionalData && additionalData.modifyVars) ? `\n${Parser.serializeVars(additionalData.modifyVars)}` : '';
if (context.pluginManager) {
const preProcessors = context.pluginManager.getPreProcessors();
for (let i = 0; i < preProcessors.length; i++) {
str = preProcessors[i].process(str, { context, imports, fileInfo });
}
}
if (globalVars || (additionalData && additionalData.banner)) {
preText = ((additionalData && additionalData.banner) ? additionalData.banner : '') + globalVars;
ignored = imports.contentsIgnoredChars;
ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
ignored[fileInfo.filename] += preText.length;
}
str = str.replace(/\r\n?/g, '\n');
// Remove potential UTF Byte Order Mark
str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
imports.contents[fileInfo.filename] = str;
// Start with the primary rule.
// The whole syntax tree is held under a Ruleset node,
// with the `root` property set to true, so no `{}` are
// output. The callback is called when the input is parsed.
try {
parserInput.start(str, context.chunkInput, function fail(msg, index) {
throw new LessError({
index,
type: 'Parse',
message: msg,
filename: fileInfo.filename
}, imports);
});
tree.Node.prototype.parse = this;
root = new tree.Ruleset(null, this.parsers.primary());
tree.Node.prototype.rootNode = root;
root.root = true;
root.firstRoot = true;
root.functionRegistry = functionRegistry.inherit();
} catch (e) {
return callback(new LessError(e, imports, fileInfo.filename));
}
// If `i` is smaller than the `input.length - 1`,
// it means the parser wasn't able to parse the whole
// string, so we've got a parsing error.
//
// We try to extract a \n delimited string,
// showing the line where the parse error occurred.
// We split it up into two parts (the part which parsed,
// and the part which didn't), so we can color them differently.
const endInfo = parserInput.end();
if (!endInfo.isFinished) {
let message = endInfo.furthestPossibleErrorMessage;
if (!message) {
message = 'Unrecognised input';
if (endInfo.furthestChar === '}') {
message += '. Possibly missing opening \'{\'';
} else if (endInfo.furthestChar === ')') {
message += '. Possibly missing opening \'(\'';
} else if (endInfo.furthestReachedEnd) {
message += '. Possibly missing something';
}
}
err = new LessError({
type: 'Parse',
message,
index: endInfo.furthest,
filename: fileInfo.filename
}, imports);
}
const finish = e => {
e = err || e || imports.error;
if (e) {
if (!(e instanceof LessError)) {
e = new LessError(e, imports, fileInfo.filename);
}
return callback(e);
}
else {
return callback(null, root);
}
};
if (context.processImports !== false) {
new visitors.ImportVisitor(imports, finish)
.run(root);
} else {
return finish();
}
},
//
// Here in, the parsing rules/functions
//
// The basic structure of the syntax tree generated is as follows:
//
// Ruleset -> Declaration -> Value -> Expression -> Entity
//
// Here's some Less code:
//
// .class {
// color: #fff;
// border: 1px solid #000;
// width: @w + 4px;
// > .child {...}
// }
//
// And here's what the parse tree might look like:
//
// Ruleset (Selector '.class', [
// Declaration ("color", Value ([Expression [Color #fff]]))
// Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
// Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
// Ruleset (Selector [Element '>', '.child'], [...])
// ])
//
// In general, most rules will try to parse a token with the `$re()` function, and if the return
// value is truly, will return a new node, of the relevant type. Sometimes, we need to check
// first, before parsing, that's when we use `peek()`.
//
parsers: parsers = {
//
// The `primary` rule is the *entry* and *exit* point of the parser.
// The rules here can appear at any level of the parse tree.
//
// The recursive nature of the grammar is an interplay between the `block`
// rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
// as represented by this simplified grammar:
//
// primary → (ruleset | declaration)+
// ruleset → selector+ block
// block → '{' primary '}'
//
// Only at one point is the primary rule not called from the
// block rule: at the root level.
//
primary: function () {
const mixin = this.mixin;
let root = [];
let node;
while (true) {
while (true) {
node = this.comment();
if (!node) { break; }
root.push(node);
}
// always process comments before deciding if finished
if (parserInput.finished) {
break;
}
if (parserInput.peek('}')) {
break;
}
node = this.extendRule();
if (node) {
root = root.concat(node);
continue;
}
node = mixin.definition() || this.declaration() || mixin.call(false, false) ||
this.ruleset() || this.variableCall() || this.entities.call() || this.atrule();
if (node) {
root.push(node);
} else {
let foundSemiColon = false;
while (parserInput.$char(';')) {
foundSemiColon = true;
}
if (!foundSemiColon) {
break;
}
}
}
return root;
},
// comments are collected by the main parsing mechanism and then assigned to nodes
// where the current structure allows it
comment: function () {
if (parserInput.commentStore.length) {
const comment = parserInput.commentStore.shift();
return new(tree.Comment)(comment.text, comment.isLineComment, comment.index + currentIndex, fileInfo);
}
},
//
// Entities are tokens which can be found inside an Expression
//
entities: {
mixinLookup: function() {
return parsers.mixin.call(true, true);
},
//
// A string, which supports escaping " and '
//
// "milky way" 'he\'s the one!'
//
quoted: function (forceEscaped) {
let str;
const index = parserInput.i;
let isEscaped = false;
parserInput.save();
if (parserInput.$char('~')) {
isEscaped = true;
} else if (forceEscaped) {
parserInput.restore();
return;
}
str = parserInput.$quoted();
if (!str) {
parserInput.restore();
return;
}
parserInput.forget();
return new(tree.Quoted)(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index + currentIndex, fileInfo);
},
//
// A catch-all word, such as:
//
// black border-collapse
//
keyword: function () {
const k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
if (k) {
return tree.Color.fromKeyword(k) || new(tree.Keyword)(k);
}
},
//
// A function call
//
// rgb(255, 0, 255)
//
// The arguments are parsed with the `entities.arguments` parser.
//
call: function () {
let name;
let args;
let func;
const index = parserInput.i;
// http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
if (parserInput.peek(/^url\(/i)) {
return;
}
parserInput.save();
name = parserInput.$re(/^([\w-]+|%|~|progid:[\w.]+)\(/);
if (!name) {
parserInput.forget();
return;
}
name = name[1];
func = this.customFuncCall(name);
if (func) {
args = func.parse();
if (args && func.stop) {
parserInput.forget();
return args;
}
}
args = this.arguments(args);
if (!parserInput.$char(')')) {
parserInput.restore('Could not parse call arguments or missing \')\'');
return;
}
parserInput.forget();
return new(tree.Call)(name, args, index + currentIndex, fileInfo);
},
declarationCall: function () {
let validCall;
let args;
const index = parserInput.i;
parserInput.save();
let keywordEntity = this.entities.keyword();
parserInput.restore();
parserInput.save();
validCall = parserInput.$re(/^[\w]+\(/);
if (!validCall) {
parserInput.forget();
return;
} else if (validCall && keywordEntity && !functionRegistry.get(validCall.substring(0, validCall.length - 1))) {
parserInput.restore();
return;
}
validCall = validCall.substring(0, validCall.length - 1);
let rule = this.ruleProperty();
let value;
if (rule) {
value = this.value();
}
if (rule && value) {
args = [new (tree.Declaration)(rule, value, null, null, parserInput.i + currentIndex, fileInfo, true)];
}
if (!parserInput.$char(')')) {
parserInput.restore('Could not parse call arguments or missing \')\'');
return;
}
parserInput.forget();
return new(tree.Call)(validCall, args, index + currentIndex, fileInfo);
},
//
// Parsing rules for functions with non-standard args, e.g.:
//
// boolean(not(2 > 1))
//
// This is a quick prototype, to be modified/improved when
// more custom-parsed funcs come (e.g. `selector(...)`)
//
customFuncCall: function (name) {
/* Ideally the table is to be moved out of here for faster perf.,
but it's quite tricky since it relies on all these `parsers`
and `expect` available only here */
return {
alpha: f(parsers.ieAlpha, true),
boolean: f(condition),
'if': f(condition)
}[name.toLowerCase()];
function f(parse, stop) {
return {
parse, // parsing function
stop // when true - stop after parse() and return its result,
// otherwise continue for plain args
};
}
function condition() {
return [expect(parsers.condition, 'expected condition')];
}
},
arguments: function (prevArgs) {
let argsComma = prevArgs || [];
const argsSemiColon = [];
let isSemiColonSeparated;
let value;
parserInput.save();
while (true) {
if (prevArgs) {
prevArgs = false;
} else {
value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
if (!value) {
break;
}
if (value.value && value.value.length == 1) {
value = value.value[0];
}
argsComma.push(value);
}
if (parserInput.$char(',')) {
continue;
}
if (parserInput.$char(';') || isSemiColonSeparated) {
isSemiColonSeparated = true;
value = (argsComma.length < 1) ? argsComma[0]
: new tree.Value(argsComma);
argsSemiColon.push(value);
argsComma = [];
}
}
parserInput.forget();
return isSemiColonSeparated ? argsSemiColon : argsComma;
},
literal: function () {
return this.dimension() ||
this.color() ||
this.quoted() ||
this.unicodeDescriptor();
},
// Assignments are argument entities for calls.
// They are present in ie filter properties as shown below.
//
// filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
//
assignment: function () {
let key;
let value;
parserInput.save();
key = parserInput.$re(/^\w+(?=\s?=)/i);
if (!key) {
parserInput.restore();
return;
}
if (!parserInput.$char('=')) {
parserInput.restore();
return;
}
value = parsers.entity();
if (value) {
parserInput.forget();
return new(tree.Assignment)(key, value);
} else {
parserInput.restore();
}
},
//
// Parse url() tokens
//
// We use a specific rule for urls, because they don't really behave like
// standard function calls. The difference is that the argument doesn't have
// to be enclosed within a string, so it can't be parsed as an Expression.
//
url: function () {
let value;
const index = parserInput.i;
parserInput.autoCommentAbsorb = false;
if (!parserInput.$str('url(')) {
parserInput.autoCommentAbsorb = true;
return;
}
value = this.quoted() || this.variable() || this.property() ||
parserInput.$re(/^(?:(?:\\[()'"])|[^()'"])+/) || '';
parserInput.autoCommentAbsorb = true;
expectChar(')');
return new(tree.URL)((value.value !== undefined ||
value instanceof tree.Variable ||
value instanceof tree.Property) ?
value : new(tree.Anonymous)(value, index), index + currentIndex, fileInfo);
},
//
// A Variable entity, such as `@fink`, in
//
// width: @fink + 2px
//
// We use a different parser for variable definitions,
// see `parsers.variable`.
//
variable: function () {
let ch;
let name;
const index = parserInput.i;
parserInput.save();
if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
ch = parserInput.currentChar();
if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
// this may be a VariableCall lookup
const result = parsers.variableCall(name);
if (result) {
parserInput.forget();
return result;
}
}
parserInput.forget();
return new(tree.Variable)(name, index + currentIndex, fileInfo);
}
parserInput.restore();
},
// A variable entity using the protective {} e.g. @{var}
variableCurly: function () {
let curly;
const index = parserInput.i;
if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
return new(tree.Variable)(`@${curly[1]}`, index + currentIndex, fileInfo);
}
},
//
// A Property accessor, such as `$color`, in
//
// background-color: $color
//
property: function () {
let name;
const index = parserInput.i;
if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
return new(tree.Property)(name, index + currentIndex, fileInfo);
}
},
// A property entity useing the protective {} e.g. ${prop}
propertyCurly: function () {
let curly;
const index = parserInput.i;
if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
return new(tree.Property)(`$${curly[1]}`, index + currentIndex, fileInfo);
}
},
//
// A Hexadecimal color
//
// #4F3C2F
//
// `rgb` and `hsl` colors are parsed through the `entities.call` parser.
//
color: function () {
let rgb;
parserInput.save();
if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#[])?/))) {
if (!rgb[2]) {
parserInput.forget();
return new(tree.Color)(rgb[1], undefined, rgb[0]);
}
}
parserInput.restore();
},
colorKeyword: function () {
parserInput.save();
const autoCommentAbsorb = parserInput.autoCommentAbsorb;
parserInput.autoCommentAbsorb = false;
const k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
parserInput.autoCommentAbsorb = autoCommentAbsorb;
if (!k) {
parserInput.forget();
return;
}
parserInput.restore();
const color = tree.Color.fromKeyword(k);
if (color) {
parserInput.$str(k);
return color;
}
},
//
// A Dimension, that is, a number and a unit
//
// 0.5em 95%
//
dimension: function () {
if (parserInput.peekNotNumeric()) {
return;
}
const value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
if (value) {
return new(tree.Dimension)(value[1], value[2]);
}
},
//
// A unicode descriptor, as is used in unicode-range
//
// U+0?? or U+00A1-00A9
//
unicodeDescriptor: function () {
let ud;
ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(-[0-9a-fA-F?]+)?/);
if (ud) {
return new(tree.UnicodeDescriptor)(ud[0]);
}
},
//
// JavaScript code to be evaluated
//
// `window.location.href`
//
javascript: function () {
let js;
const index = parserInput.i;
parserInput.save();
const escape = parserInput.$char('~');
const jsQuote = parserInput.$char('`');
if (!jsQuote) {
parserInput.restore();
return;
}
js = parserInput.$re(/^[^`]*`/);
if (js) {
parserInput.forget();
return new(tree.JavaScript)(js.substr(0, js.length - 1), Boolean(escape), index + currentIndex, fileInfo);
}
parserInput.restore('invalid javascript definition');
}
},
//
// The variable part of a variable definition. Used in the `rule` parser
//
// @fink:
//
variable: function () {
let name;
if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) { return name[1]; }
},
//
// Call a variable value to retrieve a detached ruleset
// or a value from a detached ruleset's rules.
//
// @fink();
// @fink;
// color: @fink[@color];
//
variableCall: function (parsedName) {
let lookups;
const i = parserInput.i;
const inValue = !!parsedName;
let name = parsedName;
parserInput.save();
if (name || (parserInput.currentChar() === '@'
&& (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/)))) {
lookups = this.mixin.ruleLookups();
if (!lookups && ((inValue && parserInput.$str('()') !== '()') || (name[2] !== '()'))) {
parserInput.restore('Missing \'[...]\' lookup in variable call');
return;
}
if (!inValue) {
name = name[1];
}
const call = new tree.VariableCall(name, i, fileInfo);
if (!inValue && parsers.end()) {
parserInput.forget();
return call;
}
else {
parserInput.forget();
return new tree.NamespaceValue(call, lookups, i, fileInfo);
}
}
parserInput.restore();
},
//
// extend syntax - used to extend selectors
//
extend: function(isRule) {
let elements;
let e;
const index = parserInput.i;
let option;
let extendList;
let extend;
if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
return;
}
do {
option = null;
elements = null;
let first = true;
while (!(option = parserInput.$re(/^(!?all)(?=\s*(\)|,))/))) {
e = this.element();
if (!e) {
break;
}
/**
* @note - This will not catch selectors in pseudos like :is() and :where() because
* they don't currently parse their contents as selectors.
*/
if (!first && e.combinator.value) {
warn('Targeting complex selectors can have unexpected behavior, and this behavior may change in the future.', index)
}
first = false;
if (elements) {
elements.push(e);
} else {
elements = [ e ];
}
}
option = option && option[1];
if (!elements) {
error('Missing target selector for :extend().');
}
extend = new(tree.Extend)(new(tree.Selector)(elements), option, index + currentIndex, fileInfo);
if (extendList) {
extendList.push(extend);
} else {
extendList = [ extend ];
}
} while (parserInput.$char(','));
expect(/^\)/);
if (isRule) {
expect(/^;/);
}
return extendList;
},
//
// extendRule - used in a rule to extend all the parent selectors
//
extendRule: function() {
return this.extend(true);
},
//
// Mixins
//
mixin: {
//
// A Mixin call, with an optional argument list
//
// #mixins > .square(#fff);
// #mixins.square(#fff);
// .rounded(4px, black);
// .button;
//
// We can lookup / return a value using the lookup syntax:
//
// color: #mixin.square(#fff)[@color];
//
// The `while` loop is there because mixins can be
// namespaced, but we only support the child and descendant
// selector for now.
//
call: function (inValue, getLookup) {
const s = parserInput.currentChar();
let important = false;
let lookups;
const index = parserInput.i;
let elements;
let args;
let hasParens;
let parensIndex;
let parensWS = false;
if (s !== '.' && s !== '#') { return; }
parserInput.save(); // stop us absorbing part of an invalid selector
elements = this.elements();
if (elements) {
parensIndex = parserInput.i;
if (parserInput.$char('(')) {
parensWS = parserInput.isWhitespace(-2);
args = this.args(true).args;
expectChar(')');
hasParens = true;
if (parensWS) {
warn('Whitespace between a mixin name and parentheses for a mixin call is deprecated', parensIndex, 'DEPRECATED');
}
}
if (getLookup !== false) {
lookups = this.ruleLookups();
}
if (getLookup === true && !lookups) {
parserInput.restore();
return;
}
if (inValue && !lookups && !hasParens) {
// This isn't a valid in-value mixin call