Skip to main content

css_module_lexer/
dependency_types.rs

1//! Public dependency result types and their typed side-table storage.
2
3use std::{
4  fmt::Display,
5  hash::{Hash, Hasher},
6  marker::PhantomData,
7  ops::Index,
8};
9
10use crate::lexer::Pos;
11
12#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
13pub struct Range {
14  pub start: Pos,
15  pub end: Pos,
16}
17
18impl Range {
19  pub fn new(start: Pos, end: Pos) -> Self {
20    Self { start, end }
21  }
22}
23
24/// A half-open index range into one of [`DependencyContext`]'s flat payload
25/// vectors. Keeping list payloads out of [`Dependency`] prevents rare, large
26/// variants from determining the size of every dependency value. `T` binds the
27/// range to its payload element type without adding runtime storage.
28#[derive(Debug, Hash, PartialEq, Eq)]
29pub struct DependencyListRange<T> {
30  start: u32,
31  end: u32,
32  marker: PhantomData<fn() -> T>,
33}
34
35impl<T> Copy for DependencyListRange<T> {}
36
37impl<T> Clone for DependencyListRange<T> {
38  fn clone(&self) -> Self {
39    *self
40  }
41}
42
43impl<T> DependencyListRange<T> {
44  pub(crate) fn from_bounds(start: usize, end: usize) -> Self {
45    assert!(start <= end, "dependency list range is reversed");
46    assert!(
47      u32::try_from(end).is_ok(),
48      "dependency list storage is too large"
49    );
50    Self {
51      start: start as u32,
52      end: end as u32,
53      marker: PhantomData,
54    }
55  }
56
57  pub(crate) fn as_usize_range(self) -> std::ops::Range<usize> {
58    self.start as usize..self.end as usize
59  }
60
61  pub fn start(self) -> u32 {
62    self.start
63  }
64
65  pub fn end(self) -> u32 {
66    self.end
67  }
68
69  pub fn len(self) -> usize {
70    (self.end - self.start) as usize
71  }
72
73  pub fn is_empty(self) -> bool {
74    self.start == self.end
75  }
76}
77
78/// A typed index into one of [`DependencyContext`]'s side tables.
79///
80/// `T` identifies the target table without adding runtime storage. Keeping
81/// rare payloads behind an index prevents them from determining the size of
82/// every [`Dependency`] value.
83#[derive(Debug, Hash, PartialEq, Eq)]
84pub struct DependencyIndex<T> {
85  index: u32,
86  marker: PhantomData<fn() -> T>,
87}
88
89impl<T> Copy for DependencyIndex<T> {}
90
91impl<T> Clone for DependencyIndex<T> {
92  fn clone(&self) -> Self {
93    *self
94  }
95}
96
97impl<T> DependencyIndex<T> {
98  pub(crate) fn from_index(index: usize) -> Self {
99    assert!(
100      u32::try_from(index).is_ok(),
101      "dependency side table is too large"
102    );
103    Self {
104      index: index as u32,
105      marker: PhantomData,
106    }
107  }
108
109  pub(crate) fn as_usize(self) -> usize {
110    self.index as usize
111  }
112
113  pub fn index(self) -> u32 {
114    self.index
115  }
116}
117
118#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
119pub enum Mode {
120  Local,
121  Global,
122  Pure,
123  Css,
124}
125
126#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
127pub struct ValueAtRuleImportItem<'s> {
128  local_name: &'s str,
129  import_name: &'s str,
130}
131
132impl<'s> ValueAtRuleImportItem<'s> {
133  pub(crate) fn new(local_name: &'s str, import_name: &'s str) -> Self {
134    Self {
135      local_name,
136      import_name,
137    }
138  }
139
140  pub fn local_name(&self) -> &'s str {
141    self.local_name
142  }
143
144  pub fn import_name(&self) -> &'s str {
145    self.import_name
146  }
147}
148
149#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
150pub struct ImportAttributes<'s> {
151  layer: Option<&'s str>,
152  supports: Option<&'s str>,
153  media: Option<&'s str>,
154}
155
156impl<'s> ImportAttributes<'s> {
157  pub(crate) fn new(
158    layer: Option<&'s str>,
159    supports: Option<&'s str>,
160    media: Option<&'s str>,
161  ) -> Self {
162    Self {
163      layer,
164      supports,
165      media,
166    }
167  }
168
169  pub fn layer(&self) -> Option<&'s str> {
170    self.layer
171  }
172
173  pub fn supports(&self) -> Option<&'s str> {
174    self.supports
175  }
176
177  pub fn media(&self) -> Option<&'s str> {
178    self.media
179  }
180}
181
182#[derive(Debug, Clone, Hash, PartialEq, Eq)]
183pub enum Dependency<'s> {
184  Url {
185    request: &'s str,
186    range: Range,
187    kind: UrlRangeKind,
188    magic_comments: Option<&'s str>,
189  },
190  Import {
191    request: &'s str,
192    range: Range,
193    attributes: DependencyIndex<ImportAttributes<'s>>,
194    magic_comments: Option<&'s str>,
195  },
196  ICSSImportUrl {
197    name: &'s str,
198    range: Range,
199    name_range: Range,
200  },
201  Replace {
202    content: &'s str,
203    range: Range,
204  },
205  Charset {
206    value: &'s str,
207    range: Range,
208  },
209  LocalClass {
210    name: &'s str,
211    range: Range,
212    explicit: bool,
213  },
214  LocalId {
215    name: &'s str,
216    range: Range,
217    explicit: bool,
218  },
219  LocalVar {
220    name: &'s str,
221    range: Range,
222    from: Option<&'s str>,
223    /// Whether `from` is the unquoted `global` keyword rather than a request.
224    from_is_global: bool,
225  },
226  LocalVarDecl {
227    name: &'s str,
228    range: Range,
229  },
230  LocalPropertyDecl {
231    name: &'s str,
232    range: Range,
233  },
234  LocalKeyframes {
235    name: &'s str,
236    range: Range,
237  },
238  LocalKeyframesDecl {
239    name: &'s str,
240    range: Range,
241  },
242  LocalCounterStyle {
243    name: &'s str,
244    range: Range,
245  },
246  LocalCounterStyleDecl {
247    name: &'s str,
248    range: Range,
249  },
250  LocalFontPalette {
251    name: &'s str,
252    range: Range,
253  },
254  LocalFontPaletteDecl {
255    name: &'s str,
256    range: Range,
257  },
258  LocalContainer {
259    name: &'s str,
260    range: Range,
261  },
262  LocalContainerDecl {
263    name: &'s str,
264    range: Range,
265  },
266  LocalFunction {
267    name: &'s str,
268    range: Range,
269  },
270  LocalFunctionDecl {
271    name: &'s str,
272    range: Range,
273  },
274  LocalGrid {
275    name: &'s str,
276    range: Range,
277  },
278  LocalGridDecl {
279    name: &'s str,
280    range: Range,
281  },
282  Composes {
283    local_classes: DependencyListRange<&'s str>,
284    names: DependencyListRange<&'s str>,
285    from: Option<&'s str>,
286    /// Whether `from` is the unquoted `global` keyword rather than a request.
287    from_is_global: bool,
288    range: Range,
289  },
290  ICSSImportFrom {
291    path: &'s str,
292  },
293  ICSSImportValue {
294    prop: &'s str,
295    value: &'s str,
296  },
297  ICSSExportValue {
298    prop: &'s str,
299    value: &'s str,
300    /// Whether this defines an `@value` symbol rather than a plain `:export`.
301    is_at_value: bool,
302    /// Identifier token ranges relative to `value`, collected while scanning `@value`.
303    identifiers: DependencyListRange<Range>,
304  },
305  ICSSSymbol {
306    name: &'s str,
307    range: Range,
308  },
309}
310
311/// Owns dependencies and the side-table payloads referenced by them.
312///
313/// `Dependency` values are intentionally cheap to move. Rare or variable-length
314/// data is appended to context vectors and referenced through [`DependencyIndex`]
315/// or [`DependencyListRange`]. Consumers should resolve those handles through
316/// this type rather than retaining raw indices independently.
317#[derive(Debug, Clone, Default)]
318pub struct DependencyContext<'s> {
319  dependencies: Vec<Dependency<'s>>,
320  dashed_ident_occurrences: Vec<Range>,
321  import_attributes: Vec<ImportAttributes<'s>>,
322  composes_local_classes: Vec<&'s str>,
323  composes_names: Vec<&'s str>,
324  value_at_rule_import_items: Vec<ValueAtRuleImportItem<'s>>,
325  value_at_rule_identifiers: Vec<Range>,
326}
327
328impl<'s> DependencyContext<'s> {
329  pub fn new() -> Self {
330    Self::default()
331  }
332
333  pub(crate) fn reserve_estimated_capacity(&mut self, input_len: usize, mode: Mode) {
334    let estimate = DependencyContextCapacity::estimate(input_len, mode);
335    reserve_estimated_capacity(&mut self.dependencies, estimate.dependencies);
336    reserve_estimated_capacity(
337      &mut self.import_attributes,
338      estimate.import_attributes as usize,
339    );
340    reserve_estimated_capacity(
341      &mut self.composes_local_classes,
342      estimate.composes_local_classes as usize,
343    );
344    reserve_estimated_capacity(&mut self.composes_names, estimate.composes_names as usize);
345    reserve_estimated_capacity(
346      &mut self.value_at_rule_import_items,
347      estimate.value_at_rule_import_items as usize,
348    );
349  }
350
351  pub(crate) fn checkpoint(&self) -> [usize; 5] {
352    [
353      self.dependencies.len(),
354      self.import_attributes.len(),
355      self.composes_local_classes.len(),
356      self.composes_names.len(),
357      self.value_at_rule_import_items.len(),
358    ]
359  }
360
361  pub(crate) fn rollback(&mut self, checkpoint: [usize; 5]) {
362    self.dependencies.truncate(checkpoint[0]);
363    self.import_attributes.truncate(checkpoint[1]);
364    self.composes_local_classes.truncate(checkpoint[2]);
365    self.composes_names.truncate(checkpoint[3]);
366    self.value_at_rule_import_items.truncate(checkpoint[4]);
367  }
368
369  pub fn len(&self) -> usize {
370    self.dependencies.len()
371  }
372
373  pub fn is_empty(&self) -> bool {
374    self.dependencies.is_empty()
375  }
376
377  pub fn get(&self, index: usize) -> Option<&Dependency<'s>> {
378    self.dependencies.get(index)
379  }
380
381  pub fn iter(&self) -> std::slice::Iter<'_, Dependency<'s>> {
382    self.dependencies.iter()
383  }
384
385  pub fn dependencies(&self) -> &[Dependency<'s>] {
386    &self.dependencies
387  }
388
389  pub fn dashed_ident_name_ranges(&self) -> &[Range] {
390    &self.dashed_ident_occurrences
391  }
392
393  pub(crate) fn set_dashed_ident_occurrences(&mut self, occurrences: Vec<Range>) {
394    self.dashed_ident_occurrences = occurrences;
395  }
396
397  pub(crate) fn estimated_dashed_ident_capacity(input_len: usize, mode: Mode) -> usize {
398    DependencyContextCapacity::estimate(input_len, mode).dashed_ident_occurrences
399  }
400
401  pub fn import_attributes(
402    &self,
403    index: DependencyIndex<ImportAttributes<'s>>,
404  ) -> &ImportAttributes<'s> {
405    &self.import_attributes[index.as_usize()]
406  }
407
408  pub fn composes_local_classes(&self, range: DependencyListRange<&'s str>) -> &[&'s str] {
409    &self.composes_local_classes[range.as_usize_range()]
410  }
411
412  pub fn composes_names(&self, range: DependencyListRange<&'s str>) -> &[&'s str] {
413    &self.composes_names[range.as_usize_range()]
414  }
415
416  pub fn value_at_rule_import_items(&self) -> &[ValueAtRuleImportItem<'s>] {
417    &self.value_at_rule_import_items
418  }
419
420  pub fn value_at_rule_identifiers(&self, range: DependencyListRange<Range>) -> &[Range] {
421    &self.value_at_rule_identifiers[range.as_usize_range()]
422  }
423
424  pub(crate) fn value_at_rule_identifiers_checkpoint(&self) -> usize {
425    self.value_at_rule_identifiers.len()
426  }
427
428  pub(crate) fn push_value_at_rule_identifier(&mut self, range: Range) {
429    self.value_at_rule_identifiers.push(range);
430  }
431
432  pub(crate) fn truncate_value_at_rule_identifiers(&mut self, checkpoint: usize) {
433    self.value_at_rule_identifiers.truncate(checkpoint);
434  }
435
436  pub(crate) fn finish_value_at_rule_identifiers(
437    &mut self,
438    checkpoint: usize,
439    value_start: Pos,
440  ) -> DependencyListRange<Range> {
441    let ranges = &mut self.value_at_rule_identifiers;
442    // Discard identifiers belonging to the declaration name, then translate
443    // source offsets into offsets within the (possibly trimmed) value.
444    let first =
445      checkpoint + ranges[checkpoint..].partition_point(|range| range.start < value_start);
446    let end = checkpoint + ranges.len() - first;
447    if first != checkpoint {
448      ranges.copy_within(first.., checkpoint);
449    }
450    ranges.truncate(end);
451    for range in &mut ranges[checkpoint..] {
452      range.start -= value_start;
453      range.end -= value_start;
454    }
455    DependencyListRange::from_bounds(checkpoint, end)
456  }
457
458  pub(crate) fn push_dependency(&mut self, dependency: Dependency<'s>) {
459    self.dependencies.push(dependency);
460  }
461
462  pub(crate) fn push_import(
463    &mut self,
464    request: &'s str,
465    range: Range,
466    layer: Option<&'s str>,
467    supports: Option<&'s str>,
468    media: Option<&'s str>,
469    magic_comments: Option<&'s str>,
470  ) {
471    let attributes = DependencyIndex::from_index(self.import_attributes.len());
472    self
473      .import_attributes
474      .push(ImportAttributes::new(layer, supports, media));
475    self.dependencies.push(Dependency::Import {
476      request,
477      range,
478      attributes,
479      magic_comments,
480    });
481  }
482
483  pub(crate) fn push_value_at_rule_import_item(&mut self, item: ValueAtRuleImportItem<'s>) {
484    self.value_at_rule_import_items.push(item);
485  }
486
487  pub(crate) fn value_at_rule_import_item(&self, index: usize) -> ValueAtRuleImportItem<'s> {
488    self.value_at_rule_import_items[index]
489  }
490
491  pub(crate) fn value_at_rule_import_items_checkpoint(&self) -> usize {
492    self.value_at_rule_import_items.len()
493  }
494
495  pub(crate) fn truncate_value_at_rule_import_items(&mut self, checkpoint: usize) {
496    self.value_at_rule_import_items.truncate(checkpoint);
497  }
498
499  pub(crate) fn finish_value_at_rule_import_items(
500    &self,
501    checkpoint: usize,
502  ) -> DependencyListRange<ValueAtRuleImportItem<'s>> {
503    debug_assert!(checkpoint <= self.value_at_rule_import_items.len());
504    DependencyListRange::from_bounds(checkpoint, self.value_at_rule_import_items.len())
505  }
506
507  pub(crate) fn push_composes(
508    &mut self,
509    local_classes: impl IntoIterator<Item = &'s str>,
510    names: impl IntoIterator<Item = &'s str>,
511    from: Option<&'s str>,
512    from_is_global: bool,
513    range: Range,
514  ) {
515    let local_classes_start = self.composes_local_classes.len();
516    self.composes_local_classes.extend(local_classes);
517    let local_classes = DependencyListRange::<&'s str>::from_bounds(
518      local_classes_start,
519      self.composes_local_classes.len(),
520    );
521
522    let names_start = self.composes_names.len();
523    self.composes_names.extend(names);
524    let names = DependencyListRange::<&'s str>::from_bounds(names_start, self.composes_names.len());
525
526    self.dependencies.push(Dependency::Composes {
527      local_classes,
528      names,
529      from,
530      from_is_global,
531      range,
532    });
533  }
534}
535
536impl PartialEq for DependencyContext<'_> {
537  fn eq(&self, other: &Self) -> bool {
538    self.dependencies == other.dependencies
539      && self.dashed_ident_occurrences == other.dashed_ident_occurrences
540      && self.import_attributes == other.import_attributes
541      && self.composes_local_classes == other.composes_local_classes
542      && self.composes_names == other.composes_names
543      && self.value_at_rule_import_items == other.value_at_rule_import_items
544  }
545}
546
547impl Eq for DependencyContext<'_> {}
548
549impl Hash for DependencyContext<'_> {
550  fn hash<H: Hasher>(&self, state: &mut H) {
551    self.dependencies.hash(state);
552    self.dashed_ident_occurrences.hash(state);
553    self.import_attributes.hash(state);
554    self.composes_local_classes.hash(state);
555    self.composes_names.hash(state);
556    self.value_at_rule_import_items.hash(state);
557  }
558}
559
560#[derive(Debug, Clone, Copy, Default)]
561struct DependencyContextCapacity {
562  dependencies: usize,
563  dashed_ident_occurrences: usize,
564  import_attributes: u16,
565  composes_local_classes: u16,
566  composes_names: u16,
567  value_at_rule_import_items: u16,
568}
569
570impl DependencyContextCapacity {
571  fn estimate(input_len: usize, mode: Mode) -> Self {
572    let dependency_denominator = match mode {
573      Mode::Local | Mode::Pure => 32,
574      Mode::Global => 80,
575      Mode::Css => 4096,
576    };
577    let dependencies = estimate_capacity(input_len, dependency_denominator, 4, 8192);
578    let dashed_ident_occurrences = if mode != Mode::Css {
579      estimate_capacity(input_len, 64, 2, 8192)
580    } else {
581      0
582    };
583    let import_attributes = estimate_capacity(input_len, 8192, 2, 1024);
584    let (composes_local_classes, composes_names, value_at_rule_import_items) = match mode {
585      Mode::Local | Mode::Pure => (
586        estimate_capacity(input_len, 640, 2, 4096),
587        estimate_capacity(input_len, 576, 2, 4096),
588        estimate_capacity(input_len, 1792, 2, 4096),
589      ),
590      Mode::Global => (
591        estimate_capacity(input_len, 3880, 2, 4096),
592        estimate_capacity(input_len, 3880, 2, 4096),
593        estimate_capacity(input_len, 1774, 2, 4096),
594      ),
595      Mode::Css => (0, 0, 0),
596    };
597    Self {
598      dependencies,
599      dashed_ident_occurrences,
600      import_attributes: import_attributes as u16,
601      composes_local_classes: composes_local_classes as u16,
602      composes_names: composes_names as u16,
603      value_at_rule_import_items: value_at_rule_import_items as u16,
604    }
605  }
606}
607
608fn estimate_capacity(
609  input_len: usize,
610  denominator: usize,
611  minimum: usize,
612  maximum: usize,
613) -> usize {
614  input_len
615    .checked_div(denominator)
616    .unwrap_or(0)
617    .clamp(minimum, maximum)
618}
619
620fn reserve_estimated_capacity<T>(values: &mut Vec<T>, estimated_capacity: usize) {
621  if values.capacity() < estimated_capacity {
622    values.reserve(estimated_capacity.saturating_sub(values.len()));
623  }
624}
625
626impl<'s> Index<usize> for DependencyContext<'s> {
627  type Output = Dependency<'s>;
628
629  fn index(&self, index: usize) -> &Self::Output {
630    &self.dependencies[index]
631  }
632}
633
634impl<'context, 's> IntoIterator for &'context DependencyContext<'s> {
635  type Item = &'context Dependency<'s>;
636  type IntoIter = std::slice::Iter<'context, Dependency<'s>>;
637
638  fn into_iter(self) -> Self::IntoIter {
639    self.dependencies.iter()
640  }
641}
642
643#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
644pub enum UrlRangeKind {
645  Function,
646  String,
647}
648
649#[derive(Debug, Clone, Hash, PartialEq, Eq)]
650pub struct Warning<'s> {
651  pub(crate) range: Range,
652  pub(crate) kind: WarningKind<'s>,
653}
654
655impl<'s> Warning<'s> {
656  pub fn new(range: Range, kind: WarningKind<'s>) -> Self {
657    Self { range, kind }
658  }
659
660  pub fn range(&self) -> &Range {
661    &self.range
662  }
663
664  pub fn kind(&self) -> &WarningKind<'s> {
665    &self.kind
666  }
667}
668
669#[derive(Debug, Clone, Hash, PartialEq, Eq)]
670pub enum WarningKind<'s> {
671  Unexpected { message: &'s str },
672  InvalidSelector { message: &'s str },
673  DuplicateUrl { when: &'s str },
674  NamespaceNotSupportedInBundledCss,
675  NotPrecededAtImport,
676  ExpectedUrl { when: &'s str },
677  ExpectedUrlBefore { when: &'s str },
678  ExpectedLayerBefore { when: &'s str },
679  InconsistentModeResult,
680  ExpectedNotInside { pseudo: &'s str },
681  NotPure { message: &'s str },
682  UnexpectedComposition { message: &'s str },
683}
684
685impl Display for Warning<'_> {
686  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
687    match self.kind {
688      WarningKind::Unexpected { message, .. } => write!(f, "{message}"),
689      WarningKind::InvalidSelector { message, .. } => write!(f, "{message}"),
690      WarningKind::DuplicateUrl { when, .. } => {
691        write!(f, "Duplicate of 'url(...)' in '{when}'")
692      }
693      WarningKind::NamespaceNotSupportedInBundledCss { .. } => {
694        write!(f, "'@namespace' is not supported in bundled CSS")
695      }
696      WarningKind::NotPrecededAtImport { .. } => {
697        write!(f, "Any '@import' rules must precede all other rules")
698      }
699      WarningKind::ExpectedUrl { when, .. } => write!(f, "Expected URL in '{when}'"),
700      WarningKind::ExpectedUrlBefore { when, .. } => {
701        write!(
702          f,
703          "An URL in '{when}' should be before 'layer(...)' or 'supports(...)'"
704        )
705      }
706      WarningKind::ExpectedLayerBefore { when, .. } => {
707        write!(
708          f,
709          "The 'layer(...)' in '{when}' should be before 'supports(...)'"
710        )
711      }
712      WarningKind::InconsistentModeResult { .. } => write!(
713        f,
714        "Inconsistent rule global/local (multiple selectors must result in the same mode for the rule)"
715      ),
716      WarningKind::ExpectedNotInside { pseudo, .. } => write!(
717        f,
718        "A '{pseudo}' is not allowed inside of a ':local()' or ':global()'"
719      ),
720      WarningKind::NotPure { message, .. } => {
721        write!(f, "Pure globals is not allowed in pure mode, {message}")
722      }
723      WarningKind::UnexpectedComposition { message, .. } => {
724        write!(f, "Composition is {message}")
725      }
726    }
727  }
728}
729
730#[cfg(test)]
731#[path = "../tests/dependency_types_tests.rs"]
732mod tests;