-
Notifications
You must be signed in to change notification settings - Fork 359
/
evaluate.dart
3314 lines (2889 loc) · 118 KB
/
evaluate.dart
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
// Copyright 2016 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.
// DO NOT EDIT. This file was generated from async_evaluate.dart.
// See tool/grind/synchronize.dart for details.
//
// Checksum: b2321a00031707d2df699e6888a334deba39995d
//
// ignore_for_file: unused_import
import 'async_evaluate.dart' show EvaluateResult;
export 'async_evaluate.dart' show EvaluateResult;
import 'dart:math' as math;
import 'package:charcode/charcode.dart';
import 'package:collection/collection.dart';
import 'package:path/path.dart' as p;
import 'package:source_span/source_span.dart';
import 'package:stack_trace/stack_trace.dart';
import 'package:tuple/tuple.dart';
import '../ast/css.dart';
import '../ast/css/modifiable.dart';
import '../ast/node.dart';
import '../ast/sass.dart';
import '../ast/selector.dart';
import '../environment.dart';
import '../import_cache.dart';
import '../callable.dart';
import '../color_names.dart';
import '../configuration.dart';
import '../configured_value.dart';
import '../exception.dart';
import '../extend/extension_store.dart';
import '../extend/extension.dart';
import '../functions.dart';
import '../functions/meta.dart' as meta;
import '../importer.dart';
import '../importer/node.dart';
import '../io.dart';
import '../logger.dart';
import '../module.dart';
import '../module/built_in.dart';
import '../parse/keyframe_selector.dart';
import '../syntax.dart';
import '../utils.dart';
import '../util/nullable.dart';
import '../value.dart';
import '../warn.dart';
import 'interface/css.dart';
import 'interface/expression.dart';
import 'interface/modifiable_css.dart';
import 'interface/statement.dart';
/// A function that takes a callback with no arguments.
typedef _ScopeCallback = void Function(void Function() callback);
/// Converts [stylesheet] to a plain CSS tree.
///
/// If [importCache] (or, on Node.js, [nodeImporter]) is passed, it's used to
/// resolve imports in the Sass files.
///
/// If [importer] is passed, it's used to resolve relative imports in
/// [stylesheet] relative to `stylesheet.span.sourceUrl`.
///
/// The [functions] are available as global functions when evaluating
/// [stylesheet].
///
/// The [variables] are available as global variables when evaluating
/// [stylesheet].
///
/// Warnings are emitted using [logger], or printed to standard error by
/// default.
///
/// If [sourceMap] is `true`, this will track the source locations of variable
/// declarations.
///
/// Throws a [SassRuntimeException] if evaluation fails.
EvaluateResult evaluate(Stylesheet stylesheet,
{ImportCache? importCache,
NodeImporter? nodeImporter,
Importer? importer,
Iterable<Callable>? functions,
Logger? logger,
bool quietDeps = false,
bool sourceMap = false}) =>
_EvaluateVisitor(
importCache: importCache,
nodeImporter: nodeImporter,
functions: functions,
logger: logger,
quietDeps: quietDeps,
sourceMap: sourceMap)
.run(importer, stylesheet);
/// A class that can evaluate multiple independent statements and expressions
/// in the context of a single module.
class Evaluator {
/// The visitor that evaluates each expression and statement.
final _EvaluateVisitor _visitor;
/// The importer to use to resolve `@use` rules in [_visitor].
final Importer? _importer;
/// Creates an evaluator.
///
/// Arguments are the same as for [evaluate].
Evaluator(
{ImportCache? importCache,
Importer? importer,
Iterable<Callable>? functions,
Logger? logger})
: _visitor = _EvaluateVisitor(
importCache: importCache, functions: functions, logger: logger),
_importer = importer;
void use(UseRule use) => _visitor.runStatement(_importer, use);
Value evaluate(Expression expression) =>
_visitor.runExpression(_importer, expression);
void setVariable(VariableDeclaration declaration) =>
_visitor.runStatement(_importer, declaration);
}
/// A visitor that executes Sass code to produce a CSS tree.
class _EvaluateVisitor
implements
StatementVisitor<Value?>,
ExpressionVisitor<Value>,
CssVisitor<void> {
/// The import cache used to import other stylesheets.
final ImportCache? _importCache;
/// The Node Sass-compatible importer to use when loading new Sass files when
/// compiled to Node.js.
final NodeImporter? _nodeImporter;
/// Built-in functions that are globally-accessible, even under the new module
/// system.
final _builtInFunctions = <String, Callable>{};
/// Built in modules, indexed by their URLs.
final _builtInModules = <Uri, Module<Callable>>{};
/// All modules that have been loaded and evaluated so far.
final _modules = <Uri, Module<Callable>>{};
/// A map from canonical module URLs to the nodes whose spans indicate where
/// those modules were originally loaded.
///
/// This is not guaranteed to have a node for every module in [_modules]. For
/// example, the entrypoint module was not loaded by a node.
final _moduleNodes = <Uri, AstNode>{};
/// The logger to use to print warnings.
final Logger _logger;
/// A set of message/location pairs for warnings that have been emitted via
/// [_warn].
///
/// We only want to emit one warning per location, to avoid blowing up users'
/// consoles with redundant warnings.
final _warningsEmitted = <Tuple2<String, SourceSpan>>{};
/// Whether to avoid emitting warnings for files loaded from dependencies.
final bool _quietDeps;
/// Whether to track source map information.
final bool _sourceMap;
/// The current lexical environment.
Environment _environment;
/// The style rule that defines the current parent selector, if any.
///
/// This doesn't take into consideration any intermediate `@at-root` rules. In
/// the common case where those rules are relevant, use [_styleRule] instead.
ModifiableCssStyleRule? _styleRuleIgnoringAtRoot;
/// The current media queries, if any.
List<CssMediaQuery>? _mediaQueries;
/// The current parent node in the output CSS tree.
ModifiableCssParentNode get _parent => _assertInModule(__parent, "__parent");
set _parent(ModifiableCssParentNode value) => __parent = value;
ModifiableCssParentNode? __parent;
/// The name of the current declaration parent.
String? _declarationName;
/// The human-readable name of the current stack frame.
var _member = "root stylesheet";
/// The node for the innermost callable that's being invoked.
///
/// This is used to produce warnings for function calls. It's stored as an
/// [AstNode] rather than a [FileSpan] so we can avoid calling [AstNode.span]
/// if the span isn't required, since some nodes need to do real work to
/// manufacture a source span.
AstNode? _callableNode;
/// The span for the current import that's being resolved.
///
/// This is used to produce warnings for importers.
FileSpan? _importSpan;
/// Whether we're currently executing a function.
var _inFunction = false;
/// Whether we're currently building the output of an unknown at rule.
var _inUnknownAtRule = false;
ModifiableCssStyleRule? get _styleRule =>
_atRootExcludingStyleRule ? null : _styleRuleIgnoringAtRoot;
/// Whether we're directly within an `@at-root` rule that excludes style
/// rules.
var _atRootExcludingStyleRule = false;
/// Whether we're currently building the output of a `@keyframes` rule.
var _inKeyframes = false;
/// The set that will eventually populate the JS API's
/// `result.stats.includedFiles` field.
///
/// For filesystem imports, this contains the import path. For all other
/// imports, it contains the URL passed to the `@import`.
final _includedFiles = <String>{};
/// A map from canonical URLs for modules (or imported files) that are
/// currently being evaluated to AST nodes whose spans indicate the original
/// loads for those modules.
///
/// Map values may be `null`, which indicates an active module that doesn't
/// have a source span associated with its original load (such as the
/// entrypoint module).
///
/// This is used to ensure that we don't get into an infinite load loop.
final _activeModules = <Uri, AstNode?>{};
/// The dynamic call stack representing function invocations, mixin
/// invocations, and imports surrounding the current context.
///
/// Each member is a tuple of the span where the stack trace starts and the
/// name of the member being invoked.
///
/// This stores [AstNode]s rather than [FileSpan]s so it can avoid calling
/// [AstNode.span] if the span isn't required, since some nodes need to do
/// real work to manufacture a source span.
final _stack = <Tuple2<String, AstNode>>[];
/// Whether we're running in Node Sass-compatibility mode.
bool get _asNodeSass => _nodeImporter != null;
// ## Module-Specific Fields
/// The importer that's currently being used to resolve relative imports.
///
/// If this is `null`, relative imports aren't supported in the current
/// stylesheet.
Importer? _importer;
/// Whether we're in a dependency.
///
/// A dependency is defined as a stylesheet imported by an importer other than
/// the original. In Node importers, nothing is considered a dependency.
var _inDependency = false;
/// The stylesheet that's currently being evaluated.
Stylesheet get _stylesheet => _assertInModule(__stylesheet, "_stylesheet");
set _stylesheet(Stylesheet value) => __stylesheet = value;
Stylesheet? __stylesheet;
/// The root stylesheet node.
ModifiableCssStylesheet get _root => _assertInModule(__root, "_root");
set _root(ModifiableCssStylesheet value) => __root = value;
ModifiableCssStylesheet? __root;
/// The first index in [_root.children] after the initial block of CSS
/// imports.
int get _endOfImports => _assertInModule(__endOfImports, "_endOfImports");
set _endOfImports(int value) => __endOfImports = value;
int? __endOfImports;
/// Plain-CSS imports that didn't appear in the initial block of CSS imports.
///
/// These are added to the initial CSS import block by [visitStylesheet] after
/// the stylesheet has been fully performed.
///
/// This is `null` unless there are any out-of-order imports in the current
/// stylesheet.
List<ModifiableCssImport>? _outOfOrderImports;
/// The extension store that tracks extensions and style rules for the current
/// module.
ExtensionStore get _extensionStore =>
_assertInModule(__extensionStore, "_extensionStore");
set _extensionStore(ExtensionStore value) => __extensionStore = value;
ExtensionStore? __extensionStore;
/// The configuration for the current module.
///
/// If this is empty, that indicates that the current module is not configured.
var _configuration = const Configuration.empty();
/// Creates a new visitor.
///
/// Most arguments are the same as those to [evaluate].
_EvaluateVisitor(
{ImportCache? importCache,
NodeImporter? nodeImporter,
Iterable<Callable>? functions,
Logger? logger,
bool quietDeps = false,
bool sourceMap = false})
: _importCache = nodeImporter == null
? importCache ?? ImportCache.none(logger: logger)
: null,
_nodeImporter = nodeImporter,
_logger = logger ?? const Logger.stderr(),
_quietDeps = quietDeps,
_sourceMap = sourceMap,
// The default environment is overridden in [_execute] for full
// stylesheets, but for [AsyncEvaluator] this environment is used.
_environment = Environment() {
var metaFunctions = [
// These functions are defined in the context of the evaluator because
// they need access to the [_environment] or other local state.
BuiltInCallable.function(
"global-variable-exists", r"$name, $module: null", (arguments) {
var variable = arguments[0].assertString("name");
var module = arguments[1].realNull?.assertString("module");
return SassBoolean(_environment.globalVariableExists(
variable.text.replaceAll("_", "-"),
namespace: module?.text));
}, url: "sass:meta"),
BuiltInCallable.function("variable-exists", r"$name", (arguments) {
var variable = arguments[0].assertString("name");
return SassBoolean(
_environment.variableExists(variable.text.replaceAll("_", "-")));
}, url: "sass:meta"),
BuiltInCallable.function("function-exists", r"$name, $module: null",
(arguments) {
var variable = arguments[0].assertString("name");
var module = arguments[1].realNull?.assertString("module");
return SassBoolean(_environment.functionExists(
variable.text.replaceAll("_", "-"),
namespace: module?.text) ||
_builtInFunctions.containsKey(variable.text));
}, url: "sass:meta"),
BuiltInCallable.function("mixin-exists", r"$name, $module: null",
(arguments) {
var variable = arguments[0].assertString("name");
var module = arguments[1].realNull?.assertString("module");
return SassBoolean(_environment.mixinExists(
variable.text.replaceAll("_", "-"),
namespace: module?.text));
}, url: "sass:meta"),
BuiltInCallable.function("content-exists", "", (arguments) {
if (!_environment.inMixin) {
throw SassScriptException(
"content-exists() may only be called within a mixin.");
}
return SassBoolean(_environment.content != null);
}, url: "sass:meta"),
BuiltInCallable.function("module-variables", r"$module", (arguments) {
var namespace = arguments[0].assertString("module");
var module = _environment.modules[namespace.text];
if (module == null) {
throw 'There is no module with namespace "${namespace.text}".';
}
return SassMap({
for (var entry in module.variables.entries)
SassString(entry.key): entry.value
});
}, url: "sass:meta"),
BuiltInCallable.function("module-functions", r"$module", (arguments) {
var namespace = arguments[0].assertString("module");
var module = _environment.modules[namespace.text];
if (module == null) {
throw 'There is no module with namespace "${namespace.text}".';
}
return SassMap({
for (var entry in module.functions.entries)
SassString(entry.key): SassFunction(entry.value)
});
}, url: "sass:meta"),
BuiltInCallable.function(
"get-function", r"$name, $css: false, $module: null", (arguments) {
var name = arguments[0].assertString("name");
var css = arguments[1].isTruthy;
var module = arguments[2].realNull?.assertString("module");
if (css && module != null) {
throw r"$css and $module may not both be passed at once.";
}
var callable = css
? PlainCssCallable(name.text)
: _addExceptionSpan(
_callableNode!,
() => _getFunction(name.text.replaceAll("_", "-"),
namespace: module?.text));
if (callable != null) return SassFunction(callable);
throw "Function not found: $name";
}, url: "sass:meta"),
BuiltInCallable.function("call", r"$function, $args...", (arguments) {
var function = arguments[0];
var args = arguments[1] as SassArgumentList;
var callableNode = _callableNode!;
var invocation = ArgumentInvocation([], {}, callableNode.span,
rest: ValueExpression(args, callableNode.span),
keywordRest: args.keywords.isEmpty
? null
: ValueExpression(
SassMap({
for (var entry in args.keywords.entries)
SassString(entry.key, quotes: false): entry.value
}),
callableNode.span));
if (function is SassString) {
warn(
"Passing a string to call() is deprecated and will be illegal in "
"Dart Sass 2.0.0.\n"
"\n"
"Recommendation: call(get-function($function))",
deprecation: true);
var callableNode = _callableNode!;
var expression = FunctionExpression(
Interpolation([function.text], callableNode.span),
invocation,
callableNode.span);
return expression.accept(this);
}
var callable = function.assertFunction("function").callable;
if (callable is Callable) {
return _runFunctionCallable(invocation, callable, _callableNode!);
} else {
throw SassScriptException(
"The function ${callable.name} is asynchronous.\n"
"This is probably caused by a bug in a Sass plugin.");
}
}, url: "sass:meta")
];
var metaMixins = [
BuiltInCallable.mixin("load-css", r"$url, $with: null", (arguments) {
var url = Uri.parse(arguments[0].assertString("url").text);
var withMap = arguments[1].realNull?.assertMap("with").contents;
var callableNode = _callableNode!;
var configuration = const Configuration.empty();
if (withMap != null) {
var values = <String, ConfiguredValue>{};
var span = callableNode.span;
withMap.forEach((variable, value) {
var name =
variable.assertString("with key").text.replaceAll("_", "-");
if (values.containsKey(name)) {
throw "The variable \$$name was configured twice.";
}
values[name] = ConfiguredValue.explicit(value, span, callableNode);
});
configuration = ExplicitConfiguration(values, callableNode);
}
_loadModule(url, "load-css()", callableNode,
(module) => _combineCss(module, clone: true).accept(this),
baseUrl: callableNode.span.sourceUrl,
configuration: configuration,
namesInErrors: true);
_assertConfigurationIsEmpty(configuration, nameInError: true);
return null;
}, url: "sass:meta")
];
var metaModule = BuiltInModule("meta",
functions: [...meta.global, ...metaFunctions], mixins: metaMixins);
for (var module in [...coreModules, metaModule]) {
_builtInModules[module.url] = module;
}
functions = [...?functions, ...globalFunctions, ...metaFunctions];
for (var function in functions) {
_builtInFunctions[function.name.replaceAll("_", "-")] = function;
}
}
EvaluateResult run(Importer? importer, Stylesheet node) {
return _withWarnCallback(node, () {
var url = node.span.sourceUrl;
if (url != null) {
_activeModules[url] = null;
if (_asNodeSass) {
if (url.scheme == 'file') {
_includedFiles.add(p.fromUri(url));
} else if (url.toString() != 'stdin') {
_includedFiles.add(url.toString());
}
}
}
var module = _execute(importer, node);
return EvaluateResult(_combineCss(module), _includedFiles);
});
}
Value runExpression(Importer? importer, Expression expression) =>
_withWarnCallback(
expression,
() => _withFakeStylesheet(
importer, expression, () => expression.accept(this)));
void runStatement(Importer? importer, Statement statement) =>
_withWarnCallback(
statement,
() => _withFakeStylesheet(
importer, statement, () => statement.accept(this)));
/// Runs [callback] with a definition for the top-level `warn` function.
///
/// If no other span can be found to report a warning, falls back on
/// [nodeWithSpan]'s.
T _withWarnCallback<T>(AstNode nodeWithSpan, T callback()) {
return withWarnCallback(
(message, deprecation) => _warn(
message, _importSpan ?? _callableNode?.span ?? nodeWithSpan.span,
deprecation: deprecation),
callback);
}
/// Asserts that [value] is not `null` and returns it.
///
/// This is used for fields that are set whenever the evaluator is evaluating
/// a module, which is to say essentially all the time (unless running via
/// [runExpression] or [runStatement]).
T _assertInModule<T>(T? value, String name) {
if (value != null) return value;
throw StateError("Can't access $name outside of a module.");
}
/// Runs [callback] with [importer] as [_importer] and a fake [_stylesheet]
/// with [nodeWithSpan]'s source span.
T _withFakeStylesheet<T>(
Importer? importer, AstNode nodeWithSpan, T callback()) {
var oldImporter = _importer;
_importer = importer;
assert(__stylesheet == null);
_stylesheet = Stylesheet(const [], nodeWithSpan.span);
try {
return callback();
} finally {
_importer = oldImporter;
__stylesheet = null;
}
}
/// Loads the module at [url] and passes it to [callback].
///
/// This first tries loading [url] relative to [baseUrl], which defaults to
/// `_stylesheet.span.sourceUrl`.
///
/// The [configuration] overrides values for `!default` variables defined in
/// the module or modules it forwards and/or imports. If it's not passed, the
/// current configuration is used instead. Throws a [SassRuntimeException] if
/// a configured variable is not declared with `!default`.
///
/// If [namesInErrors] is `true`, this includes the names of modules or
/// configured variables in errors relating to them. This should only be
/// `true` if the names won't be obvious from the source span.
///
/// The [stackFrame] and [nodeWithSpan] are used for the name and location of
/// the stack frame for the duration of the [callback].
void _loadModule(Uri url, String stackFrame, AstNode nodeWithSpan,
void callback(Module<Callable> module),
{Uri? baseUrl,
Configuration? configuration,
bool namesInErrors = false}) {
var builtInModule = _builtInModules[url];
if (builtInModule != null) {
if (configuration is ExplicitConfiguration) {
throw _exception(
namesInErrors
? "Built-in module $url can't be configured."
: "Built-in modules can't be configured.",
configuration.nodeWithSpan.span);
}
_addExceptionSpan(nodeWithSpan, () => callback(builtInModule));
return;
}
_withStackFrame(stackFrame, nodeWithSpan, () {
var result =
_loadStylesheet(url.toString(), nodeWithSpan.span, baseUrl: baseUrl);
var stylesheet = result.stylesheet;
var canonicalUrl = stylesheet.span.sourceUrl;
if (canonicalUrl != null && _activeModules.containsKey(canonicalUrl)) {
var message = namesInErrors
? "Module loop: ${p.prettyUri(canonicalUrl)} is already being "
"loaded."
: "Module loop: this module is already being loaded.";
throw _activeModules[canonicalUrl].andThen((previousLoad) =>
_multiSpanException(message, "new load",
{previousLoad.span: "original load"})) ??
_exception(message);
}
if (canonicalUrl != null) _activeModules[canonicalUrl] = nodeWithSpan;
var oldInDependency = _inDependency;
_inDependency = result.isDependency;
Module<Callable> module;
try {
module = _execute(result.importer, stylesheet,
configuration: configuration,
nodeWithSpan: nodeWithSpan,
namesInErrors: namesInErrors);
} finally {
_activeModules.remove(canonicalUrl);
_inDependency = oldInDependency;
}
try {
callback(module);
} on SassRuntimeException {
rethrow;
} on MultiSpanSassException catch (error) {
throw MultiSpanSassRuntimeException(error.message, error.span,
error.primaryLabel, error.secondarySpans, _stackTrace(error.span));
} on SassException catch (error) {
throw _exception(error.message, error.span);
} on MultiSpanSassScriptException catch (error) {
throw _multiSpanException(
error.message, error.primaryLabel, error.secondarySpans);
} on SassScriptException catch (error) {
throw _exception(error.message);
}
});
}
/// Executes [stylesheet], loaded by [importer], to produce a module.
///
/// If [configuration] is not passed, the current configuration is used
/// instead.
///
/// If [namesInErrors] is `true`, this includes the names of modules in errors
/// relating to them. This should only be `true` if the names won't be obvious
/// from the source span.
Module<Callable> _execute(Importer? importer, Stylesheet stylesheet,
{Configuration? configuration,
AstNode? nodeWithSpan,
bool namesInErrors = false}) {
var url = stylesheet.span.sourceUrl;
var alreadyLoaded = _modules[url];
if (alreadyLoaded != null) {
var currentConfiguration = configuration ?? _configuration;
if (currentConfiguration is ExplicitConfiguration) {
var message = namesInErrors
? "${p.prettyUri(url)} was already loaded, so it can't be "
"configured using \"with\"."
: "This module was already loaded, so it can't be configured using "
"\"with\".";
var existingSpan = _moduleNodes[url]?.span;
var configurationSpan = configuration == null
? currentConfiguration.nodeWithSpan.span
: null;
var secondarySpans = {
if (existingSpan != null) existingSpan: "original load",
if (configurationSpan != null) configurationSpan: "configuration"
};
throw secondarySpans.isEmpty
? _exception(message)
: _multiSpanException(message, "new load", secondarySpans);
}
return alreadyLoaded;
}
var environment = Environment();
late CssStylesheet css;
var extensionStore = ExtensionStore();
_withEnvironment(environment, () {
var oldImporter = _importer;
var oldStylesheet = __stylesheet;
var oldRoot = __root;
var oldParent = __parent;
var oldEndOfImports = __endOfImports;
var oldOutOfOrderImports = _outOfOrderImports;
var oldExtensionStore = __extensionStore;
var oldStyleRule = _styleRule;
var oldMediaQueries = _mediaQueries;
var oldDeclarationName = _declarationName;
var oldInUnknownAtRule = _inUnknownAtRule;
var oldAtRootExcludingStyleRule = _atRootExcludingStyleRule;
var oldInKeyframes = _inKeyframes;
var oldConfiguration = _configuration;
_importer = importer;
_stylesheet = stylesheet;
var root = __root = ModifiableCssStylesheet(stylesheet.span);
_parent = root;
_endOfImports = 0;
_outOfOrderImports = null;
_extensionStore = extensionStore;
_styleRuleIgnoringAtRoot = null;
_mediaQueries = null;
_declarationName = null;
_inUnknownAtRule = false;
_atRootExcludingStyleRule = false;
_inKeyframes = false;
if (configuration != null) _configuration = configuration;
visitStylesheet(stylesheet);
css = _outOfOrderImports == null
? root
: CssStylesheet(_addOutOfOrderImports(), stylesheet.span);
_importer = oldImporter;
__stylesheet = oldStylesheet;
__root = oldRoot;
__parent = oldParent;
__endOfImports = oldEndOfImports;
_outOfOrderImports = oldOutOfOrderImports;
__extensionStore = oldExtensionStore;
_styleRuleIgnoringAtRoot = oldStyleRule;
_mediaQueries = oldMediaQueries;
_declarationName = oldDeclarationName;
_inUnknownAtRule = oldInUnknownAtRule;
_atRootExcludingStyleRule = oldAtRootExcludingStyleRule;
_inKeyframes = oldInKeyframes;
_configuration = oldConfiguration;
});
var module = environment.toModule(css, extensionStore);
if (url != null) {
_modules[url] = module;
if (nodeWithSpan != null) _moduleNodes[url] = nodeWithSpan;
}
return module;
}
/// Returns a copy of [_root.children] with [_outOfOrderImports] inserted
/// after [_endOfImports], if necessary.
List<ModifiableCssNode> _addOutOfOrderImports() {
var outOfOrderImports = _outOfOrderImports;
if (outOfOrderImports == null) return _root.children;
return [
..._root.children.take(_endOfImports),
...outOfOrderImports,
..._root.children.skip(_endOfImports)
];
}
/// Returns a new stylesheet containing [root]'s CSS as well as the CSS of all
/// modules transitively used by [root].
///
/// This also applies each module's extensions to its upstream modules.
///
/// If [clone] is `true`, this will copy the modules before extending them so
/// that they don't modify [root] or its dependencies.
CssStylesheet _combineCss(Module<Callable> root, {bool clone = false}) {
if (!root.upstream.any((module) => module.transitivelyContainsCss)) {
var selectors = root.extensionStore.simpleSelectors;
var unsatisfiedExtension = firstOrNull(root.extensionStore
.extensionsWhereTarget((target) => !selectors.contains(target)));
if (unsatisfiedExtension != null) {
_throwForUnsatisfiedExtension(unsatisfiedExtension);
}
return root.css;
}
var sortedModules = _topologicalModules(root);
if (clone) {
sortedModules = sortedModules.map((module) => module.cloneCss()).toList();
}
_extendModules(sortedModules);
// The imports (and comments between them) that should be included at the
// beginning of the final document.
var imports = <CssNode>[];
// The CSS statements in the final document.
var css = <CssNode>[];
for (var module in sortedModules.reversed) {
var statements = module.css.children;
var index = _indexAfterImports(statements);
imports.addAll(statements.getRange(0, index));
css.addAll(statements.getRange(index, statements.length));
}
return CssStylesheet(imports + css, root.css.span);
}
/// Extends the selectors in each module with the extensions defined in
/// downstream modules.
void _extendModules(List<Module<Callable>> sortedModules) {
// All the [ExtensionStore]s directly downstream of a given module (indexed
// by its canonical URL). It's important that we create this in topological
// order, so that by the time we're processing a module we've already filled
// in all its downstream [ExtensionStore]s and we can use them to extend
// that module.
var downstreamExtensionStores = <Uri, List<ExtensionStore>>{};
/// Extensions that haven't yet been satisfied by some upstream module. This
/// adds extensions when they're defined but not satisfied, and removes them
/// when they're satisfied by any module.
var unsatisfiedExtensions = Set<Extension>.identity();
for (var module in sortedModules) {
// Create a snapshot of the simple selectors currently in the
// [ExtensionStore] so that we don't consider an extension "satisfied"
// below because of a simple selector added by another (sibling)
// extension.
var originalSelectors = module.extensionStore.simpleSelectors.toSet();
// Add all as-yet-unsatisfied extensions before adding downstream
// [ExtensionStore]s, because those are all in [unsatisfiedExtensions]
// already.
unsatisfiedExtensions.addAll(module.extensionStore.extensionsWhereTarget(
(target) => !originalSelectors.contains(target)));
downstreamExtensionStores[module.url]
.andThen(module.extensionStore.addExtensions);
if (module.extensionStore.isEmpty) continue;
for (var upstream in module.upstream) {
var url = upstream.url;
if (url == null) continue;
downstreamExtensionStores
.putIfAbsent(url, () => [])
.add(module.extensionStore);
}
// Remove all extensions that are now satisfied after adding downstream
// [ExtensionStore]s so it counts any downstream extensions that have been
// newly satisfied.
unsatisfiedExtensions.removeAll(module.extensionStore
.extensionsWhereTarget(originalSelectors.contains));
}
if (unsatisfiedExtensions.isNotEmpty) {
_throwForUnsatisfiedExtension(unsatisfiedExtensions.first);
}
}
/// Throws an exception indicating that [extension] is unsatisfied.
Never _throwForUnsatisfiedExtension(Extension extension) {
throw SassException(
'The target selector was not found.\n'
'Use "@extend ${extension.target} !optional" to avoid this error.',
extension.span);
}
/// Returns all modules transitively used by [root] in topological order,
/// ignoring modules that contain no CSS.
List<Module<Callable>> _topologicalModules(Module<Callable> root) {
// Construct a topological ordering using depth-first traversal, as in
// https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search.
var seen = <Module<Callable>>{};
var sorted = QueueList<Module<Callable>>();
void visitModule(Module<Callable> module) {
// Each module is added to the beginning of [sorted], which means the
// returned list contains sibling modules in the opposite order of how
// they appear in the document. Then when the list is reversed to generate
// the CSS, they're put back in their original order.
for (var upstream in module.upstream) {
if (upstream.transitivelyContainsCss && seen.add(upstream)) {
visitModule(upstream);
}
}
sorted.addFirst(module);
}
visitModule(root);
return sorted;
}
/// Returns the index of the first node in [statements] that comes after all
/// static imports.
int _indexAfterImports(List<CssNode> statements) {
var lastImport = -1;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement is CssImport) {
lastImport = i;
} else if (statement is! CssComment) {
break;
}
}
return lastImport + 1;
}
// ## Statements
Value? visitStylesheet(Stylesheet node) {
for (var child in node.children) {
child.accept(this);
}
return null;
}
Value? visitAtRootRule(AtRootRule node) {
var query = AtRootQuery.defaultQuery;
var unparsedQuery = node.query;
if (unparsedQuery != null) {
var resolved = _performInterpolation(unparsedQuery, warnForColor: true);
query = _adjustParseError(
unparsedQuery, () => AtRootQuery.parse(resolved, logger: _logger));
}
var parent = _parent;
var included = <ModifiableCssParentNode>[];
while (parent is! CssStylesheet) {
if (!query.excludes(parent)) included.add(parent);
var grandparent = parent.parent;
if (grandparent == null) {
throw StateError(
"CssNodes must have a CssStylesheet transitive parent node.");
}
parent = grandparent;
}
var root = _trimIncluded(included);
// If we didn't exclude any rules, we don't need to use the copies we might
// have created.
if (root == _parent) {
_environment.scope(() {
for (var child in node.children) {
child.accept(this);
}
}, when: node.hasDeclarations);
return null;
}
var innerCopy = root;
if (included.isNotEmpty) {
innerCopy = included.first.copyWithoutChildren();
var outerCopy = innerCopy;
for (var node in included.skip(1)) {
var copy = node.copyWithoutChildren();
copy.addChild(outerCopy);
outerCopy = copy;
}
root.addChild(outerCopy);
}
_scopeForAtRoot(node, innerCopy, query, included)(() {
for (var child in node.children) {
child.accept(this);
}
});
return null;
}
/// Destructively trims a trailing sublist from [nodes] that matches the
/// current list of parents.
///
/// [nodes] should be a list of parents included by an `@at-root` rule, from
/// innermost to outermost. If it contains a trailing sublist that's
/// contiguous—meaning that each node is a direct parent of the node before