hyperast 0.2.0

Temporal code analyses at scale
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
use std::{
    cell::{Ref, RefCell},
    collections::hash_map::DefaultHasher,
    fmt::Debug,
    hash::{BuildHasher, Hash, Hasher},
    marker::PhantomData,
    rc::Rc,
};

use crate::{
    compat::{DefaultHashBuilder, HashMap},
    utils::make_hash,
};

pub struct VecHasher<T: Hash> {
    state: u64,
    node_table: Rc<RefCell<Vec<T>>>,
    default: DefaultHasher,
}

impl<T: Hash> Hasher for VecHasher<T> {
    fn write_u8(&mut self, i: u8) {
        self.node_table.borrow()[i as usize].hash(&mut self.default);
        self.state = self.default.finish();
    }
    fn write_u16(&mut self, i: u16) {
        self.node_table.borrow()[i as usize].hash(&mut self.default);
        self.state = self.default.finish();
    }
    fn write_u32(&mut self, i: u32) {
        self.node_table.borrow()[i as usize].hash(&mut self.default);
        self.state = self.default.finish();
    }
    fn write_u64(&mut self, i: u64) {
        self.node_table.borrow()[i as usize].hash(&mut self.default);
        self.state = self.default.finish();
    }
    fn write_usize(&mut self, i: usize) {
        self.node_table.borrow()[i as usize].hash(&mut self.default);
        self.state = self.default.finish();
    }
    fn write(&mut self, _bytes: &[u8]) {
        // for &byte in bytes {
        //     self.state = self.state.rotate_left(8) ^ u64::from(byte);
        // }
        panic!("should not have been called")
    }

    fn finish(&self) -> u64 {
        self.state
    }
}

pub(crate) struct BuildVecHasher<T: Hash> {
    node_table: Rc<RefCell<Vec<T>>>,
}

impl<T: Hash> BuildHasher for BuildVecHasher<T> {
    type Hasher = VecHasher<T>;
    fn build_hasher(&self) -> VecHasher<T> {
        VecHasher {
            state: 0,
            node_table: self.node_table.clone(),
            default: DefaultHasher::new(),
        }
    }
}

pub trait Convertible: Copy + Debug {
    fn from(x: usize) -> Self;
    fn to(&self) -> usize;
}

impl Convertible for u8 {
    fn from(x: usize) -> Self {
        x as u8
    }
    fn to(&self) -> usize {
        *self as usize
    }
}

impl Convertible for u16 {
    fn from(x: usize) -> Self {
        x as u16
    }
    fn to(&self) -> usize {
        *self as usize
    }
}

impl Convertible for u32 {
    fn from(x: usize) -> Self {
        x as u32
    }
    fn to(&self) -> usize {
        *self as usize
    }
}

impl Convertible for u64 {
    fn from(x: usize) -> Self {
        x as u64
    }
    fn to(&self) -> usize {
        *self as usize
    }
}

impl Convertible for usize {
    fn from(x: usize) -> Self {
        x
    }
    fn to(&self) -> usize {
        *self as usize
    }
}

pub trait ArrayOffset: Convertible {
    fn offseted_hash<H: Hasher>(&self, state: &mut H);
}

impl ArrayOffset for u8 {
    fn offseted_hash<H: Hasher>(&self, state: &mut H) {
        state.write_u8(*self);
    }
}
impl ArrayOffset for u16 {
    fn offseted_hash<H: Hasher>(&self, state: &mut H) {
        state.write_u16(*self);
    }
}
impl ArrayOffset for u32 {
    fn offseted_hash<H: Hasher>(&self, state: &mut H) {
        state.write_u32(*self);
    }
}
impl ArrayOffset for u64 {
    fn offseted_hash<H: Hasher>(&self, state: &mut H) {
        state.write_u64(*self);
    }
}
impl ArrayOffset for usize {
    fn offseted_hash<H: Hasher>(&self, state: &mut H) {
        state.write_usize(*self);
    }
}

// pub struct VecMapStore<T: Hash, I: ArrayOffset> {
//     hash_table: HashSet<VecMapStoreEntry<I>, BuildVecHasher<T>>,
//     node_table: Rc<RefCell<Vec<T>>>,
//     counter: ConsistentCounter,
//     dedup: HashMap<<B as Backend>::Symbol, (), ()>;
// }

pub trait Symbol<T>: Copy + Eq {}
pub trait VecSymbol<T>: Symbol<T> {
    /// Creates a symbol from a `usize`.
    ///
    /// Returns `None` if `index` is out of bounds for the symbol.
    fn try_from_usize(index: usize) -> Option<Self>;

    /// Returns the `usize` representation of `self`.
    fn to_usize(self) -> usize;
}

pub struct SymbolU32<T> {
    internal: string_interner::symbol::SymbolU32,
    _phantom: PhantomData<*const T>,
}

impl<T> Debug for SymbolU32<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use string_interner::Symbol;
        write!(f, "${}", &self.internal.to_usize())
        // f.debug_struct("SymbolU32")
        //     .field("internal", &self.internal)
        //     .finish()
    }
}

impl<T> Clone for SymbolU32<T> {
    fn clone(&self) -> Self {
        Self {
            internal: self.internal.clone(),
            _phantom: self._phantom.clone(),
        }
    }
}

impl<T> Copy for SymbolU32<T> {}

impl<T> PartialEq for SymbolU32<T> {
    fn eq(&self, other: &Self) -> bool {
        self.internal == other.internal
    }
}

impl<T> Eq for SymbolU32<T> {}

impl<T> Symbol<T> for SymbolU32<T> {}

impl<T> VecSymbol<T> for SymbolU32<T> {
    fn try_from_usize(index: usize) -> Option<Self> {
        use string_interner::Symbol;
        string_interner::symbol::SymbolU32::try_from_usize(index).and_then(|internal| {
            Some(Self {
                internal,
                _phantom: PhantomData,
            })
        })
    }

    fn to_usize(self) -> usize {
        use string_interner::Symbol;
        self.internal.to_usize()
    }
}

pub trait AsNodeEntityRef {
    type Ref<'a>
    where
        Self: 'a;
    fn eq(&self, other: &Self::Ref<'_>) -> bool;
}
pub trait AsNodeEntityRefSelf: AsNodeEntityRef {
    fn as_ref(&self) -> Self::Ref<'_>;
}

impl AsNodeEntityRef for Box<[u8]> {
    type Ref<'a> = &'a [u8];

    fn eq(&self, other: &Self::Ref<'_>) -> bool {
        AsNodeEntityRefSelf::as_ref(self) == *other
    }
}

impl AsNodeEntityRefSelf for Box<[u8]> {
    fn as_ref(&self) -> Self::Ref<'_> {
        AsRef::as_ref(self)
    }
}

/// Come from string-interner
/// Types implementing this trait may act as backends for the string interner.
///
/// The job of a backend is to actually store, manage and organize the interned
/// strings. Different backends have different trade-offs. Users should pick
/// their backend with hinsight of their personal use-case.
pub trait Backend<T: AsNodeEntityRef>: Default {
    /// The symbol used by the string interner backend.
    type Symbol: Symbol<T>;

    fn len(&self) -> usize;

    /// Creates a new backend for the given capacity.
    ///
    /// The capacity denotes how many strings are expected to be interned.
    fn with_capacity(cap: usize) -> Self;

    /// Interns the given string and returns its interned ref and symbol.
    ///
    /// # Note
    ///
    /// The backend must make sure that the returned symbol maps back to the
    /// original string in its [`resolve`](`Backend::resolve`) method.
    fn intern(&mut self, string: T) -> Self::Symbol;

    /// Shrink backend capacity to fit interned symbols exactly.
    fn shrink_to_fit(&mut self);

    /// Resolves the given symbol to its original string contents.
    fn resolve(&self, symbol: Self::Symbol) -> Option<T::Ref<'_>>;

    /// Resolves the given symbol to its original string contents.
    ///
    /// # Safety
    ///
    /// Does not perform validity checks on the given symbol and relies
    /// on the caller to be provided with a symbol that has been generated
    /// by the [`intern`](`Backend::intern`) or
    /// [`intern_static`](`Backend::intern_static`) methods of the same
    /// interner backend.
    unsafe fn resolve_unchecked(&self, symbol: Self::Symbol) -> T::Ref<'_>;
}

pub struct VecBackend<T, S: Symbol<T>> {
    internal: Vec<T>,
    phantom: PhantomData<*const S>,
}

impl<T: AsNodeEntityRef + Debug, S: Symbol<T>> Debug for VecBackend<T, S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VecBackend")
            .field("internal", &self.internal)
            .finish()
    }
}

impl<T: AsNodeEntityRefSelf, S: VecSymbol<T>> Backend<T> for VecBackend<T, S>
// where T: for<'a> AsNodeEntityRef<Ref<'a>=&'a T> ,
{
    type Symbol = S;

    fn with_capacity(cap: usize) -> Self {
        Self {
            internal: Vec::with_capacity(cap),
            phantom: PhantomData,
        }
    }

    fn intern(&mut self, node: T) -> Self::Symbol {
        let s = Self::Symbol::try_from_usize(self.internal.len())
            .expect("not enough symbol, you should take a bigger set");
        self.internal.push(node);
        s
    }

    fn shrink_to_fit(&mut self) {
        self.internal.shrink_to_fit()
    }

    fn resolve(&self, symbol: Self::Symbol) -> Option<T::Ref<'_>> {
        self.internal.get(symbol.to_usize()).map(|x| x.as_ref())
    }

    unsafe fn resolve_unchecked(&self, symbol: Self::Symbol) -> T::Ref<'_> {
        self.internal.get_unchecked(symbol.to_usize()).as_ref()
    }

    fn len(&self) -> usize {
        self.internal.len()
    }
}

impl<T, S: Symbol<T>> Default for VecBackend<T, S> {
    fn default() -> Self {
        Self {
            internal: Default::default(),
            phantom: Default::default(),
        }
    }
}

pub type DefaultBackend<T, I> = VecBackend<T, I>;

pub struct VecMapStore<
    T: Hash + AsNodeEntityRef,
    I: Symbol<T>,
    B = DefaultBackend<T, I>,
    H = DefaultHashBuilder,
> where
    B: Backend<T>,
    H: BuildHasher,
{
    dedup: HashMap<I, (), ()>,
    hasher: H,
    backend: B,
    phantom: PhantomData<*const T>,
}

impl<T: Hash + AsNodeEntityRef, I: Symbol<T>, B, H> Default for VecMapStore<T, I, B, H>
where
    B: Backend<T>,
    H: BuildHasher + Default,
{
    fn default() -> Self {
        Self {
            dedup: Default::default(),
            hasher: Default::default(),
            backend: Default::default(),
            phantom: Default::default(),
        }
    }
}

impl<T: Hash + AsNodeEntityRef, I: Symbol<T>, B, H> VecMapStore<T, I, B, H>
where
    B: Backend<T, Symbol = I>,
    H: BuildHasher + Default,
{
    pub fn new() -> Self {
        Self {
            dedup: HashMap::default(),
            hasher: Default::default(),
            backend: B::default(),
            phantom: PhantomData,
        }
    }

    pub fn len(&self) -> usize {
        self.backend.len()
    }
}

impl<T: Hash + Debug + AsNodeEntityRef, I: Symbol<T> + Debug, B, H> Debug
    for VecMapStore<T, I, B, H>
where
    B: Backend<T> + Debug,
    <B as Backend<T>>::Symbol: Symbol<T> + Debug,
    H: BuildHasher,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VecMapStore")
            .field("dedup", &self.dedup)
            .field("backend", &self.backend)
            .finish()
    }
}

impl<T: Hash + Eq + AsNodeEntityRef, I: Symbol<T>, B> VecMapStore<T, I, B>
where
    B: Backend<T, Symbol = I>,
    for<'a> T::Ref<'a>: Hash + Eq,
{
    pub fn get<U: AsRef<T>>(&mut self, node: U) -> Option<I> {
        let node = node.as_ref();
        let Self {
            dedup,
            hasher,
            backend,
            ..
        } = self;
        let hash = make_hash(hasher, node);
        dedup
            .raw_entry()
            .from_hash(hash, |symbol| {
                // SAFETY: This is safe because we only operate on symbols that
                //         we receive from our backend making them valid.
                AsNodeEntityRef::eq(node, &unsafe { backend.resolve_unchecked(*symbol) })
            })
            .map(|(&symbol, &())| symbol)
    }
}

impl<T: Hash + Eq + AsNodeEntityRef, I: Symbol<T>, B, H> VecMapStore<T, I, B, H>
where
    B: Backend<T, Symbol = I>,
    H: BuildHasher,
    for<'a> T::Ref<'a>: Hash + Eq,
{
    pub fn get_or_intern_using(&mut self, node: T, intern_fn: fn(&mut B, T) -> I) -> I {
        let Self {
            dedup,
            hasher,
            backend,
            ..
        } = self;
        let hash = make_hash(hasher, &node);
        let a = &dedup.len();
        let entry = dedup.raw_entry_mut().from_hash(hash, |symbol| {
            // SAFETY: This is safe because we only operate on symbols that
            //         we receive from our backend making them valid.
            // node.eq(unsafe { backend.resolve_unchecked(*symbol) })
            let tmp = unsafe { backend.resolve_unchecked(*symbol) };
            if AsNodeEntityRef::eq(&node, &tmp) {
                true
            } else {
                false
            }
        });
        use crate::compat::hash_map::RawEntryMut;
        let (&mut symbol, &mut ()) = match entry {
            RawEntryMut::Occupied(occupied) => occupied.into_key_value(),
            RawEntryMut::Vacant(vacant) => {
                let symbol = intern_fn(backend, node);
                vacant.insert_with_hasher(hash, symbol, (), |symbol| {
                    // SAFETY: This is safe because we only operate on symbols that
                    //         we receive from our backend making them valid.
                    let node = unsafe { backend.resolve_unchecked(*symbol) };
                    make_hash(hasher, &node)
                })
            }
        };
        symbol
    }

    #[inline]
    pub fn get_or_intern(&mut self, node: T) -> I
where {
        self.get_or_intern_using(node, B::intern)
    }

    pub fn resolve(&self, id: &I) -> T::Ref<'_> {
        self.backend.resolve(*id).unwrap()
    }
}