Skip to main content

dry4rust/
code_unit.rs

1// Copyright (c) 2026 Matjaz Domen Pecan
2// Copyright 2026 Umberto Gotti <umberto.gotti@umbertogotti.dev>
3// Licensed under the MIT License
4// SPDX-License-Identifier: MIT
5
6use std::path::PathBuf;
7
8use crate::fingerprint::Fingerprint;
9use crate::node::NormalizedNode;
10use std::fmt;
11
12/// The kind of code unit extracted from source.
13#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
14pub enum CodeUnitKind {
15    Function,
16    Method,
17    Closure,
18    Class,
19    ImplBlock,
20    TraitImplBlock,
21    // Sub-function kinds
22    IfBranch,
23    MatchArm,
24    LoopBody,
25    Block,
26}
27
28impl fmt::Display for CodeUnitKind {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        match self {
31            Self::Function => write!(f, "function"),
32            Self::Method => write!(f, "method"),
33            Self::Closure => write!(f, "closure"),
34            Self::Class => write!(f, "class"),
35            Self::ImplBlock => write!(f, "impl block"),
36            Self::TraitImplBlock => write!(f, "trait impl block"),
37            Self::IfBranch => write!(f, "if branch"),
38            Self::MatchArm => write!(f, "match arm"),
39            Self::LoopBody => write!(f, "loop body"),
40            Self::Block => write!(f, "block"),
41        }
42    }
43}
44
45/// A unit of code extracted and normalized for duplication analysis.
46#[derive(Debug, Clone)]
47pub struct CodeUnit {
48    pub kind: CodeUnitKind,
49    pub name: String,
50    pub file: PathBuf,
51    pub line_start: usize,
52    pub line_end: usize,
53    pub signature: NormalizedNode,
54    pub body: NormalizedNode,
55    pub fingerprint: Fingerprint,
56    pub node_count: usize,
57    /// For sub-function units, the name of the parent function.
58    pub parent_name: Option<String>,
59    /// Whether this code unit was identified as test code by the language analyzer.
60    pub is_test: bool,
61}