/
environment.dart
861 lines (757 loc) · 30.4 KB
/
environment.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
// 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_environment.dart.
// See tool/grind/synchronize.dart for details.
//
// Checksum: 2522d5fbfb9d301b361a9bacac97228de2c6fd68
//
// ignore_for_file: unused_import
import 'dart:collection';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as p;
import 'package:source_span/source_span.dart';
import 'ast/css.dart';
import 'ast/node.dart';
import 'ast/sass.dart';
import 'callable.dart';
import 'exception.dart';
import 'extend/extender.dart';
import 'module.dart';
import 'module/forwarded_view.dart';
import 'util/merged_map_view.dart';
import 'util/public_member_map_view.dart';
import 'utils.dart';
import 'value.dart';
import 'visitor/clone_css.dart';
/// The lexical environment in which Sass is executed.
///
/// This tracks lexically-scoped information, such as variables, functions, and
/// mixins.
class Environment {
/// The modules used in the current scope, indexed by their namespaces.
Map<String, Module<Callable>> get modules => UnmodifiableMapView(_modules);
final Map<String, Module<Callable>> _modules;
/// The namespaceless modules used in the current scope.
///
/// This is `null` if there are no namespaceless modules.
Set<Module<Callable>> _globalModules;
/// The modules forwarded by this module.
///
/// This is `null` if there are no forwarded modules.
List<Module<Callable>> _forwardedModules;
/// Modules from [_modules], [_globalModules], and [_forwardedModules], in the
/// order in which they were `@use`d.
final List<Module<Callable>> _allModules;
/// A list of variables defined at each lexical scope level.
///
/// Each scope maps the names of declared variables to their values.
///
/// The first element is the global scope, and each successive element is
/// deeper in the tree.
final List<Map<String, Value>> _variables;
/// The nodes where each variable in [_variables] was defined.
///
/// This is `null` if source mapping is disabled.
///
/// 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 List<Map<String, AstNode>> _variableNodes;
/// A map of variable names to their indices in [_variables].
///
/// This map is filled in as-needed, and may not be complete.
final Map<String, int> _variableIndices;
/// A list of functions defined at each lexical scope level.
///
/// Each scope maps the names of declared functions to their values.
///
/// The first element is the global scope, and each successive element is
/// deeper in the tree.
final List<Map<String, Callable>> _functions;
/// A map of function names to their indices in [_functions].
///
/// This map is filled in as-needed, and may not be complete.
final Map<String, int> _functionIndices;
/// A list of mixins defined at each lexical scope level.
///
/// Each scope maps the names of declared mixins to their values.
///
/// The first element is the global scope, and each successive element is
/// deeper in the tree.
final List<Map<String, Callable>> _mixins;
/// A map of mixin names to their indices in [_mixins].
///
/// This map is filled in as-needed, and may not be complete.
final Map<String, int> _mixinIndices;
/// The content block passed to the lexically-enclosing mixin, or `null` if
/// this is not in a mixin, or if no content block was passed.
UserDefinedCallable<Environment> get content => _content;
UserDefinedCallable<Environment> _content;
/// Whether the environment is lexically at the root of the document.
bool get atRoot => _variables.length == 1;
/// Whether the environment is lexically within a mixin.
bool get inMixin => _inMixin;
var _inMixin = false;
/// Whether the environment is currently in a global or semi-global scope.
///
/// A semi-global scope can assign to global variables, but it doesn't declare
/// them by default.
var _inSemiGlobalScope = true;
/// The name of the last variable that was accessed.
///
/// This is cached to speed up repeated references to the same variable, as
/// well as references to the last variable's [FileSpan].
String _lastVariableName;
/// The index in [_variables] of the last variable that was accessed.
int _lastVariableIndex;
/// Creates an [Environment].
///
/// If [sourceMap] is `true`, this tracks variables' source locations
Environment({bool sourceMap = false})
: _modules = {},
_globalModules = null,
_forwardedModules = null,
_allModules = [],
_variables = [{}],
_variableNodes = sourceMap ? [{}] : null,
_variableIndices = {},
_functions = [{}],
_functionIndices = {},
_mixins = [{}],
_mixinIndices = {};
Environment._(
this._modules,
this._globalModules,
this._forwardedModules,
this._allModules,
this._variables,
this._variableNodes,
this._functions,
this._mixins,
this._content)
// Lazily fill in the indices rather than eagerly copying them from the
// existing environment in closure() because the copying took a lot of
// time and was rarely helpful. This saves a bunch of time on Susy's
// tests.
: _variableIndices = {},
_functionIndices = {},
_mixinIndices = {};
/// Creates a closure based on this environment.
///
/// Any scope changes in this environment will not affect the closure.
/// However, any new declarations or assignments in scopes that are visible
/// when the closure was created will be reflected.
Environment closure() => Environment._(
_modules,
_globalModules,
_forwardedModules,
_allModules,
_variables.toList(),
_variableNodes?.toList(),
_functions.toList(),
_mixins.toList(),
_content);
/// Returns a new global environment.
///
/// The returned environment shares this environment's global variables,
/// functions, and mixins, but not its modules.
Environment global() => Environment._(
{},
null,
null,
[],
_variables.toList(),
_variableNodes?.toList(),
_functions.toList(),
_mixins.toList(),
_content);
/// Adds [module] to the set of modules visible in this environment.
///
/// If [namespace] is passed, the module is made available under that
/// namespace.
///
/// Throws a [SassScriptException] if there's already a module with the given
/// [namespace], or if [namespace] is `null` and [module] defines a variable
/// with the same name as a variable defined in this environment.
void addModule(Module<Callable> module, {String namespace}) {
if (namespace == null) {
_globalModules ??= {};
_globalModules.add(module);
_allModules.add(module);
for (var name in _variables.first.keys) {
if (module.variables.containsKey(name)) {
throw SassScriptException(
'This module and the new module both define a variable named '
'"\$$name".');
}
}
} else {
if (_modules.containsKey(namespace)) {
throw SassScriptException(
"There's already a module with namespace \"$namespace\".");
}
_modules[namespace] = module;
_allModules.add(module);
}
}
/// Exposes the members in [module] to downstream modules as though they were
/// defined in this module, according to the modifications defined by [rule].
void forwardModule(Module<Callable> module, ForwardRule rule) {
_forwardedModules ??= [];
var view = ForwardedModuleView(module, rule);
for (var other in _forwardedModules) {
_assertNoConflicts(view.variables, other.variables, "variable", other);
_assertNoConflicts(view.functions, other.functions, "function", other);
_assertNoConflicts(view.mixins, other.mixins, "mixin", other);
}
// Add the original module to [_allModules] (rather than the
// [ForwardedModuleView]) so that we can de-duplicate upstream modules using
// `==`. This is safe because upstream modules are only used for collating
// CSS, not for the members they expose.
_allModules.add(module);
_forwardedModules.add(view);
}
/// Throws a [SassScriptException] if [newMembers] has any keys that overlap
/// with [oldMembers].
///
/// The [type] and [oldModule] is used for error reporting.
void _assertNoConflicts(Map<String, Object> newMembers,
Map<String, Object> oldMembers, String type, Module<Callable> oldModule) {
Map<String, Object> smaller;
Map<String, Object> larger;
if (newMembers.length < oldMembers.length) {
smaller = newMembers;
larger = oldMembers;
} else {
smaller = oldMembers;
larger = newMembers;
}
for (var name in smaller.keys) {
if (larger.containsKey(name)) {
if (type == "variable") name = "\$$name";
throw SassScriptException(
'Module ${p.prettyUri(oldModule.url)} and the new module both '
'forward a $type named $name.');
}
}
}
/// Makes the members forwarded by [module] available in the current
/// environment.
///
/// This is called when [module] is `@import`ed.
void importForwards(Module<Callable> module) {
if (module is _EnvironmentModule) {
for (var forwarded in module._environment._forwardedModules ??
const <Module<Callable>>[]) {
_globalModules ??= {};
_globalModules.add(forwarded);
// Remove existing definitions that the forwarded members are now
// shadowing.
for (var variable in forwarded.variables.keys) {
var index =
_variableIndices.remove(variable) ?? _variableIndex(variable);
if (index != null) {
_variables[index].remove(variable);
if (_variableNodes != null) _variableNodes[index].remove(variable);
}
}
for (var function in forwarded.functions.keys) {
var index =
_functionIndices.remove(function) ?? _functionIndex(function);
if (index != null) _functions[index].remove(function);
}
for (var mixin in forwarded.mixins.keys) {
var index = _mixinIndices.remove(mixin) ?? _mixinIndex(mixin);
if (index != null) _mixins[index].remove(mixin);
}
}
}
}
/// Returns the value of the variable named [name], optionally with the given
/// [namespace], or `null` if no such variable is declared.
///
/// Throws a [SassScriptException] if there is no module named [namespace], or
/// if multiple global modules expose variables named [name].
Value getVariable(String name, {String namespace}) {
if (namespace != null) return _getModule(namespace).variables[name];
if (_lastVariableName == name) {
return _variables[_lastVariableIndex][name] ??
_getVariableFromGlobalModule(name);
}
var index = _variableIndices[name];
if (index != null) {
_lastVariableName = name;
_lastVariableIndex = index;
return _variables[index][name] ?? _getVariableFromGlobalModule(name);
}
index = _variableIndex(name);
if (index == null) return _getVariableFromGlobalModule(name);
_lastVariableName = name;
_lastVariableIndex = index;
_variableIndices[name] = index;
return _variables[index][name] ?? _getVariableFromGlobalModule(name);
}
/// Returns the value of the variable named [name] from a namespaceless
/// module, or `null` if no such variable is declared in any namespaceless
/// module.
Value _getVariableFromGlobalModule(String name) =>
_fromOneModule("variable", (module) => module.variables[name]);
/// Returns the node for the variable named [name], or `null` if no such
/// variable is declared.
///
/// This node is intended as a proxy for the [FileSpan] indicating where the
/// variable's value originated. It's returned 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 getVariableNode(String name, {String namespace}) {
if (namespace != null) return _getModule(namespace).variableNodes[name];
if (_lastVariableName == name) {
return _variableNodes[_lastVariableIndex][name] ??
_getVariableNodeFromGlobalModule(name);
}
var index = _variableIndices[name];
if (index != null) {
_lastVariableName = name;
_lastVariableIndex = index;
return _variableNodes[index][name] ??
_getVariableNodeFromGlobalModule(name);
}
index = _variableIndex(name);
if (index == null) return _getVariableNodeFromGlobalModule(name);
_lastVariableName = name;
_lastVariableIndex = index;
_variableIndices[name] = index;
return _variableNodes[index][name] ??
_getVariableNodeFromGlobalModule(name);
}
/// Returns the node for the variable named [name] from a namespaceless
/// module, or `null` if no such variable is declared.
///
/// This node is intended as a proxy for the [FileSpan] indicating where the
/// variable's value originated. It's returned 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 _getVariableNodeFromGlobalModule(String name) {
// There isn't a real variable defined as this index, but it will cause
// [getVariable] to short-circuit and get to this function faster next time
// the variable is accessed.
_lastVariableName = name;
_lastVariableIndex = 0;
if (_globalModules == null) return null;
// We don't need to worry about multiple modules defining the same variable,
// because that's already been checked by [getVariable].
for (var module in _globalModules) {
var value = module.variableNodes[name];
if (value != null) return value;
}
return null;
}
/// Returns whether a variable named [name] exists.
bool variableExists(String name) => getVariable(name) != null;
/// Returns whether a global variable named [name] exists.
///
/// Throws a [SassScriptException] if there is no module named [namespace], or
/// if multiple global modules expose functions named [name].
bool globalVariableExists(String name, {String namespace}) {
if (namespace != null) {
return _getModule(namespace).variables.containsKey(name);
}
if (_variables.first.containsKey(name)) return true;
return _getVariableFromGlobalModule(name) != null;
}
/// Returns the index of the last map in [_variables] that has a [name] key,
/// or `null` if none exists.
int _variableIndex(String name) {
for (var i = _variables.length - 1; i >= 0; i--) {
if (_variables[i].containsKey(name)) return i;
}
return null;
}
/// Sets the variable named [name] to [value], associated with
/// [nodeWithSpan]'s source span.
///
/// If [namespace] is passed, this sets the variable in the module with the
/// given namespace, if that module exposes a variable with that name.
///
/// If [global] is `true`, this sets the variable at the top-level scope.
/// Otherwise, if the variable was already defined, it'll set it in the
/// previous scope. If it's undefined, it'll set it in the current scope.
///
/// This takes an [AstNode] rather than a [FileSpan] 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.
///
/// Throws a [SassScriptException] if [namespace] is passed but no module is
/// defined with the given namespace, if no variable with the given [name] is
/// defined in module with the given namespace, or if no [namespace] is passed
/// and multiple global modules define variables named [name].
void setVariable(String name, Value value, AstNode nodeWithSpan,
{String namespace, bool global = false}) {
if (namespace != null) {
_getModule(namespace).setVariable(name, value, nodeWithSpan);
return;
}
if (global || atRoot) {
// Don't set the index if there's already a variable with the given name,
// since local accesses should still return the local variable.
_variableIndices.putIfAbsent(name, () {
_lastVariableName = name;
_lastVariableIndex = 0;
return 0;
});
// If this module doesn't already contain a variable named [name], try
// setting it in a global module.
if (!_variables.first.containsKey(name) && _globalModules != null) {
var moduleWithName = _fromOneModule("variable",
(module) => module.variables.containsKey(name) ? module : null);
if (moduleWithName != null) {
moduleWithName.setVariable(name, value, nodeWithSpan);
return;
}
}
_variables.first[name] = value;
if (_variableNodes != null) _variableNodes.first[name] = nodeWithSpan;
return;
}
var index = _lastVariableName == name
? _lastVariableIndex
: _variableIndices.putIfAbsent(
name, () => _variableIndex(name) ?? _variables.length - 1);
if (!_inSemiGlobalScope && index == 0) {
index = _variables.length - 1;
_variableIndices[name] = index;
}
_lastVariableName = name;
_lastVariableIndex = index;
_variables[index][name] = value;
if (_variableNodes != null) _variableNodes[index][name] = nodeWithSpan;
}
/// Sets the variable named [name] to [value], associated with
/// [nodeWithSpan]'s source span.
///
/// Unlike [setVariable], this will declare the variable in the current scope
/// even if a declaration already exists in an outer scope.
///
/// This takes an [AstNode] rather than a [FileSpan] 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.
void setLocalVariable(String name, Value value, AstNode nodeWithSpan) {
var index = _variables.length - 1;
_lastVariableName = name;
_lastVariableIndex = index;
_variableIndices[name] = index;
_variables[index][name] = value;
if (_variableNodes != null) _variableNodes[index][name] = nodeWithSpan;
}
/// Returns the value of the function named [name], optionally with the given
/// [namespace], or `null` if no such variable is declared.
///
/// Throws a [SassScriptException] if there is no module named [namespace], or
/// if multiple global modules expose functions named [name].
Callable getFunction(String name, {String namespace}) {
if (namespace != null) return _getModule(namespace).functions[name];
var index = _functionIndices[name];
if (index != null) {
return _functions[index][name] ?? _getFunctionFromGlobalModule(name);
}
index = _functionIndex(name);
if (index == null) return _getFunctionFromGlobalModule(name);
_functionIndices[name] = index;
return _functions[index][name] ?? _getFunctionFromGlobalModule(name);
}
/// Returns the value of the function named [name] from a namespaceless
/// module, or `null` if no such function is declared in any namespaceless
/// module.
Callable _getFunctionFromGlobalModule(String name) =>
_fromOneModule("function", (module) => module.functions[name]);
/// Returns the index of the last map in [_functions] that has a [name] key,
/// or `null` if none exists.
int _functionIndex(String name) {
for (var i = _functions.length - 1; i >= 0; i--) {
if (_functions[i].containsKey(name)) return i;
}
return null;
}
/// Returns whether a function named [name] exists.
///
/// Throws a [SassScriptException] if there is no module named [namespace], or
/// if multiple global modules expose functions named [name].
bool functionExists(String name, {String namespace}) =>
getFunction(name, namespace: namespace) != null;
/// Sets the variable named [name] to [value] in the current scope.
void setFunction(Callable callable) {
var index = _functions.length - 1;
_functionIndices[callable.name] = index;
_functions[index][callable.name] = callable;
}
/// Returns the value of the mixin named [name], optionally with the given
/// [namespace], or `null` if no such variable is declared.
///
/// Throws a [SassScriptException] if there is no module named [namespace], or
/// if multiple global modules expose mixins named [name].
Callable getMixin(String name, {String namespace}) {
if (namespace != null) return _getModule(namespace).mixins[name];
var index = _mixinIndices[name];
if (index != null) {
return _mixins[index][name] ?? _getMixinFromGlobalModule(name);
}
index = _mixinIndex(name);
if (index == null) return _getMixinFromGlobalModule(name);
_mixinIndices[name] = index;
return _mixins[index][name] ?? _getMixinFromGlobalModule(name);
}
/// Returns the value of the mixin named [name] from a namespaceless
/// module, or `null` if no such mixin is declared in any namespaceless
/// module.
Callable _getMixinFromGlobalModule(String name) =>
_fromOneModule("mixin", (module) => module.mixins[name]);
/// Returns the index of the last map in [_mixins] that has a [name] key, or
/// `null` if none exists.
int _mixinIndex(String name) {
for (var i = _mixins.length - 1; i >= 0; i--) {
if (_mixins[i].containsKey(name)) return i;
}
return null;
}
/// Returns whether a mixin named [name] exists.
///
/// Throws a [SassScriptException] if there is no module named [namespace], or
/// if multiple global modules expose functions named [name].
bool mixinExists(String name, {String namespace}) =>
getMixin(name, namespace: namespace) != null;
/// Sets the variable named [name] to [value] in the current scope.
void setMixin(Callable callable) {
var index = _mixins.length - 1;
_mixinIndices[callable.name] = index;
_mixins[index][callable.name] = callable;
}
/// Sets [content] as [this.content] for the duration of [callback].
void withContent(UserDefinedCallable<Environment> content, void callback()) {
var oldContent = _content;
_content = content;
callback();
_content = oldContent;
}
/// Sets [inMixin] to `true` for the duration of [callback].
void asMixin(void callback()) {
var oldInMixin = _inMixin;
_inMixin = true;
callback();
_inMixin = oldInMixin;
}
/// Runs [callback] in a new scope.
///
/// Variables, functions, and mixins declared in a given scope are
/// inaccessible outside of it. If [semiGlobal] is passed, this scope can
/// assign to global variables without a `!global` declaration.
///
/// If [when] is false, this doesn't create a new scope and instead just
/// executes [callback] and returns its result.
T scope<T>(T callback(), {bool semiGlobal = false, bool when = true}) {
if (!when) {
// We still have to track semi-globalness so that
//
// div {
// @if ... {
// $x: y;
// }
// }
//
// doesn't assign to the global scope.
var wasInSemiGlobalScope = _inSemiGlobalScope;
_inSemiGlobalScope = semiGlobal;
try {
return callback();
} finally {
_inSemiGlobalScope = wasInSemiGlobalScope;
}
}
semiGlobal = semiGlobal && _inSemiGlobalScope;
var wasInSemiGlobalScope = _inSemiGlobalScope;
_inSemiGlobalScope = semiGlobal;
_variables.add({});
_variableNodes?.add({});
_functions.add({});
_mixins.add({});
try {
return callback();
} finally {
_inSemiGlobalScope = wasInSemiGlobalScope;
_lastVariableName = null;
_lastVariableIndex = null;
for (var name in _variables.removeLast().keys) {
_variableIndices.remove(name);
}
for (var name in _functions.removeLast().keys) {
_functionIndices.remove(name);
}
for (var name in _mixins.removeLast().keys) {
_mixinIndices.remove(name);
}
}
}
/// Returns a module that represents the top-level members defined in [this],
/// that contains [css] as its CSS tree, which can be extended using
/// [extender].
Module<Callable> toModule(CssStylesheet css, Extender extender) =>
_EnvironmentModule(this, css, extender, forwarded: _forwardedModules);
/// Returns the module with the given [namespace], or throws a
/// [SassScriptException] if none exists.
Module<Callable> _getModule(String namespace) {
var module = _modules[namespace];
if (module != null) return module;
throw SassScriptException(
'There is no module with the namespace "$namespace".');
}
/// Returns the result of [callback] if it returns non-`null` for exactly one
/// module in [_globalModules].
///
/// Returns `null` if [callback] returns `null` for all modules. Throws an
/// error if [callback] returns non-`null` for more than one module.
///
/// The [type] should be the singular name of the value type being returned.
/// It's used to format an appropriate error message.
T _fromOneModule<T>(String type, T callback(Module<Callable> module)) {
if (_globalModules == null) return null;
T value;
for (var module in _globalModules) {
var valueInModule = callback(module);
if (valueInModule == null) continue;
if (value != null) {
throw SassScriptException(
'This $type is available from multiple global modules:\n' +
bulletedList(_globalModules
.where((module) => callback(module) != null)
.map((module) => p.prettyUri(module.url))));
}
value = valueInModule;
}
return value;
}
}
/// A module that represents the top-level members defined in an [Environment].
class _EnvironmentModule implements Module<Callable> {
Uri get url => css.span.sourceUrl;
final List<Module<Callable>> upstream;
final Map<String, Value> variables;
final Map<String, AstNode> variableNodes;
final Map<String, Callable> functions;
final Map<String, Callable> mixins;
final Extender extender;
final CssStylesheet css;
final bool transitivelyContainsCss;
final bool transitivelyContainsExtensions;
/// The environment that defines this module's members.
final Environment _environment;
/// A map from variable names to the modules in which those variables appear,
/// used to determine where variables should be set.
///
/// Variables that don't appear in this map are either defined directly in
/// this module (if they appear in `_environment._variables.first`) or not
/// defined at all.
final Map<String, Module<Callable>> _modulesByVariable;
factory _EnvironmentModule(
Environment environment, CssStylesheet css, Extender extender,
{List<Module<Callable>> forwarded}) {
forwarded ??= const [];
return _EnvironmentModule._(
environment,
css,
extender,
_makeModulesByVariable(forwarded),
_memberMap(environment._variables.first,
forwarded.map((module) => module.variables)),
environment._variableNodes == null
? null
: _memberMap(environment._variableNodes.first,
forwarded.map((module) => module.variableNodes)),
_memberMap(environment._functions.first,
forwarded.map((module) => module.functions)),
_memberMap(environment._mixins.first,
forwarded.map((module) => module.mixins)),
transitivelyContainsCss: css.children.isNotEmpty ||
environment._allModules
.any((module) => module.transitivelyContainsCss),
transitivelyContainsExtensions: !extender.isEmpty ||
environment._allModules
.any((module) => module.transitivelyContainsExtensions));
}
/// Create [_modulesByVariable] for a set of forwarded modules.
static Map<String, Module<Callable>> _makeModulesByVariable(
List<Module<Callable>> forwarded) {
if (forwarded.isEmpty) return const {};
var modulesByVariable = <String, Module<Callable>>{};
for (var module in forwarded) {
if (module is _EnvironmentModule) {
// Flatten nested forwarded modules to avoid O(depth) overhead.
for (var child in module._modulesByVariable.values) {
setAll(modulesByVariable, child.variables.keys, child);
}
setAll(modulesByVariable, module._environment._variables.first.keys,
module);
} else {
setAll(modulesByVariable, module.variables.keys, module);
}
}
return modulesByVariable;
}
/// Returns a map that exposes the public members of [localMap] as well as all
/// the members of [otherMaps].
static Map<String, V> _memberMap<V>(
Map<String, V> localMap, Iterable<Map<String, V>> otherMaps) {
localMap = PublicMemberMapView(localMap);
if (otherMaps.isEmpty) return localMap;
var allMaps = [
for (var map in otherMaps) if (map.isNotEmpty) map,
localMap
];
if (allMaps.length == 1) return localMap;
return MergedMapView(allMaps);
}
_EnvironmentModule._(
this._environment,
this.css,
this.extender,
this._modulesByVariable,
this.variables,
this.variableNodes,
this.functions,
this.mixins,
{@required this.transitivelyContainsCss,
@required this.transitivelyContainsExtensions})
: upstream = _environment._allModules;
void setVariable(String name, Value value, AstNode nodeWithSpan) {
var module = _modulesByVariable[name];
if (module != null) {
module.setVariable(name, value, nodeWithSpan);
return;
}
if (!_environment._variables.first.containsKey(name)) {
throw SassScriptException("Undefined variable.");
}
_environment._variables.first[name] = value;
if (_environment._variableNodes != null) {
_environment._variableNodes.first[name] = nodeWithSpan;
}
return;
}
Module<Callable> cloneCss() {
if (css.children.isEmpty) return this;
var newCssAndExtender = cloneCssStylesheet(css, extender);
return _EnvironmentModule._(
_environment,
newCssAndExtender.item1,
newCssAndExtender.item2,
_modulesByVariable,
variables,
variableNodes,
functions,
mixins,
transitivelyContainsCss: transitivelyContainsCss,
transitivelyContainsExtensions: transitivelyContainsExtensions);
}
String toString() => p.prettyUri(css.span.sourceUrl);
}