Skip to main content

rust_css_parser/ast/
cache.rs

1//! Port of `src/ast/cache.ts`: structural memoization of values computed from token trees.
2//!
3//! A token tree is serialized into i32 values (a header with the type, the color type and the fields that follow, the
4//! fields that are not empty, then the token list and the children list). The typescript open addressing table over a
5//! key pool is ported as is: the keys are appended to a pool, the slots are numbered in insertion order, a lookup
6//! reuses a scratch buffer and a miss keeps the key.
7//!
8//! The keys do not reference arena ids, the interned string ids are part of the keys: a memo must not outlive the
9//! string table of the arena.
10
11use crate::ast::arena::Arena;
12
13const NAME: i32 = 1 << 16;
14const STRING: i32 = 1 << 17;
15const UNIT: i32 = 1 << 18;
16/// 32 bits integer numeric value, other than 0
17const INTEGER: i32 = 1 << 19;
18/// raw bits of the numeric value (2 values)
19const NUMBER: i32 = 1 << 20;
20/// token list, terminated by an end marker
21const TOKENS: i32 = 1 << 21;
22/// children list, terminated by an end marker
23const CHILDREN: i32 = 1 << 22;
24/// end of a token list or of a children list
25const END: i32 = -1;
26
27/// memoize values by token structure. lookups return a slot, the value of a slot is `None` until it is set
28pub struct StructuralMemo<T> {
29    /// values by slot
30    pub values: Vec<Option<T>>,
31    /// number of distinct structures
32    pub size: usize,
33    /// number of lookups that found an existing entry
34    pub hits: usize,
35    /// open addressing table: slot + 1 by hash index, 0 when empty
36    table: Vec<u32>,
37    /// the keys, one after the other (no allocation per key)
38    pool: Vec<i32>,
39    /// start, length and hash of the key of each slot
40    keys: Vec<(u32, u32, u64)>,
41    scratch: Vec<i32>,
42    /// compare the numeric values with all the `NaN` values equal (the raw bits are compared otherwise)
43    numeric_equality: bool,
44}
45
46impl<T> Default for StructuralMemo<T> {
47    fn default() -> Self {
48        Self::new(false)
49    }
50}
51
52impl<T> StructuralMemo<T> {
53    pub fn new(numeric_equality: bool) -> Self {
54        Self {
55            values: Vec::new(),
56            size: 0,
57            hits: 0,
58            table: vec![0; 256],
59            pool: Vec::new(),
60            keys: Vec::new(),
61            scratch: Vec::with_capacity(64),
62            numeric_equality,
63        }
64    }
65
66    /// slot of a token list (the token and its next siblings). `prefix`: extra key component, not negative
67    pub fn list(&mut self, arena: &Arena, first: u32, prefix: i32) -> usize {
68        self.scratch.clear();
69        self.scratch.push(prefix);
70        let mut token = first;
71        while token != 0 {
72            self.serialize(arena, token);
73            token = arena.next_sibling.get(token);
74        }
75        self.lookup()
76    }
77
78    /// slot of a single token (its next siblings are ignored)
79    pub fn token(&mut self, arena: &Arena, token: u32) -> usize {
80        self.scratch.clear();
81        self.serialize(arena, token);
82        self.lookup()
83    }
84
85    pub fn get(&self, slot: usize) -> Option<&T> {
86        self.values.get(slot).and_then(|v| v.as_ref())
87    }
88
89    pub fn set(&mut self, slot: usize, value: T) {
90        self.values[slot] = Some(value);
91    }
92
93    /// drop the entries
94    pub fn clear(&mut self) {
95        self.values.clear();
96        self.table.fill(0);
97        self.pool.clear();
98        self.keys.clear();
99        self.size = 0;
100        self.hits = 0;
101    }
102
103    fn serialize(&mut self, arena: &Arena, token: u32) {
104        let name = arena.name.get(token) as i32;
105        let str = arena.string_value.get(token) as i32;
106        let unit = arena.unit.get(token) as i32;
107        let first_token = arena.first_token.get(token);
108        let first_child = arena.first_child.get(token);
109        let mut value = arena.numeric_value.get(token);
110        // type and color type are 8 bits values
111        let mut header = arena.data_types.get(token) as i32 | ((arena.color_type.get(token) as i32) << 8);
112        let index = self.scratch.len();
113        self.scratch.push(0);
114        if name != 0 {
115            header |= NAME;
116            self.scratch.push(name);
117        }
118        if str != 0 {
119            header |= STRING;
120            self.scratch.push(str);
121        }
122        if unit != 0 {
123            header |= UNIT;
124            self.scratch.push(unit);
125        }
126        if self.numeric_equality && value.is_nan() {
127            value = f64::NAN;
128        }
129        // 0 is not serialized. -0 is not an integer: its raw bits are serialized
130        if value != 0.0 || value.is_sign_negative() && value == 0.0 {
131            if value.fract() == 0.0 && value >= i32::MIN as f64 && value <= i32::MAX as f64 && value != 0.0 {
132                header |= INTEGER;
133                self.scratch.push(value as i32);
134            } else {
135                header |= NUMBER;
136                let bits = if value.is_nan() { f64::NAN.to_bits() } else { value.to_bits() };
137                self.scratch.push(bits as u32 as i32);
138                self.scratch.push((bits >> 32) as u32 as i32);
139            }
140        }
141        if first_token != 0 {
142            header |= TOKENS;
143        }
144        if first_child != 0 {
145            header |= CHILDREN;
146        }
147        self.scratch[index] = header;
148        if first_token != 0 {
149            let mut child = first_token;
150            while child != 0 {
151                self.serialize(arena, child);
152                child = arena.next_sibling.get(child);
153            }
154            self.scratch.push(END);
155        }
156        if first_child != 0 {
157            let mut child = first_child;
158            while child != 0 {
159                self.serialize(arena, child);
160                child = arena.next_sibling.get(child);
161            }
162            self.scratch.push(END);
163        }
164    }
165
166    /// find or insert the serialized key: the key is hashed once, a new key is appended to the pool
167    fn lookup(&mut self) -> usize {
168        let hash = hash_key(&self.scratch);
169        let mask = self.table.len() - 1;
170        let mut index = hash as usize & mask;
171        loop {
172            let entry = self.table[index];
173            if entry == 0 {
174                break;
175            }
176            let slot = entry as usize - 1;
177            let (start, length, key_hash) = self.keys[slot];
178            if key_hash == hash && self.pool[start as usize..(start + length) as usize] == self.scratch[..] {
179                self.hits += 1;
180                return slot;
181            }
182            index = (index + 1) & mask;
183        }
184        let slot = self.size;
185        self.size += 1;
186        self.keys.push((self.pool.len() as u32, self.scratch.len() as u32, hash));
187        self.pool.extend_from_slice(&self.scratch);
188        self.values.push(None);
189        self.table[index] = slot as u32 + 1;
190        // load factor 1/2
191        if self.size * 2 > self.table.len() {
192            self.rehash(self.table.len() * 2);
193        }
194        slot
195    }
196
197    fn rehash(&mut self, capacity: usize) {
198        self.table.clear();
199        self.table.resize(capacity, 0);
200        let mask = capacity - 1;
201        for (slot, &(_, _, hash)) in self.keys.iter().enumerate() {
202            let mut index = hash as usize & mask;
203            while self.table[index] != 0 {
204                index = (index + 1) & mask;
205            }
206            self.table[index] = slot as u32 + 1;
207        }
208    }
209}
210
211/// Fx hash of a serialized key, with a final mix: the low bits index the table
212fn hash_key(key: &[i32]) -> u64 {
213    let mut hash: u64 = key.len() as u64;
214    for &value in key {
215        hash = (hash.rotate_left(5) ^ value as u32 as u64).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95);
216    }
217    hash ^ (hash >> 32)
218}