traverse-graph 0.1.4

Call graph analysis and visualization for Solidity smart contracts
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
/*
    This module is responsible for parsing NatSpec documentation comments
    commonly found in Solidity source code. NatSpec comments provide a
    standardized way to document contracts, functions, parameters, return
    values, and other code elements.

    The primary functionality includes:
    - Defining data structures (`NatSpecKind`, `NatSpecItem`, `NatSpec`)
      to represent the parsed NatSpec information.
    - Implementing `nom` parsers to break down raw comment strings (both
      single-line `///` and multi-line `/** ... */`) into these
      structured types.
    - Handling various NatSpec tags like `@title`, `@author`, `@notice`,
      `@dev`, `@param`, `@return`, `@inheritdoc`, and custom tags
      (`@custom:...`).
    - Providing utility functions on the `NatSpec` struct to query and
      manipulate the parsed documentation, such as populating return item
      names and counting specific tag occurrences.

    The main entry point for parsing is the `parse_natspec_comment` function,
    which takes a raw comment string and attempts to parse it into a
    `NatSpec` struct.
*/
use nom::{
    branch::alt,
    bytes::complete::{tag, take_while1},
    character::complete::{
        anychar, char, line_ending, multispace0, not_line_ending, space0, space1,
    },
    combinator::{cut, map, not, opt, peek, recognize},
    multi::{many0, separated_list0},
    sequence::{delimited, pair, preceded},
    IResult, Parser,
};
use serde::{Deserialize, Serialize};
use std::ops::Range;

pub mod extract;

#[derive(Default, Copy, Clone, PartialEq, Eq, Debug, Hash, Serialize, Deserialize)]
pub struct TextIndex {
    pub utf8: usize,
    pub line: usize,
    pub column: usize,
}

pub type TextRange = Range<TextIndex>;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identifier {
    pub name: Option<String>,
    pub span: TextRange,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NatSpecKind {
    Title,
    Author,
    Notice,
    Dev,
    Param { name: String },
    Return { name: Option<String> },
    Inheritdoc { parent: String },
    Custom { tag: String },
}

impl NatSpecKind {
    pub fn is_param(&self) -> bool {
        matches!(self, NatSpecKind::Param { .. })
    }
    pub fn is_return(&self) -> bool {
        matches!(self, NatSpecKind::Return { .. })
    }
    pub fn is_notice(&self) -> bool {
        matches!(self, NatSpecKind::Notice)
    }
    pub fn is_dev(&self) -> bool {
        matches!(self, NatSpecKind::Dev)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NatSpecItem {
    pub kind: NatSpecKind,
    pub comment: String,
}

impl NatSpecItem {
    pub fn populate_return(&mut self, returns: &[Identifier]) {
        if !matches!(self.kind, NatSpecKind::Return { name: _ }) {
            return;
        }
        
        // If already populated with a name, don't reprocess
        if let NatSpecKind::Return { name: Some(_) } = &self.kind {
            return;
        }
        
        let name = self
            .comment
            .split_whitespace()
            .next()
            .filter(|first_word| {
                returns.iter().any(|r| match &r.name {
                    Some(name) => first_word == name,
                    None => false,
                })
            })
            .map(ToOwned::to_owned);

        if let Some(name_val) = &name {
            if let Some(stripped_comment) = self.comment.strip_prefix(name_val) {
                self.comment = stripped_comment.trim_start().to_string();
            }
        }
        self.kind = NatSpecKind::Return { name };
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.kind == NatSpecKind::Notice && self.comment.is_empty()
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NatSpec {
    pub items: Vec<NatSpecItem>,
}

impl NatSpec {
    pub fn append(&mut self, other: &mut Self) {
        self.items.append(&mut other.items);
    }

    #[must_use]
    pub fn populate_returns(mut self, returns: &[Identifier]) -> Self {
        for i in &mut self.items {
            i.populate_return(returns);
        }
        self
    }

    #[must_use]
    pub fn count_param(&self, ident: &Identifier) -> usize {
        let Some(ident_name) = &ident.name else {
            return 0;
        };
        self.items
            .iter()
            .filter(|n| match &n.kind {
                NatSpecKind::Param { name } => name == ident_name,
                _ => false,
            })
            .count()
    }

    #[must_use]
    pub fn count_return(&self, ident: &Identifier) -> usize {
        let Some(ident_name) = &ident.name else {
            return 0;
        };
        self.items
            .iter()
            .filter(|n| match &n.kind {
                NatSpecKind::Return { name: Some(name) } => name == ident_name,
                _ => false,
            })
            .count()
    }

    #[must_use]
    pub fn count_unnamed_returns(&self) -> usize {
        self.items
            .iter()
            .filter(|n| matches!(&n.kind, NatSpecKind::Return { name: None }))
            .count()
    }

    #[must_use]
    pub fn count_all_returns(&self) -> usize {
        self.items.iter().filter(|n| n.kind.is_return()).count()
    }

    #[must_use]
    pub fn has_param(&self) -> bool {
        self.items.iter().any(|n| n.kind.is_param())
    }

    #[must_use]
    pub fn has_return(&self) -> bool {
        self.items.iter().any(|n| n.kind.is_return())
    }

    #[must_use]
    pub fn has_notice(&self) -> bool {
        self.items.iter().any(|n| n.kind.is_notice())
    }

    #[must_use]
    pub fn has_dev(&self) -> bool {
        self.items.iter().any(|n| n.kind.is_dev())
    }
}

impl From<NatSpecItem> for NatSpec {
    fn from(value: NatSpecItem) -> Self {
        Self { items: vec![value] }
    }
}

fn trim_str(input: &str) -> String {
    input.trim().to_string()
}

fn parse_identifier_str(input: &str) -> IResult<&str, String> {
    let mut parser = map(take_while1(|c: char| !c.is_whitespace()), |s: &str| {
        s.to_string()
    });
    parser.parse(input)
}

fn parse_natspec_kind(input: &str) -> IResult<&str, NatSpecKind> {
    let mut parser = alt((
        map(tag("@title"), |_| NatSpecKind::Title),
        map(tag("@author"), |_| NatSpecKind::Author),
        map(tag("@notice"), |_| NatSpecKind::Notice),
        map(tag("@dev"), |_| NatSpecKind::Dev),
        map(
            preceded(pair(tag("@param"), space1), parse_identifier_str),
            |name| NatSpecKind::Param { name },
        ),
        map(tag("@return"), |_| NatSpecKind::Return { name: None }),
        map(
            preceded(pair(tag("@inheritdoc"), space1), parse_identifier_str),
            |parent| NatSpecKind::Inheritdoc { parent },
        ),
        map(
            preceded(tag("@custom:"), parse_identifier_str),
            |tag_name| NatSpecKind::Custom { tag: tag_name },
        ),
    ));
    parser.parse(input)
}

fn parse_comment_text(input: &str) -> IResult<&str, String> {
    let mut parser = map(not_line_ending, trim_str);
    parser.parse(input)
}

fn parse_multiline_comment_text(input: &str) -> IResult<&str, String> {
    let mut parser = map(
        recognize(many0(preceded(
            not(peek(alt((line_ending, tag("*/"))))),
            anychar,
        ))),
        |s: &str| s.trim().to_string(),
    );
    parser.parse(input)
}

fn parse_one_multiline_natspec_item(input: &str) -> IResult<&str, NatSpecItem> {
    // First check if we're at the closing part of the comment
    if input.trim_start().starts_with("*/") {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Char,
        )));
    }

    let (remaining_input, (_lead_space_consumed, _star_opt, _mid_space_consumed, kind_opt, _trail_space_consumed, comment_str)) = (
        space0,
        opt(many0(char('*'))),  // Changed to consume multiple asterisks
        space0,
        opt(parse_natspec_kind),
        space0,
        parse_multiline_comment_text,
    ).parse(input)?;

    let item = NatSpecItem {
        kind: kind_opt.unwrap_or(NatSpecKind::Notice),
        comment: comment_str,
    };

    Ok((remaining_input, item))
}

fn parse_multiline_comment(input: &str) -> IResult<&str, NatSpec> {
    // First check if input starts with /*** which is invalid
    if input.starts_with("/***") {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }
    
    let mut parser = map(
        delimited(
            // Changed multispace0 to space0 after tag("/**").
            // space0 will consume spaces/tabs on the same line as "/**", but not a newline.
            // If there's a newline after "/**", the first parse_one_multiline_natspec_item's
            // leading space0 or the separated_list0's line_ending logic will handle it.
            (tag("/**"), space0),
            separated_list0(line_ending, parse_one_multiline_natspec_item),
            preceded(multispace0, tag("*/")),
        ),
        |items| {
            // Filter out any completely empty NatSpecItems (Notice with empty comment)
            // that might arise from lines like " * " or the final " */" if not handled by line_ending.
            let filtered_items = items.into_iter().filter(|item| !item.is_empty()).collect();
            NatSpec { items: filtered_items }
        },
    );
    parser.parse(input)
}

fn parse_empty_multiline_comment(input: &str) -> IResult<&str, NatSpec> {
    // Match /**/ or /** */ but not /***/ or similar
    let mut parser = map(
        preceded(
            tag("/**"),
            preceded(space0, tag("*/"))
        ),
        |_| NatSpec::default(),
    );
    parser.parse(input)
}

fn parse_single_line_natspec_item(input: &str) -> IResult<&str, NatSpecItem> {
    let mut parser = map(
        (space0, opt(parse_natspec_kind), space0, parse_comment_text),
        |(_, kind_opt, _, comment_str)| NatSpecItem {
            kind: kind_opt.unwrap_or(NatSpecKind::Notice),
            comment: comment_str,
        },
    );
    parser.parse(input)
}

fn parse_single_line_comment(input: &str) -> IResult<&str, NatSpec> {
    let mut parser = map(
        preceded(
            (tag("///"), cut(not(char('/')))),
            parse_single_line_natspec_item,
        ),
        |item| {
            if item.is_empty() {
                NatSpec::default()
            } else {
                NatSpec { items: vec![item] }
            }
        },
    );
    parser.parse(input)
}

fn do_parse_natspec_comment(input: &str) -> IResult<&str, NatSpec> {
    let trimmed_input = input.trim();
    let mut parser = alt((
        parse_single_line_comment,
        parse_multiline_comment,
        parse_empty_multiline_comment,
    ));
    parser.parse(trimmed_input)
}

/// Parses a raw Natspec comment string into a structured `NatSpec` object.
///
/// This function handles both single-line (`///`) and multi-line (`/** ... */`)
/// Natspec comments. It trims the input string before parsing.
///
/// # Arguments
///
/// * `input`: A string slice representing the raw Natspec comment.
///
/// # Returns
///
/// * `anyhow::Result<NatSpec>`: A result containing the parsed `NatSpec` on success,
///   or an `anyhow::Error` if parsing fails.
pub fn parse_natspec_comment(input: &str) -> anyhow::Result<NatSpec> {
    use nom::Finish; // Keep Finish scoped to this function
    match do_parse_natspec_comment(input).finish() {
        Ok((_, natspec)) => Ok(natspec),
        Err(e) => {
            // Use a simpler error message approach that doesn't rely on convert_error
            Err(anyhow::anyhow!(
                "Failed to parse Natspec comment: {}",
                e
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use nom::Finish;

    #[test]
    fn test_parse_identifier_str_parser() {
        assert_eq!(
            parse_identifier_str("foo bar"),
            Ok((" bar", "foo".to_string()))
        );
        assert_eq!(parse_identifier_str("foo"), Ok(("", "foo".to_string())));
    }

    #[test]
    fn test_natspec_kind_parser() {
        assert_eq!(parse_natspec_kind("@title"), Ok(("", NatSpecKind::Title)));
        assert_eq!(parse_natspec_kind("@author"), Ok(("", NatSpecKind::Author)));
        assert_eq!(parse_natspec_kind("@notice"), Ok(("", NatSpecKind::Notice)));
        assert_eq!(parse_natspec_kind("@dev"), Ok(("", NatSpecKind::Dev)));
        assert_eq!(
            parse_natspec_kind("@param foo"),
            Ok((
                "",
                NatSpecKind::Param {
                    name: "foo".to_string()
                }
            ))
        );
        assert_eq!(
            parse_natspec_kind("@return"),
            Ok(("", NatSpecKind::Return { name: None }))
        );
        assert_eq!(
            parse_natspec_kind("@inheritdoc ISome"),
            Ok((
                "",
                NatSpecKind::Inheritdoc {
                    parent: "ISome".to_string()
                }
            ))
        );
        assert_eq!(
            parse_natspec_kind("@custom:tagname"),
            Ok((
                "",
                NatSpecKind::Custom {
                    tag: "tagname".to_string()
                }
            ))
        );
    }

    #[test]
    fn test_one_multiline_item_parser() {
        let cases = [
            ("* @dev Hello world", NatSpecKind::Dev, "Hello world"),
            (" @title The Title", NatSpecKind::Title, "The Title"),
            (
                "* @author McGyver <hi@buildanything.com>",
                NatSpecKind::Author,
                "McGyver <hi@buildanything.com>",
            ),
            (
                " @param foo The bar",
                NatSpecKind::Param {
                    name: "foo".to_string(),
                },
                "The bar",
            ),
            (
                " @return something The return value",
                NatSpecKind::Return { name: None },
                "something The return value",
            ),
            (
                "* @custom:foo bar",
                NatSpecKind::Custom {
                    tag: "foo".to_string(),
                },
                "bar",
            ),
            ("  lorem ipsum", NatSpecKind::Notice, "lorem ipsum"),
            ("lorem ipsum", NatSpecKind::Notice, "lorem ipsum"),
            ("*  foobar", NatSpecKind::Notice, "foobar"),
        ];
        for (input, kind, comment) in cases {
            let res = parse_one_multiline_natspec_item(input).finish();
            assert!(
                res.is_ok(),
                "Failed on input: '{}', Error: {:?}",
                input,
                res.err()
            );
            let (_, item) = res.unwrap();
            assert_eq!(item.kind, kind);
            assert_eq!(item.comment, comment.to_string());
        }
    }

    #[test]
    fn test_single_line_comment_parser() {
        let cases = [
            ("/// Foo bar", NatSpecKind::Notice, "Foo bar"),
            ("///  Baz", NatSpecKind::Notice, "Baz"),
            (
                "/// @notice  Hello world",
                NatSpecKind::Notice,
                "Hello world",
            ),
            (
                "/// @param foo This is bar",
                NatSpecKind::Param {
                    name: "foo".to_string(),
                },
                "This is bar",
            ),
            (
                "/// @return The return value",
                NatSpecKind::Return { name: None },
                "The return value",
            ),
            (
                "/// @custom:foo  This is bar",
                NatSpecKind::Custom {
                    tag: "foo".to_string(),
                },
                "This is bar",
            ),
        ];
        for (input, kind, comment) in cases {
            let res = parse_natspec_comment(input);
            assert!(
                res.is_ok(),
                "Failed on input: '{}', Error: {:?}",
                input,
                res.err()
            );
            let natspec = res.unwrap();
            assert_eq!(natspec.items.len(), 1);
            assert_eq!(natspec.items[0].kind, kind);
            assert_eq!(natspec.items[0].comment, comment.to_string());
        }
    }

    #[test]
    fn test_single_line_empty() {
        let res = parse_natspec_comment("///");
        assert!(res.is_ok(), "{:?}", res.err());
        let natspec = res.unwrap();
        assert_eq!(natspec, NatSpec::default());

        let res = parse_natspec_comment("/// ");
        assert!(res.is_ok(), "{:?}", res.err());
        let natspec = res.unwrap();
        assert_eq!(natspec, NatSpec::default());
    }

    #[test]
    fn test_single_line_invalid_delimiter() {
        let res = parse_natspec_comment("//// Hello");
        assert!(res.is_err());
    }

    #[test]
    fn test_multiline_comment_parser() {
        let comment = "/**\n     * @notice Some notice text.\n     */";
        let res = parse_natspec_comment(comment);
        assert!(res.is_ok(), "{:?}", res.err());
        let natspec = res.unwrap();
        assert_eq!(natspec.items.len(), 1);
        assert_eq!(
            natspec.items[0],
            NatSpecItem {
                kind: NatSpecKind::Notice,
                comment: "Some notice text.".to_string()
            }
        );
    }

    #[test]
    fn test_multiline_two_items() {
        let comment = "/**\n     * @notice Some notice text.\n     * @custom:something\n     */";
        let res = parse_natspec_comment(comment);
        assert!(res.is_ok(), "{:?}", res.err());
        let natspec = res.unwrap();
        assert_eq!(natspec.items.len(), 2);
        assert_eq!(
            natspec.items[0],
            NatSpecItem {
                kind: NatSpecKind::Notice,
                comment: "Some notice text.".to_string()
            }
        );
        assert_eq!(
            natspec.items[1],
            NatSpecItem {
                kind: NatSpecKind::Custom {
                    tag: "something".to_string()
                },
                comment: "".to_string()
            }
        );
    }

    #[test]
    fn test_multiline_mixed_leading_asterisks() {
        let comment = "/** @notice First line.\n  Another line, no asterisk.\n\t* @param p The param\n ** @dev Dev comment */";
        let res = parse_natspec_comment(comment);
        assert!(res.is_ok(), "Input: '{}'\nError: {:?}", comment, res.err());
        let natspec = res.unwrap();

        assert_eq!(natspec.items.len(), 4);
        assert_eq!(
            natspec.items[0],
            NatSpecItem {
                kind: NatSpecKind::Notice,
                comment: "First line.".to_string()
            }
        );
        assert_eq!(
            natspec.items[1],
            NatSpecItem {
                kind: NatSpecKind::Notice,
                comment: "Another line, no asterisk.".to_string()
            }
        );
        assert_eq!(
            natspec.items[2],
            NatSpecItem {
                kind: NatSpecKind::Param {
                    name: "p".to_string()
                },
                comment: "The param".to_string()
            }
        );
        assert_eq!(
            natspec.items[3],
            NatSpecItem {
                kind: NatSpecKind::Dev,
                comment: "Dev comment".to_string()
            }
        );
    }

    #[test]
    fn test_multiline_empty_comment() {
        let comment = "/**\n        */";
        let res = parse_natspec_comment(comment);
        assert!(res.is_ok(), "{:?}", res.err());
        let natspec = res.unwrap();
        assert_eq!(natspec, NatSpec::default());

        let comment = "/** */";
        let res = parse_natspec_comment(comment);
        assert!(res.is_ok(), "{:?}", res.err());
        let natspec = res.unwrap();
        assert_eq!(natspec, NatSpec::default());

        let comment = "/***/";
        let res = parse_natspec_comment(comment);
        assert!(res.is_ok(), "{:?}", res.err());
        let natspec = res.unwrap();
        assert_eq!(natspec, NatSpec::default());
    }

    #[test]
    fn test_multiline_invalid_delimiter() {
        let comment = "/*** @notice Some text\n    ** */";
        let res = parse_natspec_comment(comment);
        // Debug: Parse result for '/***'
        assert!(res.is_err(), "Expected error for input: {}", comment);
    }

    #[test]
    fn test_populate_returns_logic() {
        let mut item = NatSpecItem {
            kind: NatSpecKind::Return { name: None },
            comment: "value The value returned".to_string(),
        };
        let identifiers = vec![
            Identifier {
                name: Some("value".to_string()),
                span: TextRange::default(),
            },
            Identifier {
                name: Some("success".to_string()),
                span: TextRange::default(),
            },
        ];
        item.populate_return(&identifiers);
        assert_eq!(
            item.kind,
            NatSpecKind::Return {
                name: Some("value".to_string())
            }
        );
        assert_eq!(item.comment, "The value returned".to_string());

        let mut natspec = NatSpec { items: vec![item] };
        natspec = natspec.populate_returns(&identifiers);
        assert_eq!(
            natspec.items[0].kind,
            NatSpecKind::Return {
                name: Some("value".to_string())
            }
        );
        assert_eq!(natspec.items[0].comment, "The value returned".to_string());
    }

    #[test]
    fn test_populate_returns_no_match() {
        let mut item = NatSpecItem {
            kind: NatSpecKind::Return { name: None },
            comment: "Something else".to_string(),
        };
        let identifiers = vec![Identifier {
            name: Some("value".to_string()),
            span: TextRange::default(),
        }];
        item.populate_return(&identifiers);
        assert_eq!(item.kind, NatSpecKind::Return { name: None });
        assert_eq!(item.comment, "Something else".to_string());
    }
}