big-code-analysis 1.1.0

Tool to compute and export code metrics
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
// `get_language!` is invoked only from feature-gated arms in `mk_lang!`
// (one arm per `LANG::*` variant whose per-language Cargo feature is
// enabled). A build with `--no-default-features` and no language
// feature has no remaining call sites; suppress the lint for that
// pathological-but-valid configuration.
#[allow(unused_macros)]
macro_rules! get_language {
    (tree_sitter_cpp) => {
        tree_sitter_mozcpp::LANGUAGE.into()
    };
    (tree_sitter_typescript) => {
        tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()
    };
    (tree_sitter_tsx) => {
        tree_sitter_typescript::LANGUAGE_TSX.into()
    };
    (tree_sitter_php) => {
        tree_sitter_php::LANGUAGE_PHP.into()
    };
    ($name:ident) => {
        $name::LANGUAGE.into()
    };
}

// `implement_metric_trait!` emits no-op `compute` bodies for every
// metric / language pair listed. Every named-trait arm below
// (`Abc`, `Cognitive`, `Halstead`, `Exit`, `Cyclomatic`, `Npa`,
// `Npm`, `Loc`, `Wmc`) is silent: the metric will report 0 on every
// input. The bracketed-trait arm (`[Trait]`) is different — it
// emits an empty `impl Trait for X {}` and relies on the trait's
// own default method body, which is correct for `Tokens`, `Nom`,
// and `NArgs`.
//
// Audit: #188 walked every `(language, metric)` cell and classified
// each as either a real default (the language has no construct the
// metric measures) or a placeholder (the language HAS the construct
// but no impl exists yet). Each invocation site carries a comment
// recording the rationale and any follow-up issue number — keep
// those comments in sync when you add a new language or land a real
// impl.
macro_rules! implement_metric_trait {
    (Abc, $($code:ident),+) => (
        implement_metric_trait!(@code_taking Abc, $($code),+);
    );
    (Cognitive, $($code:ident),+) => (
        $(
           impl Cognitive for $code {
               fn compute<'a>(
                   _node: &Node<'a>,
                   _code: &'a [u8],
                   _stats: &mut Stats,
                   _nesting_map: &mut HashMap<usize, (usize, usize, usize)>,
               ) {}
           }
        )+
    );
    (Halstead, $($code:ident),+) => (
        $(
           impl Halstead for $code {
               fn compute<'a>(_node: &Node<'a>, _code: &'a [u8], _halstead_maps: &mut HalsteadMaps<'a>) {}
           }
        )+
    );
    // Internal helper: shared no-op body for traits whose `compute`
    // signature is `<'a>(&Node<'a>, &'a [u8], &mut Stats)` (Exit,
    // Cyclomatic). Public arms below delegate here so the body is
    // written once.
    (@code_taking $trait:ident, $($code:ident),+) => (
        $(
           impl $trait for $code {
               fn compute<'a>(_node: &Node<'a>, _code: &'a [u8], _stats: &mut Stats) {}
           }
        )+
    );
    (Exit, $($code:ident),+) => (
        implement_metric_trait!(@code_taking Exit, $($code),+);
    );
    (Cyclomatic, $($code:ident),+) => (
        implement_metric_trait!(@code_taking Cyclomatic, $($code),+);
    );
    (Npa, $($code:ident),+) => (
        implement_metric_trait!(@code_taking Npa, $($code),+);
    );
    (Npm, $($code:ident),+) => (
        implement_metric_trait!(@code_taking Npm, $($code),+);
    );
    (Loc, $($code:ident),+) => (
        $(
           impl Loc for $code {
               fn compute(_node: &Node, _stats: &mut Stats, _is_func_space: bool, _is_unit: bool) {}
           }
        )+
    );
    (Wmc, $($code:ident),+) => (
        $(
           impl Wmc for $code {
               fn compute(_space_kind: SpaceKind, _cyclomatic: &cyclomatic::Stats, _stats: &mut Stats) {}
           }
        )+
    );
    ([$trait:ident], $($code:ident),+) => (
        $(
           impl $trait for $code {}
        )+
    );
    ($trait:ident, $($code:ident),+) => (
        $(
           impl $trait for $code {
               fn compute(_node: &Node, _stats: &mut Stats) {}
           }
        )+
    )
}

macro_rules! mk_lang {
    ( $( ($feature:literal, $camel:ident, $name:ident, $display: expr, $description:expr) ),* ) => {
        /// The list of supported languages.
        ///
        /// Every variant is always defined regardless of the Cargo
        /// feature set: per-language features only gate the grammar
        /// crate references, never the enum surface itself. Disabled
        /// variants surface at runtime as
        /// [`crate::MetricsError::LanguageDisabled`] from every entry
        /// point that returns a `Result`.
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        pub enum LANG {
            $(
                #[doc = $description]
                $camel,
            )*
        }
        impl LANG {
            /// Return an iterator over the supported languages.
            ///
            /// # Examples
            ///
            /// ```
            /// use big_code_analysis::LANG;
            ///
            /// for lang in LANG::into_enum_iter() {
            ///     println!("{:?}", lang);
            /// }
            /// ```
            pub fn into_enum_iter() -> impl Iterator<Item=LANG> {
                use LANG::*;
                [$( $camel, )*].into_iter()
            }

            /// Returns the name of a language as a `&str`.
            ///
            /// # Examples
            ///
            /// ```
            /// use big_code_analysis::LANG;
            ///
            /// println!("{}", LANG::Rust.get_name());
            /// ```
            pub fn get_name(&self) -> &'static str {
                match self {
                    $(
                        LANG::$camel => $display,
                    )*
                }
            }

            /// Reports whether this variant's grammar crate is
            /// compiled into the current build.
            ///
            /// Returns `false` for variants whose per-language Cargo
            /// feature is disabled; calling
            /// [`Self::get_tree_sitter_language`], [`crate::analyze`],
            /// or any other dispatcher with such a variant will
            /// return [`crate::MetricsError::LanguageDisabled`].
            #[must_use]
            pub fn is_enabled(&self) -> bool {
                match self {
                    $(
                        #[cfg(feature = $feature)]
                        LANG::$camel => true,
                        #[cfg(not(feature = $feature))]
                        LANG::$camel => false,
                    )*
                }
            }

            // Returns a tree-sitter language paired with this variant,
            // or `Err(LanguageDisabled)` when the matching Cargo
            // feature is off. This is the internal entry point used
            // by `Tree::new` to construct a parser; the public
            // counterpart is `get_tree_sitter_language`.
            pub(crate) fn get_ts_language(&self) -> Result<Language, crate::MetricsError> {
                match self {
                    $(
                        #[cfg(feature = $feature)]
                        LANG::$camel => Ok(get_language!($name)),
                        #[cfg(not(feature = $feature))]
                        LANG::$camel => Err(crate::MetricsError::LanguageDisabled(*self)),
                    )*
                }
            }

            /// Returns the [`tree_sitter::Language`] grammar used by
            /// this variant.
            ///
            /// Useful when feeding a caller-built
            /// [`tree_sitter::Parser`] into the
            /// [`crate::metrics_from_tree`] / [`crate::Parser::from_tree`]
            /// entry points — the language returned here is the one
            /// the metric walker expects for `kind_id` matching, so
            /// the trees agree structurally.
            ///
            /// This method is part of the value-not-stable surface:
            /// the underlying `tree-sitter-*` grammar pin may bump
            /// in any minor release, which can change `Language`
            /// equality on the caller side.
            ///
            /// # Errors
            ///
            /// Returns [`crate::MetricsError::LanguageDisabled`] when
            /// the variant's per-language Cargo feature is not
            /// enabled in the current build (see the `[features]`
            /// table in the root `Cargo.toml`).
            ///
            /// # Examples
            ///
            /// ```
            /// use big_code_analysis::LANG;
            ///
            /// let _lang = LANG::Rust.get_tree_sitter_language().expect("rust feature enabled");
            /// ```
            pub fn get_tree_sitter_language(&self) -> Result<::tree_sitter::Language, crate::MetricsError> {
                self.get_ts_language()
            }
        }
    };
}

macro_rules! mk_action {
    ( $( ($feature:literal, $camel:ident, $parser:ident) ),* ) => {
        /// Runs a function, which implements the [`Callback`] trait,
        /// on a code written in one of the supported languages.
        ///
        /// # Errors
        ///
        /// Returns [`MetricsError::LanguageDisabled`] when `lang`
        /// names a language whose per-language Cargo feature is not
        /// enabled in the current build (see the `[features]` table
        /// in the root `Cargo.toml`). All other failure modes are
        /// reported through the callback's own `T::Res`.
        ///
        /// # Examples
        ///
        /// The following example dumps to shell every metric computed using
        /// the dummy source code.
        ///
        /// ```
        /// use std::path::PathBuf;
        ///
        /// use big_code_analysis::{action, Callback, LANG, Metrics, MetricsCfg};
        ///
        /// let source_code = "int a = 42;";
        /// let language = LANG::Cpp;
        ///
        /// // The path to a dummy file used to contain the source code
        /// let path = PathBuf::from("foo.c");
        /// let source_as_vec = source_code.as_bytes().to_vec();
        ///
        /// // Configuration options used by the function which computes the metrics
        /// let cfg = MetricsCfg::new(path);
        ///
        /// action::<Metrics>(&language, source_as_vec, &cfg.path.clone(), None, cfg)
        ///     .expect("cpp feature enabled");
        /// ```
        ///
        /// [`Callback`]: trait.Callback.html
        #[inline]
        pub fn action<T: Callback>(lang: &LANG, source: Vec<u8>, path: &Path, pr: Option<Arc<PreprocResults>>, cfg: T::Cfg) -> Result<T::Res, MetricsError> {
            match lang {
                $(
                    #[cfg(feature = $feature)]
                    LANG::$camel => {
                        let parser = $parser::new(source, path, pr);
                        Ok(T::call(cfg, &parser))
                    },
                    #[cfg(not(feature = $feature))]
                    LANG::$camel => {
                        let _ = (source, path, pr, cfg);
                        Err(MetricsError::LanguageDisabled(*lang))
                    },
                )*
            }
        }

        /// Returns all function spaces data of a code.
        ///
        /// # Deprecated
        ///
        /// Prefer [`analyze`], which accepts a [`Source`] carrying an
        /// explicit display name distinct from any on-disk path. This
        /// shim derives [`FuncSpace::name`] from `path` via lossy
        /// UTF-8 conversion and remains for backwards compatibility
        /// for one minor release.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::path::PathBuf;
        ///
        /// # #[allow(deprecated)]
        /// use big_code_analysis::{get_function_spaces, LANG};
        ///
        /// let source_code = "int a = 42;";
        /// let language = LANG::Cpp;
        ///
        /// // The path to a dummy file used to contain the source code
        /// let path = PathBuf::from("foo.c");
        /// let source_as_vec = source_code.as_bytes().to_vec();
        ///
        /// # #[allow(deprecated)]
        /// get_function_spaces(&language, source_as_vec, &path, None).unwrap();
        /// ```
        ///
        /// # Errors
        ///
        /// Returns [`MetricsError::LanguageDisabled`] when `lang`'s
        /// per-language Cargo feature is not enabled in this build.
        /// The return type also carries [`MetricsError::EmptyRoot`]
        /// for forward compatibility, but the walker does not produce
        /// it today — see the variant doc.
        #[deprecated(
            since = "0.0.26",
            note = "Use `analyze(Source::new(lang, &code).with_name(Some(name)), MetricsOptions::default())` instead — the path-positional shim derives the top-level FuncSpace name via lossy UTF-8 conversion."
        )]
        #[inline]
        pub fn get_function_spaces(lang: &LANG, source: Vec<u8>, path: &Path, pr: Option<Arc<PreprocResults>>) -> Result<FuncSpace, MetricsError> {
            #[allow(deprecated)]
            match lang {
                $(
                    #[cfg(feature = $feature)]
                    LANG::$camel => {
                        let parser = $parser::new(source, &path, pr);
                        metrics(&parser, &path)
                    },
                    #[cfg(not(feature = $feature))]
                    LANG::$camel => {
                        let _ = (source, path, pr);
                        Err(MetricsError::LanguageDisabled(*lang))
                    },
                )*
            }
        }

        /// Language-dispatched bundle of a parsed tree plus its
        /// source bytes, one variant per Cargo-feature-enabled
        /// language. The public seam is [`crate::Ast`]; this enum is
        /// the macro-generated internal carrier it wraps.
        ///
        /// With every per-language feature disabled this enum is a
        /// 0-variant uninhabited type. Each method below therefore
        /// terminates its `match self` with a
        /// `#[cfg(not(any(feature = …)))] _ => match *self {}` arm:
        /// stable Rust treats `&UninhabitedType` as inhabited (E0004),
        /// so the outer match needs a wildcard, and `match *self {}`
        /// is exhaustive over the uninhabited dereferenced value —
        /// divergent, no panic, no `unsafe`, statically unreachable in
        /// safe code because the public seam `crate::Ast` has only
        /// fallible constructors that return `Err(LanguageDisabled)`
        /// for every `LANG` variant under that build.
        ///
        /// When a method takes by-value parameters (see
        /// [`Self::run_metrics`]), prefix the divergent arm with
        /// `let _ = (param1, param2, …);` to silence
        /// `unused_variables` under `RUSTFLAGS=-D warnings` — the
        /// `match *self {}` body is `!`, so the consumed values are
        /// never actually dropped at runtime.
        pub(crate) enum AstInner {
            $(
                #[cfg(feature = $feature)]
                $camel($parser),
            )*
        }

        impl AstInner {
            /// Run the metric walker against the held parse. The
            /// caller passes `name` and `options` per call so a
            /// single `AstInner` can be reused with different metric
            /// subsets.
            pub(crate) fn run_metrics(
                &self,
                name: Option<String>,
                options: MetricsOptions,
            ) -> Result<FuncSpace, MetricsError> {
                match self {
                    $(
                        #[cfg(feature = $feature)]
                        AstInner::$camel(parser) => metrics_inner(parser, name, options),
                    )*
                    #[cfg(not(any( $( feature = $feature ),* )))]
                    _ => {
                        let _ = (name, options);
                        match *self {}
                    },
                }
            }

            pub(crate) fn language(&self) -> LANG {
                match self {
                    $(
                        #[cfg(feature = $feature)]
                        AstInner::$camel(_) => LANG::$camel,
                    )*
                    #[cfg(not(any( $( feature = $feature ),* )))]
                    _ => match *self {},
                }
            }

            pub(crate) fn code_bytes(&self) -> &[u8] {
                match self {
                    $(
                        #[cfg(feature = $feature)]
                        AstInner::$camel(parser) => parser.get_code(),
                    )*
                    #[cfg(not(any( $( feature = $feature ),* )))]
                    _ => match *self {},
                }
            }

            pub(crate) fn ts_tree(&self) -> &::tree_sitter::Tree {
                match self {
                    $(
                        #[cfg(feature = $feature)]
                        AstInner::$camel(parser) => parser.get_ts_tree(),
                    )*
                    #[cfg(not(any( $( feature = $feature ),* )))]
                    _ => match *self {},
                }
            }
        }

        /// Internal parse-dispatch shim that backs [`crate::Ast::parse`].
        /// Lives in the `mk_action!` macro so each new language only
        /// has to declare its parser tag once.
        pub(crate) fn ast_parse_dispatch(
            lang: LANG,
            source: &[u8],
            preproc_path: Option<&Path>,
            preproc: Option<Arc<PreprocResults>>,
        ) -> Result<AstInner, MetricsError> {
            // `Parser::new` keys the C++ macro-expansion lookup off the
            // caller-supplied path; for callers analysing in-memory
            // snippets with no preprocessor path, fall back to an
            // empty `Path` ("") which the lookup ignores. The empty
            // path is *not* leaked into `FuncSpace::name` — that
            // is carried separately on `Ast`.
            let preproc_path = preproc_path.unwrap_or(Path::new(""));
            let source = source.to_vec();
            match lang {
                $(
                    #[cfg(feature = $feature)]
                    LANG::$camel => Ok(AstInner::$camel($parser::new(source, preproc_path, preproc))),
                    #[cfg(not(feature = $feature))]
                    LANG::$camel => {
                        let _ = (source, preproc_path, preproc);
                        Err(MetricsError::LanguageDisabled(lang))
                    },
                )*
            }
        }

        /// Internal tree-adoption dispatch that backs
        /// [`crate::Ast::from_tree_sitter`].
        pub(crate) fn ast_from_tree_dispatch(
            lang: LANG,
            tree: ::tree_sitter::Tree,
            source: Vec<u8>,
        ) -> Result<AstInner, MetricsError> {
            match lang {
                $(
                    #[cfg(feature = $feature)]
                    LANG::$camel => Ok(AstInner::$camel($parser::from_tree(tree, source))),
                    #[cfg(not(feature = $feature))]
                    LANG::$camel => {
                        let _ = (tree, source);
                        Err(MetricsError::LanguageDisabled(lang))
                    },
                )*
            }
        }

        /// Internal language-dispatch shim that backs [`analyze`].
        /// Delegates to [`ast_parse_dispatch`] + [`AstInner::run_metrics`]
        /// so the per-`LANG` match arm lives in exactly one place.
        #[doc(hidden)]
        pub fn analyze_dispatch(
            lang: LANG,
            source: &[u8],
            name: Option<String>,
            preproc_path: Option<&Path>,
            preproc: Option<Arc<PreprocResults>>,
            options: MetricsOptions,
        ) -> Result<FuncSpace, MetricsError> {
            ast_parse_dispatch(lang, source, preproc_path, preproc)?.run_metrics(name, options)
        }

        /// Returns all function spaces data of a code, applying the
        /// per-traversal flags in `options` (e.g.
        /// `exclude_tests: true` to elide Rust `#[cfg(test)]` /
        /// `#[test]` subtrees from every metric). Equivalent to
        /// [`get_function_spaces`] when `options` is the default.
        ///
        /// # Deprecated
        ///
        /// Prefer [`analyze`], which accepts a [`Source`] carrying an
        /// explicit display name distinct from any on-disk path.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::path::PathBuf;
        ///
        /// # #[allow(deprecated)]
        /// use big_code_analysis::{get_function_spaces_with_options, LANG, MetricsOptions};
        ///
        /// let source_code = "fn main() {}\n#[test] fn t() {}";
        /// let language = LANG::Rust;
        ///
        /// let path = PathBuf::from("foo.rs");
        /// let source_as_vec = source_code.as_bytes().to_vec();
        /// let options = MetricsOptions::default().with_exclude_tests(true);
        ///
        /// # #[allow(deprecated)]
        /// get_function_spaces_with_options(&language, source_as_vec, &path, None, options).unwrap();
        /// ```
        ///
        /// # Errors
        ///
        /// Returns [`MetricsError::LanguageDisabled`] when `lang`'s
        /// per-language Cargo feature is not enabled in this build.
        /// The return type also carries [`MetricsError::EmptyRoot`]
        /// for forward compatibility, but the walker does not produce
        /// it today — see the variant doc.
        #[deprecated(
            since = "0.0.26",
            note = "Use `analyze(Source::new(lang, &code).with_name(Some(name)), options)` instead — the path-positional shim derives the top-level FuncSpace name via lossy UTF-8 conversion."
        )]
        #[inline]
        pub fn get_function_spaces_with_options(lang: &LANG, source: Vec<u8>, path: &Path, pr: Option<Arc<PreprocResults>>, options: MetricsOptions) -> Result<FuncSpace, MetricsError> {
            #[allow(deprecated)]
            match lang {
                $(
                    #[cfg(feature = $feature)]
                    LANG::$camel => {
                        let parser = $parser::new(source, &path, pr);
                        metrics_with_options(&parser, &path, options)
                    },
                    #[cfg(not(feature = $feature))]
                    LANG::$camel => {
                        let _ = (source, path, pr, options);
                        Err(MetricsError::LanguageDisabled(*lang))
                    },
                )*
            }
        }

        /// Returns all function spaces data of a code, reusing a
        /// caller-supplied [`tree_sitter::Tree`] instead of running
        /// the bundled parser.
        ///
        /// Use this when the caller already drives `tree-sitter` for
        /// other purposes (e.g. an editor doing incremental
        /// reparsing) and wants the metric walker to share that
        /// parse. The supplied `tree` must have been produced from
        /// `source` with the [`tree_sitter::Language`] returned by
        /// [`LANG::get_tree_sitter_language`] for `lang`; a mismatch
        /// is not `unsafe` but yields nonsensical metric values.
        ///
        /// Equivalent to [`get_function_spaces_with_options`] on the
        /// same `(lang, source, path)` triple when the same tree is
        /// reproduced internally.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::path::PathBuf;
        ///
        /// use big_code_analysis::{
        ///     get_function_spaces, metrics_from_tree, tree_sitter, LANG,
        ///     MetricsOptions,
        /// };
        ///
        /// let source_code = "fn main() { if true { 1 } else { 2 }; }";
        /// let path = PathBuf::from("foo.rs");
        /// let source = source_code.as_bytes().to_vec();
        ///
        /// let mut parser = tree_sitter::Parser::new();
        /// parser
        ///     .set_language(
        ///         &LANG::Rust
        ///             .get_tree_sitter_language()
        ///             .expect("rust feature enabled"),
        ///     )
        ///     .expect("rust grammar pinned to a compatible version");
        /// let tree = parser
        ///     .parse(&source, None)
        ///     .expect("parser has a language set");
        ///
        /// let from_tree = metrics_from_tree(
        ///     &LANG::Rust,
        ///     tree,
        ///     source.clone(),
        ///     &path,
        ///     None,
        ///     MetricsOptions::default(),
        /// )
        /// .unwrap();
        /// # #[allow(deprecated)]
        /// let from_bytes =
        ///     get_function_spaces(&LANG::Rust, source, &path, None).unwrap();
        ///
        /// assert_eq!(
        ///     from_tree.metrics.cyclomatic.cyclomatic_sum(),
        ///     from_bytes.metrics.cyclomatic.cyclomatic_sum(),
        /// );
        /// ```
        ///
        /// # Errors
        ///
        /// Returns [`MetricsError::LanguageDisabled`] when `lang`'s
        /// per-language Cargo feature is not enabled in this build.
        /// The return type also carries [`MetricsError::EmptyRoot`]
        /// for forward compatibility, but the walker does not produce
        /// it today — see the variant doc.
        #[inline]
        pub fn metrics_from_tree(
            lang: &LANG,
            tree: ::tree_sitter::Tree,
            source: Vec<u8>,
            path: &Path,
            pr: Option<Arc<PreprocResults>>,
            options: MetricsOptions,
        ) -> Result<FuncSpace, MetricsError> {
            // `pr` is accepted for parity with the byte-based entry
            // points so callers can swap one for the other without
            // changing call shape. Today only the C/C++ pre-pass uses
            // it, and that pre-pass runs before parsing — if the
            // caller built the tree themselves, they have already
            // accepted whatever macro expansion (or lack thereof) the
            // tree reflects, so the parameter is currently a no-op.
            let _ = pr;
            // Same path-name handling as the deprecated entry points
            // so existing callers see no behaviour change. Callers
            // who want to drop the lossy round-trip should use
            // [`crate::Ast::from_tree_sitter`], which carries an
            // explicit `name: Option<String>` end-to-end.
            let name = Some(path.to_string_lossy().into_owned());
            ast_from_tree_dispatch(*lang, tree, source)?.run_metrics(name, options)
        }

        /// Returns all operators and operands of each space in a code.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::path::PathBuf;
        ///
        /// use big_code_analysis::{get_ops, LANG};
        ///
        /// # fn main() {
        /// let source_code = "int a = 42;";
        /// let language = LANG::Cpp;
        ///
        /// // The path to a dummy file used to contain the source code
        /// let path = PathBuf::from("foo.c");
        /// let source_as_vec = source_code.as_bytes().to_vec();
        ///
        /// get_ops(&language, source_as_vec, &path, None).unwrap();
        /// # }
        /// ```
        ///
        /// # Errors
        ///
        /// Returns [`MetricsError::LanguageDisabled`] when `lang`'s
        /// per-language Cargo feature is not enabled in this build.
        /// The return type also carries [`MetricsError::EmptyRoot`]
        /// for forward compatibility, but the walker does not produce
        /// it today — see the variant doc.
        #[inline]
        pub fn get_ops(lang: &LANG, source: Vec<u8>, path: &Path, pr: Option<Arc<PreprocResults>>) -> Result<Ops, MetricsError> {
            match lang {
                $(
                    #[cfg(feature = $feature)]
                    LANG::$camel => {
                        let parser = $parser::new(source, &path, pr);
                        operands_and_operators(&parser, &path)
                    },
                    #[cfg(not(feature = $feature))]
                    LANG::$camel => {
                        let _ = (source, path, pr);
                        Err(MetricsError::LanguageDisabled(*lang))
                    },
                )*
            }
        }
    };
}

macro_rules! mk_extensions {
    ( $( ($camel:ident, [ $( $ext:ident ),* ]) ),* ) => {
        /// Detects the language associated to the input file extension.
        ///
        /// # Examples
        ///
        /// ```
        /// use big_code_analysis::get_from_ext;
        ///
        /// let ext = "rs";
        ///
        /// get_from_ext(ext).unwrap();
        /// ```
        pub fn get_from_ext(ext: &str) -> Option<LANG>{
            match ext {
                $(
                    $(
                        stringify!($ext) => Some(LANG::$camel),
                    )*
                )*
                _ => None,
            }
        }

        impl LANG {
            /// Returns the file extensions recognised for this language.
            ///
            /// The returned list is the same one consulted by
            /// [`get_from_ext`] and [`crate::get_language_for_file`].
            /// Helper variants without user-facing files (`Ccomment`,
            /// `Preproc`) return an empty slice.
            ///
            /// # Examples
            ///
            /// ```
            /// use big_code_analysis::LANG;
            ///
            /// assert!(LANG::Rust.get_extensions().contains(&"rs"));
            /// ```
            #[must_use]
            pub fn get_extensions(&self) -> &'static [&'static str] {
                match self {
                    $(
                        LANG::$camel => &[ $( stringify!($ext), )* ],
                    )*
                }
            }
        }
    };
}

macro_rules! mk_emacs_mode {
    ( $( ($camel:ident, [ $( $emacs_mode:expr ),* ]) ),* ) => {
        /// Detects the language associated to the input `Emacs` mode.
        ///
        /// An `Emacs` mode is used to detect a language according to
        /// particular text-information contained in a file.
        ///
        /// # Examples
        ///
        /// ```
        /// use big_code_analysis::get_from_emacs_mode;
        ///
        /// let emacs_mode = "rust";
        ///
        /// get_from_emacs_mode(emacs_mode).unwrap();
        /// ```
        pub fn get_from_emacs_mode(mode: &str) -> Option<LANG>{
            match mode {
                $(
                    $(
                        $emacs_mode => Some(LANG::$camel),
                    )*
                )*
                _ => None,
            }
        }
    };
}

macro_rules! mk_code {
    ( $( ($camel:ident, $code:ident, $parser:ident, $name:ident, $docname:expr) ),* ) => {
        $(
            #[doc = concat!("Per-language code type tag for ", $docname, "; carries no data.")]
            pub struct $code { _guard: (), }

            impl LanguageInfo for $code {
                type BaseLang = $camel;

                fn get_lang() -> LANG {
                    LANG::$camel
                }

                fn get_lang_name() -> &'static str {
                    $docname
                }
            }

            #[doc = "The `"]
            #[doc = $docname]
            #[doc = "` language parser."]
            pub type $parser = Parser<$code>;
        )*
    };
}

macro_rules! mk_langs {
    ( $( ($feature:literal, $camel:ident, $description: expr, $display: expr, $code:ident, $parser:ident, $name:ident, [ $( $ext:ident ),* ], [ $( $emacs_mode:expr ),* ]) ),* ) => {
        mk_lang!($( ($feature, $camel, $name, $display, $description) ),*);
        mk_action!($( ($feature, $camel, $parser) ),*);
        mk_extensions!($( ($camel, [ $( $ext ),* ]) ),*);
        mk_emacs_mode!($( ($camel, [ $( $emacs_mode ),* ]) ),*);
        mk_code!($( ($camel, $code, $parser, $name, stringify!($camel)) ),*);
    };
}

// Aliased C# `kind_id` unions. The C# tree-sitter grammar emits multiple
// numbered variants for several rules (lesson #2 in
// `docs/development/lessons_learned.md`); centralizing the alias sets
// here keeps every match site in lockstep, so a future grammar bump that
// adds another numbered variant is a one-line edit instead of a scatter
// of 4-5 sites.
macro_rules! csharp_invocation_expr_kinds {
    () => {
        $crate::Csharp::InvocationExpression
            | $crate::Csharp::InvocationExpression2
            | $crate::Csharp::InvocationExpression3
    };
}

macro_rules! csharp_paren_expr_kinds {
    () => {
        $crate::Csharp::ParenthesizedExpression
            | $crate::Csharp::ParenthesizedExpression2
            | $crate::Csharp::ParenthesizedExpression3
    };
}

macro_rules! csharp_prefix_unary_expr_kinds {
    () => {
        $crate::Csharp::PrefixUnaryExpression | $crate::Csharp::PrefixUnaryExpression2
    };
}

macro_rules! csharp_var_decl_kinds {
    () => {
        $crate::Csharp::VariableDeclaration | $crate::Csharp::VariableDeclaration2
    };
}

macro_rules! csharp_var_declarator_kinds {
    () => {
        $crate::Csharp::VariableDeclarator | $crate::Csharp::VariableDeclarator2
    };
}

pub(crate) use implement_metric_trait;
pub(crate) use {
    csharp_invocation_expr_kinds, csharp_paren_expr_kinds, csharp_prefix_unary_expr_kinds,
    csharp_var_decl_kinds, csharp_var_declarator_kinds, get_language, mk_action, mk_code,
    mk_emacs_mode, mk_extensions, mk_lang, mk_langs,
};