File: ruff_parse_simple.rs

package info (click to toggle)
ruff 0.0.291%2Bdfsg1-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 27,672 kB
  • sloc: python: 30,930; sh: 189; makefile: 9
file content (67 lines) | stat: -rw-r--r-- 2,219 bytes parent folder | download
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
//! Fuzzer harness which merely explores the parse/unparse coverage space and tries to make it
//! crash. On its own, this fuzzer is (hopefully) not going to find a crash.

#![no_main]

use libfuzzer_sys::{fuzz_target, Corpus};
use ruff_python_codegen::{Generator, Stylist};
use ruff_python_parser::{lexer, parse_suite, Mode, ParseError};
use ruff_source_file::Locator;

fn do_fuzz(case: &[u8]) -> Corpus {
    let Ok(code) = std::str::from_utf8(case) else {
        return Corpus::Reject;
    };

    // just round-trip it once to trigger both parse and unparse
    let locator = Locator::new(code);
    let python_ast = match parse_suite(code, "fuzzed-source.py") {
        Ok(stmts) => stmts,
        Err(ParseError { offset, .. }) => {
            let offset = offset.to_usize();
            assert!(
                code.is_char_boundary(offset),
                "Invalid error location {} (not at char boundary)",
                offset
            );
            return Corpus::Keep;
        }
    };

    let tokens: Vec<_> = lexer::lex(code, Mode::Module).collect();

    for maybe_token in tokens.iter() {
        match maybe_token.as_ref() {
            Ok((_, range)) => {
                let start = range.start().to_usize();
                let end = range.end().to_usize();
                assert!(
                    code.is_char_boundary(start),
                    "Invalid start position {} (not at char boundary)",
                    start
                );
                assert!(
                    code.is_char_boundary(end),
                    "Invalid end position {} (not at char boundary)",
                    end
                );
            }
            Err(err) => {
                let offset = err.location.to_usize();
                assert!(
                    code.is_char_boundary(offset),
                    "Invalid error location {} (not at char boundary)",
                    offset
                );
            }
        }
    }

    let stylist = Stylist::from_tokens(&tokens, &locator);
    let mut generator: Generator = (&stylist).into();
    generator.unparse_suite(&python_ast);

    Corpus::Keep
}

fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });