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
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
// region: Stuff provided usually provided by HyperAST

/// Helper to define and build subtrees while computing metrics
struct Builder<C>(C);

/// The AS node types
#[derive(Clone, Copy, Debug)]
pub enum Ty {
    Class,
    Method,
    IfStatement,
    WhileStatement,
}

impl Ty {
    fn is_branch(&self) -> bool {
        matches!(self, Ty::IfStatement | Ty::WhileStatement)
    }
}

/// interface to an AS node
pub trait Subtree {
    fn try_get<M: Clone + 'static>(&self) -> Option<M>;
    fn get<M: Clone + 'static>(&self) -> M {
        dbg!(std::any::type_name::<M>());
        self.try_get().unwrap()
    }
    fn ty(&self) -> Ty;
    fn label(&self) -> Option<&str> {
        self.try_get()
    }
    fn push_metric<M: 'static>(&mut self, m: M);
    fn builder() -> Builder<NoMetrics<Self>>
    where
        Self: Sized,
    {
        Builder(NoMetrics::default())
    }
}

// endregion

// region: Defining computation behavior directly on metric accumulator

pub trait MetricAcc {
    type S: Subtree;
    type M: 'static;
    fn init(ty: Ty, l: Option<&str>) -> Self;
    fn acc(acc: Self, current: &Self::S) -> Self;
    fn finish(acc: Self, current: &Self::S) -> Self::M;
}
impl<T> MetricComputing for T
where
    T: MetricAcc,
{
    type S = T::S;

    fn pipe<O: MetricComputing<S = Self::S>>(self, o: O) -> impl MetricComputing<S = Self::S> {
        Chained(self, o)
    }

    type Acc = Self;

    type M = T::M;

    fn init(&self, ty: Ty, l: Option<&str>) -> Self::Acc {
        MetricAcc::init(ty, l)
    }

    fn finish(&self, acc: Self::Acc, mut current: Self::S) -> Self::S {
        let m = MetricAcc::finish(acc, &current);
        current.push_metric(m);
        current
    }

    fn acc(&self, acc: Self::Acc, current: &Self::S) -> Self::Acc {
        MetricAcc::acc(acc, current)
    }
}
// endregion

// region: Defining computation behavior of a metric

/// Define how to compute a metric.
/// Easily composed using [`MetricComputing::pipe`] (see also [`Chained`]).
/// Can be made from closures with [`Functional`]
pub trait MetricComputing {
    /// Target code of the metric computation
    type S: Subtree;
    fn pipe<O: MetricComputing<S = Self::S>>(self, o: O) -> impl MetricComputing<S = Self::S>
    where
        Self: Sized,
    {
        Chained(self, o)
    }
    /// Holds the value of the metric while it is accumulated
    type Acc;
    /// The final output metric
    type M: 'static;
    fn init(&self, ty: Ty, l: Option<&str>) -> Self::Acc;
    fn acc(&self, acc: Self::Acc, current: &Self::S) -> Self::Acc;
    fn finish(&self, acc: Self::Acc, current: Self::S) -> Self::S;
}

struct NoMetrics<U>(std::marker::PhantomData<U>);
impl<U> Default for NoMetrics<U> {
    fn default() -> Self {
        Self(Default::default())
    }
}
impl<S: Subtree> MetricComputing for NoMetrics<S> {
    type S = S;
    fn pipe<O: MetricComputing<S = Self::S>>(self, o: O) -> impl MetricComputing<S = Self::S> {
        // optimization: no need this is a noop anyway
        o
    }
    type Acc = ();
    fn init(&self, ty: Ty, l: Option<&str>) -> Self::Acc {
        ()
    }
    fn acc(&self, acc: Self::Acc, current: &Self::S) -> Self::Acc {
        ()
    }
    type M = ();
    fn finish(&self, acc: Self::Acc, current: Self::S) -> Self::S {
        current
    }
}

struct Chained<F0, F1>(F0, F1);
impl<F0: MetricComputing, F1: MetricComputing<S = F0::S>> MetricComputing for Chained<F0, F1> {
    type S = F0::S;
    type Acc = (F0::Acc, F1::Acc);
    fn init(&self, ty: Ty, l: Option<&str>) -> Self::Acc {
        (self.0.init(ty, l), self.1.init(ty, l))
    }
    type M = (F0::M, F1::M);
    fn acc(&self, acc: Self::Acc, current: &Self::S) -> Self::Acc {
        let a0 = self.0.acc(acc.0, current);
        let a1 = self.1.acc(acc.1, current);
        (a0, a1)
    }
    fn finish(&self, acc: Self::Acc, current: Self::S) -> Self::S {
        let current = self.0.finish(acc.0, current);
        let current = self.1.finish(acc.1, current);
        current
    }
}

// endregion
// region: functional

/// Defining computation behavior of a metric with functions
struct Functional<T, U>(T, std::marker::PhantomData<U>);
impl<
        A,
        M: 'static,
        I: Fn(Ty, Option<&str>) -> A,
        Acc: Fn(A, &S) -> A,
        F: Fn(A, &S) -> M,
        S: Subtree,
    > MetricComputing for Functional<(I, Acc, F), (A, M, S)>
{
    type S = S;
    type Acc = A;
    fn init(&self, ty: Ty, l: Option<&str>) -> Self::Acc {
        (self.0 .0)(ty, l)
    }
    type M = M;
    fn finish(&self, acc: Self::Acc, mut current: Self::S) -> Self::S {
        let m = (self.0 .2)(acc, &current);
        current.push_metric(m);
        current
    }
    fn acc(&self, acc: Self::Acc, current: &Self::S) -> Self::Acc {
        (self.0 .1)(acc, current)
    }
}

// endregion

#[cfg(test)]
mod tests {
    use super::*;
    #[allow(dead_code, unreachable_code, unused)]
    #[test]
    fn test_metrics_computing_function_api() {
        struct A(u32);
        dbg!(std::any::TypeId::of::<A>());
        dbg!(std::any::TypeId::of::<M>());
        #[derive(Clone, Copy)]
        struct M(u32);
        fn mcc(s: &impl Subtree) -> M {
            s.get()
        }
        let builder = STree::builder();
        let builder = builder.with_function_metric(
            |_, _| A(0),
            |a, c| A(a.0 + mcc(c).0),
            |a, s| {
                if s.ty().is_branch() {
                    M(a.0 + 1)
                } else {
                    M(a.0)
                }
            },
        );
        let root = build_mcc_example_class(&builder);
        dbg!(mcc(&root).0);
    }
    #[test]
    fn test_metrics_computing_function_api2() {
        struct A(u32);
        impl std::ops::Add<M> for A {
            type Output = A;

            fn add(self, rhs: M) -> Self::Output {
                A(self.0 + rhs.0)
            }
        }
        impl std::ops::Add<Ty> for A {
            type Output = M;

            fn add(self, rhs: Ty) -> Self::Output {
                M(self.0 + rhs.is_branch() as u32)
            }
        }
        #[derive(Clone, Copy)]
        struct M(u32);
        fn mcc(s: &impl Subtree) -> M {
            s.get()
        }
        let builder = STree::builder();
        let builder = builder.with_function_metric(
            |_, _| A(0),       //
            |a, c| a + mcc(c), //
            |a, s| a + s.ty(), //
        );
        let root = build_mcc_example_class(&builder);
        dbg!(mcc(&root).0);
    }

    #[test]
    fn test_metrics_computing_function_api3() {
        #[derive(Default)]
        struct A(u32);
        impl std::ops::Add<M> for A {
            type Output = A;

            fn add(self, rhs: M) -> Self::Output {
                A(self.0 + rhs.0)
            }
        }
        impl std::ops::Add<Ty> for A {
            type Output = M;

            fn add(self, rhs: Ty) -> Self::Output {
                M(self.0 + rhs.is_branch() as u32)
            }
        }
        #[derive(Clone, Copy)]
        struct M(u32);
        fn mcc(s: &impl Subtree) -> M {
            s.get()
        }
        let builder = STree::builder();
        let builder = builder.with_simple_metric::<A, M>();
        let root = build_mcc_example_class(&builder);
        dbg!(mcc(&root).0);
    }

    #[test]
    fn test_metrics_computing_function_api4() {
        #[derive(Default)]
        struct A(u32);
        impl<S: Subtree> std::ops::AddAssign<&S> for A {
            fn add_assign(&mut self, rhs: &S) {
                self.0 += mcc(rhs).0;
            }
        }
        impl<S: Subtree> std::ops::Add<&S> for A {
            type Output = M;

            fn add(self, rhs: &S) -> Self::Output {
                M(self.0 + rhs.ty().is_branch() as u32)
            }
        }
        #[derive(Clone, Copy)]
        struct M(u32);
        fn mcc(s: &impl Subtree) -> M {
            s.get()
        }
        let builder = STree::builder();
        let builder = builder.with_simpler_metric::<A, M>();
        let root = build_mcc_example_class(&builder);
        dbg!(mcc(&root).0);
    }

    #[test]
    fn test_metrics_computing_trait_api() {
        struct A(u32);
        #[derive(Clone, Copy, Debug)]
        struct M(u32);
        let builder = STree::builder();
        impl MetricAcc for A {
            type S = STree;

            type M = M;

            fn init(ty: Ty, l: Option<&str>) -> Self {
                A(0)
            }

            fn acc(a: Self, c: &Self::S) -> Self {
                A(a.0 + c.get::<M>().0)
            }

            fn finish(a: Self, s: &Self::S) -> Self::M {
                if s.ty().is_branch() {
                    M(a.0 + 1)
                } else {
                    M(a.0)
                }
            }
        }
        let builder = builder.with_accumulator::<A>();
        let root = build_mcc_example_class(&builder);
        let m: M = root.get();
        dbg!(m);
    }

    fn build_mcc_example_class(builder: &Builder<impl MetricComputing<S = STree>>) -> STree {
        let root = Ty::Class;
        let acc_root = builder.0.init(root, None);
        let meth = build_mcc_example_meth(builder);
        let acc_root = builder.0.acc(acc_root, &meth);
        let class_members = Children(vec![meth]);
        let root = STree(root, vec![Box::new(class_members)]);
        let root = builder.0.finish(acc_root, root);
        root
    }

    fn build_mcc_example_meth(builder: &Builder<impl MetricComputing<S = STree>>) -> STree {
        let meth = Ty::Method;
        let acc_meth = builder.0.init(meth, None);
        let if_statement = build_mcc_example_if_statement(builder);
        let acc_meth = builder.0.acc(acc_meth, &if_statement);
        let meth_statements = Children(vec![if_statement]);
        let meth = STree(meth, vec![Box::new(meth_statements)]);
        let meth = builder.0.finish(acc_meth, meth);
        meth
    }

    fn build_mcc_example_if_statement(builder: &Builder<impl MetricComputing<S = STree>>) -> STree {
        let if_statement = Ty::IfStatement;
        let acc_if_statement = builder.0.init(if_statement, None);
        let if_statement = STree(if_statement, vec![]);
        let if_statement = builder.0.finish(acc_if_statement, if_statement);
        if_statement
    }

    // region: Stuff provided usually provided by HyperAST

    struct STree(Ty, Vec<Box<dyn std::any::Any>>);

    struct Children(#[allow(unused)] pub Vec<STree>);

    impl Subtree for STree {
        fn try_get<M: Clone + 'static>(&self) -> Option<M> {
            for x in &self.1 {
                let Some(m) = x.downcast_ref::<M>() else {
                    continue;
                };
                return Some(m.clone());
            }
            None
        }
        fn ty(&self) -> Ty {
            self.0
        }
        fn push_metric<M: 'static>(&mut self, m: M) {
            self.1.push(Box::new(m));
        }
    }

    // endregion

    impl Builder<()> {
        /// creates a builder without metrics
        fn new<U: Subtree>() -> Builder<NoMetrics<U>> {
            Builder(Default::default())
        }
    }

    impl<C: MetricComputing> Builder<C>
    where
        C::S: Subtree,
    {
        fn with_accumulator<A: 'static + MetricAcc<S = C::S>>(
            self,
        ) -> Builder<impl MetricComputing<S = C::S>> {
            struct Comp<A>(std::marker::PhantomData<A>);
            impl<A: 'static + MetricAcc> MetricComputing for Comp<A>
            where
                A::M: 'static,
            {
                type S = A::S;

                fn pipe<O: MetricComputing<S = Self::S>>(
                    self,
                    o: O,
                ) -> impl MetricComputing<S = Self::S> {
                    Chained(self, o)
                }

                type Acc = A;

                type M = A::M;

                fn init(&self, ty: Ty, l: Option<&str>) -> Self::Acc {
                    A::init(ty, l)
                }

                fn acc(&self, a: Self::Acc, c: &Self::S) -> Self::Acc {
                    A::acc(a, c)
                }

                fn finish(&self, a: Self::Acc, mut s: Self::S) -> Self::S {
                    let m = A::finish(a, &s);
                    s.push_metric(m);
                    s
                }
            }
            Builder(self.0.pipe(Comp::<A>(Default::default())))
        }

        fn with_simple_metric<
            A: 'static + Default + std::ops::Add<M, Output = A> + std::ops::Add<Ty, Output = M>,
            M: 'static + Copy,
        >(
            self,
        ) -> Builder<impl MetricComputing<S = C::S>> {
            struct Comp<A, M, S>(std::marker::PhantomData<(A, M, S)>);
            impl<
                    A: 'static
                        + Default
                        + std::ops::Add<M, Output = A>
                        + std::ops::Add<Ty, Output = M>,
                    M: 'static + Copy,
                    S: Subtree,
                > MetricComputing for Comp<A, M, S>
            {
                type S = S;

                fn pipe<O: MetricComputing<S = Self::S>>(
                    self,
                    o: O,
                ) -> impl MetricComputing<S = Self::S> {
                    Chained(self, o)
                }

                type Acc = A;

                type M = M;

                fn init(&self, ty: Ty, l: Option<&str>) -> Self::Acc {
                    A::default()
                }

                fn acc(&self, a: Self::Acc, c: &Self::S) -> Self::Acc {
                    a + c.get::<M>()
                }

                fn finish(&self, a: Self::Acc, mut s: Self::S) -> Self::S {
                    let m = a + s.ty();
                    s.push_metric(m);
                    s
                }
            }
            Builder(self.0.pipe(Comp::<A, M, C::S>(Default::default())))
        }

        fn with_simpler_metric<
            A: 'static
                + Default
                + for<'a> std::ops::AddAssign<&'a C::S>
                + for<'a> std::ops::Add<&'a C::S, Output = M>,
            M: 'static + Copy,
        >(
            self,
        ) -> Builder<impl MetricComputing<S = C::S>> {
            struct Comp<A, M, S>(std::marker::PhantomData<(A, M, S)>);
            impl<
                    A: 'static
                        + Default
                        + for<'a> std::ops::AddAssign<&'a S>
                        + for<'a> std::ops::Add<&'a S, Output = M>,
                    M: 'static + Copy,
                    S: Subtree,
                > MetricComputing for Comp<A, M, S>
            {
                type S = S;

                fn pipe<O: MetricComputing<S = Self::S>>(
                    self,
                    o: O,
                ) -> impl MetricComputing<S = Self::S> {
                    Chained(self, o)
                }

                type Acc = A;

                type M = M;

                fn init(&self, ty: Ty, l: Option<&str>) -> Self::Acc {
                    A::default()
                }

                fn acc(&self, mut a: Self::Acc, c: &Self::S) -> Self::Acc {
                    a += c;
                    a
                }

                fn finish(&self, a: Self::Acc, mut s: Self::S) -> Self::S {
                    let m = a + &s;
                    s.push_metric(m);
                    s
                }
            }
            Builder(self.0.pipe(Comp::<A, M, C::S>(Default::default())))
        }
    }

    impl<C: MetricComputing> Builder<C>
    where
        C::S: Subtree,
    {
        fn with_function_metric<A, M: 'static>(
            self,
            init: impl Fn(Ty, Option<&str>) -> A,
            acc: impl Fn(A, &C::S) -> A,
            finish: impl Fn(A, &C::S) -> M,
        ) -> Builder<impl MetricComputing<S = C::S>> {
            Builder(
                self.0
                    .pipe(Functional((init, acc, finish), Default::default())),
            )
        }

        // Does not work because of limitation of closure with generics
        // fn with_simple_metric<
        //     A: Default + std::ops::Add<M, Output = A> + std::ops::Add<Ty, Output = M>,
        //     M: 'static,
        // >(
        //     self,
        // ) -> Builder<impl MetricComputing<S = C::S>> {
        //     Builder(self.0.pipe(Functional(
        //         (
        //             |_: Ty, _: &str| A::default(),
        //             |a: A, c: &C::S| a + c.get(),
        //             |a: A, s: &C::S| a + s.ty(),
        //         ),
        //         Default::default(),
        //     )))
        // }
    }
}