accent_sass_compiler 0.16.0

Internal implementation of the accent-sass compiler
Documentation
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
use codemap::{Span, Spanned};

use crate::{
    ast::{AstForwardRule, Configuration, ConfiguredValue, Mixin},
    builtin::modules::{ForwardedModule, Module, ModuleScope, Modules, ShadowedModule},
    common::Identifier,
    error::SassResult,
    selector::ExtensionStore,
    utils::MapView,
    value::{SassFunction, Value},
};
use std::{
    cell::RefCell,
    collections::{BTreeMap, HashSet},
    sync::Arc,
};

type Mutable<T> = Arc<RefCell<T>>;

use super::{scope::Scopes, visitor::CallableContentBlock};

#[derive(Debug, Clone)]
pub(crate) struct Environment {
    pub scopes: Scopes,
    pub modules: Mutable<Modules>,
    pub global_modules: Vec<Mutable<Module>>,
    pub content: Option<Arc<CallableContentBlock>>,
    pub forwarded_modules: Mutable<Vec<Mutable<Module>>>,
    pub imported_modules: Mutable<Vec<Mutable<Module>>>,
    #[allow(clippy::type_complexity)]
    pub nested_forwarded_modules: Option<Mutable<Vec<Mutable<Vec<Mutable<Module>>>>>>,
    /// The names declared `!default` at this environment's root -- the
    /// variables a `with (...)` clause could have configured. Consulted when
    /// a configuration reaches an already-loaded module, to tell a clause
    /// that could never have applied from a genuine double configuration.
    pub configurable_variables: Mutable<HashSet<Identifier>>,
}

impl Environment {
    pub fn new() -> Self {
        Self {
            scopes: Scopes::new(),
            modules: Arc::new(RefCell::new(Modules::new())),
            global_modules: Vec::new(),
            content: None,
            forwarded_modules: Arc::new(RefCell::new(Vec::new())),
            imported_modules: Arc::new(RefCell::new(Vec::new())),
            nested_forwarded_modules: None,
            configurable_variables: Arc::new(RefCell::new(HashSet::new())),
        }
    }

    pub fn new_closure(&self) -> Self {
        Self {
            scopes: self.scopes.new_closure(),
            modules: Arc::clone(&self.modules),
            global_modules: self.global_modules.iter().map(Arc::clone).collect(),
            content: self.content.as_ref().map(Arc::clone),
            forwarded_modules: Arc::clone(&self.forwarded_modules),
            imported_modules: Arc::clone(&self.imported_modules),
            nested_forwarded_modules: self.nested_forwarded_modules.as_ref().map(Arc::clone),
            configurable_variables: Arc::clone(&self.configurable_variables),
        }
    }

    /// The environment an `@import`ed stylesheet runs in.
    ///
    /// The imported file shares the importer's scopes and previously imported
    /// members, but gets its own forward list: the conflict check for two
    /// `@forward`s naming the same member applies within one file, and sharing
    /// the list made forwards from sibling `@import`s conflict with each other.
    /// `import_forwards` merges the fresh list back into the importer once the
    /// file has run.
    pub fn for_import(&self) -> Self {
        Self {
            scopes: self.scopes.new_closure(),
            modules: Arc::new(RefCell::new(Modules::new())),
            global_modules: Vec::new(),
            content: self.content.as_ref().map(Arc::clone),
            forwarded_modules: Arc::new(RefCell::new(Vec::new())),
            imported_modules: Arc::clone(&self.imported_modules),
            nested_forwarded_modules: self.nested_forwarded_modules.as_ref().map(Arc::clone),
            configurable_variables: Arc::clone(&self.configurable_variables),
        }
    }

    pub fn to_dummy_module(&self, span: Span) -> Module {
        Module::Environment {
            scope: ModuleScope::new(),
            upstream: Vec::new(),
            extension_store: ExtensionStore::new(span),
            env: self.clone(),
        }
    }

    /// Makes the members forwarded by [module] available in the current
    /// environment.
    ///
    /// This is called when [module] is `@import`ed.
    pub fn import_forwards(&mut self, _env: Module) {
        if let Module::Environment { env, .. } = _env {
            let mut forwarded = env.forwarded_modules;

            if (*forwarded).borrow().is_empty() {
                return;
            }

            // Omit modules from [forwarded] that are already globally available and
            // forwarded in this module.
            let forwarded_modules = Arc::clone(&self.forwarded_modules);
            if !(*forwarded_modules).borrow().is_empty() {
                // todo: intermediate name
                let mut x = Vec::new();
                for entry in (*forwarded).borrow().iter() {
                    if !forwarded_modules
                        .borrow()
                        .iter()
                        .any(|module| Arc::ptr_eq(module, entry))
                        || !self
                            .global_modules
                            .iter()
                            .any(|module| Arc::ptr_eq(module, entry))
                    {
                        x.push(Arc::clone(entry));
                    }
                }

                forwarded = Arc::new(RefCell::new(x));
            }

            let forwarded_var_names = forwarded
                .borrow()
                .iter()
                .flat_map(|module| (*module).borrow().scope().variables.keys())
                .collect::<HashSet<Identifier>>();
            let forwarded_fn_names = forwarded
                .borrow()
                .iter()
                .flat_map(|module| (*module).borrow().scope().functions.keys())
                .collect::<HashSet<Identifier>>();
            let forwarded_mixin_names = forwarded
                .borrow()
                .iter()
                .flat_map(|module| (*module).borrow().scope().mixins.keys())
                .collect::<HashSet<Identifier>>();

            if self.at_root() {
                let mut to_remove = Vec::new();

                // Hide members from modules that have already been imported or
                // forwarded that would otherwise conflict with the @imported members.
                for (idx, module) in (*self.imported_modules).borrow().iter().enumerate() {
                    let shadowed = ShadowedModule::if_necessary(
                        Arc::clone(module),
                        Some(&forwarded_var_names),
                        Some(&forwarded_fn_names),
                        Some(&forwarded_mixin_names),
                    );

                    if shadowed.is_some() {
                        to_remove.push(idx);
                    }
                }

                let mut imported_modules = (*self.imported_modules).borrow_mut();

                for &idx in to_remove.iter().rev() {
                    imported_modules.remove(idx);
                }

                to_remove.clear();

                for (idx, module) in (*self.forwarded_modules).borrow().iter().enumerate() {
                    let shadowed = ShadowedModule::if_necessary(
                        Arc::clone(module),
                        Some(&forwarded_var_names),
                        Some(&forwarded_fn_names),
                        Some(&forwarded_mixin_names),
                    );

                    if shadowed.is_some() {
                        to_remove.push(idx);
                    }
                }

                let mut forwarded_modules = (*self.forwarded_modules).borrow_mut();

                for &idx in to_remove.iter().rev() {
                    forwarded_modules.remove(idx);
                }

                imported_modules.extend(forwarded.borrow().iter().map(Arc::clone));
                forwarded_modules.extend(forwarded.borrow().iter().map(Arc::clone));
            } else {
                self.nested_forwarded_modules
                    .get_or_insert_with(|| {
                        Arc::new(RefCell::new(
                            (0..self.scopes.len())
                                .map(|_| Arc::new(RefCell::new(Vec::new())))
                                .collect(),
                        ))
                    })
                    .borrow_mut()
                    .last_mut()
                    .unwrap()
                    .borrow_mut()
                    .extend(forwarded.borrow().iter().map(Arc::clone));
            }

            // Remove existing member definitions that are now shadowed by the
            // forwarded modules.
            for variable in forwarded_var_names {
                (*self.scopes.variables)
                    .borrow_mut()
                    .last_mut()
                    .unwrap()
                    .borrow_mut()
                    .remove(&variable);
            }
            self.scopes.last_variable_index = None;

            for func in forwarded_fn_names {
                (*self.scopes.functions)
                    .borrow_mut()
                    .last_mut()
                    .unwrap()
                    .borrow_mut()
                    .remove(&func);
            }
            for mixin in forwarded_mixin_names {
                (*self.scopes.mixins)
                    .borrow_mut()
                    .last_mut()
                    .unwrap()
                    .borrow_mut()
                    .remove(&mixin);
            }
        }
    }

    /// Collects every variable visible at an `@import` into a configuration
    /// for the modules the imported file `@forward`s.
    ///
    /// Scope variables come first, then variables reaching this environment
    /// through earlier `@import`s of forwarding files -- at the root and in
    /// nested import contexts respectively. Later sources overwrite earlier
    /// ones, matching the lookup order for the same names: a variable
    /// forwarded by a previous `@import` configures a later one even though it
    /// lives in a module rather than a scope (the sass/dart-sass#2641 shape),
    /// and `import_forwards` has already removed any scope definition it
    /// shadows.
    pub fn to_implicit_configuration(&self) -> Configuration {
        let mut configuration = BTreeMap::new();

        let variables = (*self.scopes.variables).borrow();

        for variables in variables.iter() {
            let entries = (**variables).borrow();
            for (key, value) in entries.iter() {
                // Implicit configurations are never invalid, making [configurationSpan]
                // unnecessary, so we pass null here to avoid having to compute it.
                configuration.insert(*key, ConfiguredValue::implicit(value.clone()));
            }
        }

        for module in (*self.imported_modules).borrow().iter() {
            let scope = (**module).borrow().scope();
            for key in scope.variables.keys() {
                if let Some(value) = scope.variables.get(key) {
                    configuration.insert(key, ConfiguredValue::implicit(value));
                }
            }
        }

        if let Some(nested_forwarded_modules) = &self.nested_forwarded_modules {
            for modules in nested_forwarded_modules.borrow().iter() {
                for module in modules.borrow().iter() {
                    let scope = (**module).borrow().scope();
                    for key in scope.variables.keys() {
                        if let Some(value) = scope.variables.get(key) {
                            configuration.insert(key, ConfiguredValue::implicit(value));
                        }
                    }
                }
            }
        }

        Configuration::implicit(configuration)
    }

    /// Records a `@forward`ed module so its members are re-exported.
    ///
    /// Two forwarded modules that define the same member are an error as soon
    /// as the second is forwarded, even if nothing ever names it -- unlike
    /// `@use ... as *`, which only complains at the point of use.
    pub fn forward_module(
        &mut self,
        module: Arc<RefCell<Module>>,
        rule: AstForwardRule,
    ) -> SassResult<()> {
        let span = rule.span;
        let view = ForwardedModule::if_necessary(module, rule);

        {
            let forwarded = (*self.forwarded_modules).borrow();
            let scope = (*view).borrow().scope();

            for other in forwarded.iter() {
                let other_scope = (**other).borrow().scope();

                Self::assert_no_forward_conflict(
                    &scope.variables,
                    &other_scope.variables,
                    "variable",
                    "$",
                    span,
                )?;
                Self::assert_no_forward_conflict(
                    &scope.functions,
                    &other_scope.functions,
                    "function",
                    "",
                    span,
                )?;
                Self::assert_no_forward_conflict(
                    &scope.mixins,
                    &other_scope.mixins,
                    "mixin",
                    "",
                    span,
                )?;
            }
        }

        (*self.forwarded_modules).borrow_mut().push(view);

        Ok(())
    }

    fn assert_no_forward_conflict<T: std::fmt::Debug + Clone + 'static>(
        scope: &Arc<dyn MapView<Value = T>>,
        other: &Arc<dyn MapView<Value = T>>,
        ty: &str,
        sigil: &str,
        span: Span,
    ) -> SassResult<()> {
        for name in scope.keys() {
            let identity = match other.identity(name) {
                Some(identity) => identity,
                None => continue,
            };

            // Both modules re-export the same declaration, which is one member
            // reached two ways rather than two members with one name.
            if scope.identity(name) == Some(identity) {
                continue;
            }

            return Err((
                format!(
                    "Two forwarded modules both define a {} named {}{}.",
                    ty, sigil, name
                ),
                span,
            )
                .into());
        }

        Ok(())
    }

    /// Records that a `!default` declaration at this environment's root made
    /// `name` configurable.
    pub fn mark_variable_configurable(&mut self, name: Identifier) {
        (*self.configurable_variables).borrow_mut().insert(name);
    }

    pub fn insert_mixin(&mut self, name: Identifier, mixin: Mixin) {
        self.scopes.insert_mixin(name, mixin);
    }

    pub fn mixin_exists(&self, name: Identifier) -> bool {
        self.scopes.mixin_exists(name)
    }

    pub fn get_mixin(
        &self,
        name: Spanned<Identifier>,
        namespace: Option<Spanned<Identifier>>,
    ) -> SassResult<Mixin> {
        if let Some(namespace) = namespace {
            let modules = (*self.modules).borrow();
            let module = modules.get(namespace.node, namespace.span)?;
            return (*module).borrow().get_mixin(name);
        }

        match self.scopes.get_mixin(name) {
            Ok(v) => Ok(v),
            Err(e) => {
                if let Some(v) = self.get_mixin_from_global_modules(name.node, name.span)? {
                    return Ok(v);
                }

                Err(e)
            }
        }
    }

    pub fn insert_fn(&mut self, func: SassFunction) {
        self.scopes.insert_fn(func);
    }

    pub fn fn_exists(&self, name: Identifier) -> bool {
        self.scopes.fn_exists(name)
    }

    pub fn get_fn(
        &self,
        name: Identifier,
        namespace: Option<Spanned<Identifier>>,
        span: Span,
    ) -> SassResult<Option<SassFunction>> {
        if let Some(namespace) = namespace {
            let modules = (*self.modules).borrow();
            let module = modules.get(namespace.node, namespace.span)?;
            return Ok((*module).borrow().get_fn(name));
        }

        if let Some(func) = self.scopes.get_fn(name) {
            return Ok(Some(func));
        }

        // The call site's span is not threaded down here, so the error points
        // at the module list instead of the use. Both name the same mistake.
        self.get_function_from_global_modules(name, span)
    }

    pub fn var_exists(
        &self,
        name: Identifier,
        namespace: Option<Spanned<Identifier>>,
    ) -> SassResult<bool> {
        if let Some(namespace) = namespace {
            let modules = (*self.modules).borrow();
            let module = modules.get(namespace.node, namespace.span)?;
            return Ok((*module).borrow().var_exists(name));
        }

        Ok(self.scopes.var_exists(name))
    }

    pub fn get_var(
        &mut self,
        name: Spanned<Identifier>,
        namespace: Option<Spanned<Identifier>>,
    ) -> SassResult<Value> {
        if let Some(namespace) = namespace {
            let modules = (*self.modules).borrow();
            let module = modules.get(namespace.node, namespace.span)?;
            return (*module).borrow().get_var(name);
        }

        match self.scopes.get_var(name) {
            Ok(v) => Ok(v),
            Err(e) => match self.get_variable_from_global_modules(name.node, name.span)? {
                Some(v) => Ok(v),
                None => Err(e),
            },
        }
    }

    pub fn insert_var(
        &mut self,
        name: Spanned<Identifier>,
        namespace: Option<Spanned<Identifier>>,
        value: Value,
        is_global: bool,
        in_semi_global_scope: bool,
    ) -> SassResult<()> {
        if let Some(namespace) = namespace {
            let mut modules = (*self.modules).borrow_mut();
            let module = modules.get_mut(namespace.node, namespace.span)?;
            (*module).borrow_mut().update_var(name, value)?;
            return Ok(());
        }

        if is_global || self.at_root() {
            // If this module doesn't already contain a variable named [name], try
            // setting it in a global module.
            if !self.scopes.global_var_exists(name.node) {
                let module_with_name = self.from_one_module(
                    name.node,
                    "variable",
                    name.span,
                    |module| {
                        if module.borrow().var_exists(*name) {
                            Some(Arc::clone(module))
                        } else {
                            None
                        }
                    },
                    |module| (**module).borrow().scope().variables.identity(name.node),
                )?;

                if let Some(module_with_name) = module_with_name {
                    module_with_name.borrow_mut().update_var(name, value)?;
                    return Ok(());
                }
            }

            self.scopes.insert_var(0, name.node, value);
            return Ok(());
        }

        let mut index = self
            .scopes
            .find_var(name.node)
            .unwrap_or(self.scopes.len() - 1);

        if !in_semi_global_scope && index == 0 {
            index = self.scopes.len() - 1;
        }

        self.scopes.last_variable_index = Some((name.node, index));

        self.scopes.insert_var(index, name.node, value);

        Ok(())
    }

    pub fn at_root(&self) -> bool {
        self.scopes.len() == 1
    }

    pub fn scopes_mut(&mut self) -> &mut Scopes {
        &mut self.scopes
    }

    pub fn global_vars(&self) -> Arc<RefCell<BTreeMap<Identifier, Value>>> {
        self.scopes.global_variables()
    }

    pub fn global_mixins(&self) -> Arc<RefCell<BTreeMap<Identifier, Mixin>>> {
        self.scopes.global_mixins()
    }

    pub fn global_functions(&self) -> Arc<RefCell<BTreeMap<Identifier, SassFunction>>> {
        self.scopes.global_functions()
    }

    fn get_variable_from_global_modules(
        &self,
        name: Identifier,
        span: Span,
    ) -> SassResult<Option<Value>> {
        self.from_one_module(
            name,
            "variable",
            span,
            |module| (**module).borrow().get_var_no_err(name),
            |module| (**module).borrow().scope().variables.identity(name),
        )
    }

    fn get_function_from_global_modules(
        &self,
        name: Identifier,
        span: Span,
    ) -> SassResult<Option<SassFunction>> {
        self.from_one_module(
            name,
            "function",
            span,
            |module| (**module).borrow().get_fn(name),
            |module| (**module).borrow().scope().functions.identity(name),
        )
    }

    fn get_mixin_from_global_modules(
        &self,
        name: Identifier,
        span: Span,
    ) -> SassResult<Option<Mixin>> {
        self.from_one_module(
            name,
            "mixin",
            span,
            |module| (**module).borrow().get_mixin_no_err(name),
            |module| (**module).borrow().scope().mixins.identity(name),
        )
    }

    pub fn add_module(
        &mut self,
        namespace: Option<Identifier>,
        module: Arc<RefCell<Module>>,
        span: Span,
    ) -> SassResult<()> {
        match namespace {
            Some(namespace) => {
                (*self.modules)
                    .borrow_mut()
                    .insert(namespace, module, span)?;
            }
            None => {
                for name in (*self.scopes.global_variables()).borrow().keys() {
                    if (*module).borrow().var_exists(*name) {
                        return Err((
                            format!("This module and the new module both define a variable named \"${name}\".", name = name)
                        , span).into());
                    }
                }

                self.global_modules.push(module);
            }
        }

        Ok(())
    }

    pub fn to_module(
        self,
        extension_store: ExtensionStore,
        upstream: Vec<Arc<RefCell<Module>>>,
    ) -> Arc<RefCell<Module>> {
        debug_assert!(self.at_root());

        Arc::new(RefCell::new(Module::new_env(
            self,
            extension_store,
            upstream,
        )))
    }

    /// Finds a member in the modules loaded without a namespace.
    ///
    /// A member that two `@use ... as *` modules both provide is ambiguous, and
    /// naming it is an error rather than a silent choice between them.
    fn from_one_module<T>(
        &self,
        _name: Identifier,
        ty: &str,
        span: Span,
        callback: impl Fn(&Arc<RefCell<Module>>) -> Option<T>,
        identify: impl Fn(&Arc<RefCell<Module>>) -> Option<usize>,
    ) -> SassResult<Option<T>> {
        if let Some(nested_forwarded_modules) = &self.nested_forwarded_modules {
            for modules in nested_forwarded_modules.borrow().iter().rev() {
                for module in modules.borrow().iter().rev() {
                    if let Some(value) = callback(module) {
                        return Ok(Some(value));
                    }
                }
            }
        }

        for module in self.imported_modules.borrow().iter() {
            if let Some(value) = callback(module) {
                return Ok(Some(value));
            }
        }

        let mut value: Option<T> = None;
        let mut identity: Option<Option<usize>> = None;

        for module in &self.global_modules {
            let value_in_module = match callback(module) {
                Some(v) => v,
                None => continue,
            };

            let identity_in_module = identify(module);

            // Two modules that re-export the same declaration offer one member
            // reached two ways, not two members with one name.
            if let Some(identity) = identity {
                if identity == identity_in_module && identity.is_some() {
                    continue;
                }

                return Err((
                    format!("This {} is available from multiple global modules.", ty),
                    span,
                )
                    .into());
            }

            value = Some(value_in_module);
            identity = Some(identity_in_module);
        }

        Ok(value)
    }
}