debtmap 0.21.0

Code complexity and technical debt analyzer
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
pub mod natspec;
pub mod security_patterns;

use std::path::Path;

use crate::analyzers::solidity::debt::natspec::detect_natspec_debt;
use crate::analyzers::solidity::debt::security_patterns::detect_contract_patterns;
use crate::config::SolidityLanguageConfig;
use crate::core::ast::SolidityAst;
use crate::core::{DebtItem, DebtType, FunctionMetrics, Priority};
use crate::debt::patterns::find_todos_and_fixmes_with_suppression;
use crate::debt::smells::analyze_function_smells;
use crate::debt::suppression::{SuppressionContext, parse_suppression_comments};

pub fn detect_debt(
    path: &Path,
    threshold: u32,
    functions: &[FunctionMetrics],
    ast: &SolidityAst,
    skip_debt: bool,
    config: &SolidityLanguageConfig,
) -> Vec<DebtItem> {
    if skip_debt {
        return Vec::new();
    }

    let suppression =
        parse_suppression_comments(&ast.source, crate::core::Language::Solidity, path);
    let mut items = if config.features.detect_complexity {
        detect_complexity_debt(path, threshold, functions)
    } else {
        advisory_debt_items_for_functions(path, functions)
    };
    items.extend(find_todos_and_fixmes_with_suppression(
        &ast.source,
        path,
        Some(&suppression),
    ));
    items.extend(function_smell_debt(functions));
    items.extend(detect_natspec_debt(path, ast, functions));
    items.extend(contract_level_debt(path, ast, config));
    filter_suppressed_items(items, &suppression)
}

pub fn detect_complexity_debt(
    path: &Path,
    threshold: u32,
    functions: &[FunctionMetrics],
) -> Vec<DebtItem> {
    functions
        .iter()
        .filter(|function| !function.is_test)
        .flat_map(|function| debt_for_function(path, threshold, function))
        .collect()
}

fn debt_for_function(path: &Path, threshold: u32, function: &FunctionMetrics) -> Vec<DebtItem> {
    let mut items = Vec::new();

    if function.cyclomatic > threshold || function.cognitive > threshold {
        items.push(complexity_debt(path, function, threshold));
    }

    if function.nesting > 4 {
        items.push(nesting_debt(path, function));
    }

    if function.length > 50 {
        items.push(length_debt(path, function));
    }

    items.extend(advisory_debt_items(path, function));
    items
}

fn function_smell_debt(functions: &[FunctionMetrics]) -> Vec<DebtItem> {
    functions
        .iter()
        .filter(|function| !function.is_test)
        .flat_map(|function| analyze_function_smells(function, 0))
        .map(|smell| smell.to_debt_item())
        .collect()
}

fn contract_level_debt(
    path: &Path,
    ast: &SolidityAst,
    config: &SolidityLanguageConfig,
) -> Vec<DebtItem> {
    let root = ast.tree.root_node();
    let mut items = Vec::new();
    collect_contract_debt(root, path, ast, config, &mut items);
    items
}

fn collect_contract_debt(
    node: tree_sitter::Node,
    path: &Path,
    ast: &SolidityAst,
    config: &SolidityLanguageConfig,
    items: &mut Vec<DebtItem>,
) {
    if matches!(
        node.kind(),
        "contract_declaration" | "interface_declaration" | "library_declaration"
    ) {
        let name = node
            .child_by_field_name("name")
            .map(|n| crate::analyzers::solidity::parser::node_text(&n, &ast.source))
            .unwrap_or("Contract");
        let function_count = count_callables(node);
        for pattern in detect_contract_patterns(node, &ast.source, function_count, config) {
            if let Some(item) = contract_advisory(path, name, &pattern, node) {
                items.push(item);
            }
        }
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_contract_debt(child, path, ast, config, items);
    }
}

fn contract_advisory(
    path: &Path,
    contract_name: &str,
    pattern: &str,
    node: tree_sitter::Node,
) -> Option<DebtItem> {
    let definition = contract_advisory_definition(pattern)?;
    let line = crate::analyzers::solidity::parser::node_line(&node);

    Some(DebtItem {
        id: format!("solidity-{pattern}-{}-{line}", path.display()),
        debt_type: DebtType::CodeSmell {
            smell_type: Some(pattern.to_string()),
        },
        priority: definition.priority,
        file: path.to_path_buf(),
        line,
        column: None,
        message: format!("Contract '{contract_name}' {}", definition.message),
        context: Some(definition.context.to_string()),
    })
}

fn complexity_debt(path: &Path, function: &FunctionMetrics, threshold: u32) -> DebtItem {
    let max_complexity = function.cyclomatic.max(function.cognitive);

    DebtItem {
        id: format!(
            "solidity-high-complexity-{}-{}",
            path.display(),
            function.line
        ),
        debt_type: DebtType::Complexity {
            cyclomatic: function.cyclomatic,
            cognitive: function.cognitive,
        },
        priority: complexity_priority(max_complexity, threshold),
        file: path.to_path_buf(),
        line: function.line,
        column: None,
        message: format!(
            "Function '{}' has high complexity (cyclomatic: {}, cognitive: {})",
            function.name, function.cyclomatic, function.cognitive
        ),
        context: Some("Consider breaking this function into smaller functions.".to_string()),
    }
}

fn nesting_debt(path: &Path, function: &FunctionMetrics) -> DebtItem {
    DebtItem {
        id: format!("solidity-deep-nesting-{}-{}", path.display(), function.line),
        debt_type: DebtType::NestedLoops {
            depth: function.nesting,
            complexity_estimate: format!("O(n^{})", function.nesting),
        },
        priority: if function.nesting > 6 {
            Priority::High
        } else {
            Priority::Medium
        },
        file: path.to_path_buf(),
        line: function.line,
        column: None,
        message: format!(
            "Function '{}' has deep nesting ({} levels)",
            function.name, function.nesting
        ),
        context: Some("Consider guard clauses or extracting nested logic.".to_string()),
    }
}

fn length_debt(path: &Path, function: &FunctionMetrics) -> DebtItem {
    DebtItem {
        id: format!(
            "solidity-long-function-{}-{}",
            path.display(),
            function.line
        ),
        debt_type: DebtType::CodeSmell {
            smell_type: Some("long_function".to_string()),
        },
        priority: if function.length > 100 {
            Priority::High
        } else {
            Priority::Medium
        },
        file: path.to_path_buf(),
        line: function.line,
        column: None,
        message: format!(
            "Function '{}' is too long ({} lines)",
            function.name, function.length
        ),
        context: Some("Consider splitting this function into smaller units.".to_string()),
    }
}

fn advisory_debt_items(path: &Path, function: &FunctionMetrics) -> Vec<DebtItem> {
    function
        .detected_patterns
        .clone()
        .unwrap_or_default()
        .into_iter()
        .filter_map(|pattern| advisory_debt(path, function, &pattern))
        .collect()
}

fn advisory_debt_items_for_functions(path: &Path, functions: &[FunctionMetrics]) -> Vec<DebtItem> {
    functions
        .iter()
        .filter(|function| !function.is_test)
        .flat_map(|function| advisory_debt_items(path, function))
        .collect()
}

fn advisory_debt(path: &Path, function: &FunctionMetrics, pattern: &str) -> Option<DebtItem> {
    let definition = advisory_definition(pattern)?;

    Some(DebtItem {
        id: format!("solidity-{pattern}-{}-{}", path.display(), function.line),
        debt_type: DebtType::CodeSmell {
            smell_type: Some(pattern.to_string()),
        },
        priority: definition.priority,
        file: path.to_path_buf(),
        line: function.line,
        column: None,
        message: format!(
            "Function '{}' {} — review recommended",
            function.name, definition.message
        ),
        context: Some(definition.context.to_string()),
    })
}

fn filter_suppressed_items(
    items: Vec<DebtItem>,
    suppression: &SuppressionContext,
) -> Vec<DebtItem> {
    items
        .into_iter()
        .filter(|item| !is_suppressed_item(item, suppression))
        .collect()
}

fn is_suppressed_item(item: &DebtItem, suppression: &SuppressionContext) -> bool {
    suppression.is_suppressed(item.line, &item.debt_type)
        || suppression.is_function_allowed(item.line, &item.debt_type)
}

struct AdvisoryDefinition {
    priority: Priority,
    message: &'static str,
    context: &'static str,
}

fn advisory_definition(pattern: &str) -> Option<AdvisoryDefinition> {
    let definition = match pattern {
        "tx-origin-usage" => AdvisoryDefinition {
            priority: Priority::High,
            message: "uses tx.origin for authorization",
            context: "Prefer msg.sender; tx.origin is vulnerable to phishing-style attacks.",
        },
        "unchecked-low-level-call" => AdvisoryDefinition {
            priority: Priority::High,
            message: "may perform an unchecked low-level call",
            context: "Check the return value or use a safe wrapper that reverts on failure.",
        },
        "delegatecall-usage" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "uses delegatecall",
            context: "Delegatecall executes foreign code in this contract's context; review carefully.",
        },
        "selfdestruct-usage" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "uses selfdestruct",
            context: "Contract destruction is irreversible; confirm this is intentional.",
        },
        "assembly-block" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "contains inline assembly",
            context: "Assembly bypasses Solidity safety checks and increases audit complexity.",
        },
        "unbounded-loop" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "contains a potentially unbounded loop",
            context: "Unbounded loops can cause gas DoS; consider pagination or caps.",
        },
        "external-call-before-state-update" => AdvisoryDefinition {
            priority: Priority::High,
            message: "may perform an external call before updating state",
            context: "Follow checks-effects-interactions; external calls before state updates increase reentrancy risk.",
        },
        "hardcoded-address" => AdvisoryDefinition {
            priority: Priority::Low,
            message: "contains a hardcoded address literal",
            context: "Hardcoded addresses reduce maintainability across deployments.",
        },
        "missing-access-control" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "is public/external without visible access control",
            context: "Confirm authorization is enforced via modifiers or explicit checks.",
        },
        "unchecked-arithmetic" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "uses an unchecked arithmetic block",
            context: "Unchecked arithmetic skips overflow checks; confirm bounds are proven elsewhere.",
        },
        "unsafe-erc20-transfer" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "may call ERC20 transfer functions without checking the result",
            context: "Use SafeERC20 wrappers or explicitly validate token transfer return values.",
        },
        "push-without-length-cap" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "pushes to a collection without an obvious length cap",
            context: "Unbounded storage growth can increase gas costs or create denial-of-service risk.",
        },
        "block-timestamp-dependency" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "depends on block.timestamp",
            context: "Timestamp-dependent logic can be miner/validator-influenced within protocol limits.",
        },
        "tx-gas-price-dependency" => AdvisoryDefinition {
            priority: Priority::Low,
            message: "depends on tx.gasprice",
            context: "Gas price assumptions are brittle across fee markets and transaction relayers.",
        },
        "encode-packed-collision" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "uses abi.encodePacked",
            context: "Packed encoding with dynamic values can create hash collision ambiguity; review typed inputs.",
        },
        "delegatecall-in-constructor" => AdvisoryDefinition {
            priority: Priority::High,
            message: "uses delegatecall during construction",
            context: "Constructor delegatecalls can create proxy initialization and storage-layout risks.",
        },
        "mutability-mismatch" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "declared mutability may not match detected effects",
            context: "Review pure/view/payable keywords against state reads, writes, and external calls.",
        },
        _ => return None,
    };

    Some(definition)
}

fn contract_advisory_definition(pattern: &str) -> Option<AdvisoryDefinition> {
    let definition = match pattern {
        "floating-pragma" => AdvisoryDefinition {
            priority: Priority::Low,
            message: "uses a floating pragma",
            context: "Pin compiler versions to reduce unexpected behavior across builds.",
        },
        "large-contract" => AdvisoryDefinition {
            priority: Priority::Medium,
            message: "is large (many functions or state variables)",
            context: "Large contracts are harder to audit and may approach deployment size limits.",
        },
        _ => return None,
    };

    Some(definition)
}

fn complexity_priority(complexity: u32, threshold: u32) -> Priority {
    if complexity > threshold * 2 {
        Priority::Critical
    } else if complexity > threshold + 5 {
        Priority::High
    } else {
        Priority::Medium
    }
}

fn count_callables(node: tree_sitter::Node) -> usize {
    let mut count = usize::from(matches!(
        node.kind(),
        "function_definition" | "modifier_definition" | "constructor" | "fallback" | "receive"
    ));
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        count += count_callables(child);
    }
    count
}