spring_controller_parser/
lib.rs

1use pest::{Parser, iterators::Pair};
2use thiserror::Error;
3
4pub mod ast;
5use ast::{Controller, ControllerMethod};
6
7///The 'Grammar' struct that uses `grammar.pest` to define rules
8#[derive(pest_derive::Parser)]
9#[grammar = "./grammar.pest"]
10pub struct Grammar;
11
12/// The `SpringControllerParserError` enum represents errors that can haapen during parsing
13#[derive(Error, Debug)]
14pub enum SpringControllerParserError {
15    #[error("parsing error: {0}")]
16    PestError(#[from] Box<pest::error::Error<Rule>>),
17    #[error("no controllers found error")]
18    NoControllers,
19    #[error("failed to extract annotation arguments for method: {0}")]
20    MethodAnnotationError(String),
21    #[error("failed to extract class name")]
22    ClassNameError,
23    #[error("extraction error: {0}")]
24    ExtractionError(String),
25}
26/// Parses a Java source string and returns all detected Spring controllers
27/// # Arguments
28/// * `src` – The Java source code as a string slice
29///
30/// # Returns
31/// A `Vec<Controller>` on success, or [`SpringControllerParserError`] on failure
32/// This func parses from the controller_file defined in `grammar.pest`
33pub fn parse_controllers(src: &str) -> Result<Vec<Controller>, SpringControllerParserError> {
34    let parse_result = Grammar::parse(Rule::controller_file, src)
35        .map_err(|e| SpringControllerParserError::PestError(Box::new(e)))?;
36    let mut controllers = Vec::new();
37    for pair in parse_result {
38        controllers.push(extract_controller(pair)?);
39    }
40    if controllers.is_empty() {
41        Err(SpringControllerParserError::NoControllers)
42    } else {
43        Ok(controllers)
44    }
45}
46
47/// Extracts a [`Controller`] from the parsed [`Pair`]
48///
49/// # Arguments
50/// * `pair` — A Pest [`Pair<Rule>`] representing a parsed controller block
51///
52/// # Returns
53/// * `Some(Controller)` if the pair represents a Spring controller
54/// * `None` if no controller annotation is present
55fn extract_controller(pair: Pair<Rule>) -> Result<Controller, SpringControllerParserError> {
56    let parsed = pair.as_str();
57    if !(parsed.contains("@Controller") || parsed.contains("@RestController")) {
58        return Err(SpringControllerParserError::NoControllers);
59    }
60
61    let name = extract_name(parsed)?;
62    let class_mapping = extract_mapping(parsed)?;
63    let methods = extract_methods(parsed)?;
64
65    Ok(Controller {
66        name,
67        class_mapping,
68        methods,
69    })
70}
71/// Extracts the class name from a `class` declaration
72/// # Arguments
73/// * `text` — The Java src text containing a optionally class declaration
74///
75/// # Returns
76/// * `Some(String)` containing the class name
77/// * `None` if no class name is found
78fn extract_name(text: &str) -> Result<String, SpringControllerParserError> {
79    let words: Vec<&str> = text.split_whitespace().collect();
80
81    for i in 0..words.len() {
82        if words[i] == "class"
83            && let Some(name) = words.get(i + 1)
84        {
85            return Ok(name.trim_end_matches('{').to_string());
86        }
87    }
88
89    Err(SpringControllerParserError::ClassNameError)
90}
91/// Extracts the argument of a class-level `@RequestMapping` annotation
92/// # Arguments
93/// * `text` — The full Java src of the controller class
94///
95/// # Returns
96/// * `Some(String)` with the request mapping path
97/// * or `None` if no `@RequestMapping` is found
98fn extract_mapping(text: &str) -> Result<Option<String>, SpringControllerParserError> {
99    if let Some(idx) = text.find("@RequestMapping") {
100        let args = text[idx..]
101            .split_once('(')
102            .and_then(|(_, rem)| rem.split_once(')'))
103            .ok_or_else(|| {
104                SpringControllerParserError::ExtractionError("@RequestMapping args".into())
105            })?
106            .0
107            .trim()
108            .trim_matches('"')
109            .to_string();
110        Ok(Some(args))
111    } else {
112        Ok(None)
113    }
114}
115/// Extracts all controller methods with mapping annotations
116/// Recognizes:
117/// - `@GetMapping`
118/// - `@PostMapping`
119/// - `@PutMapping`
120/// - `@DeleteMapping`
121/// - `@PatchMapping`
122/// - `@RequestMapping`
123///
124/// # Arguments
125/// * `s` — The Java src code of the controller class
126///
127/// # Returns
128/// * A `Vec<ControllerMethod>` representing all detected methods with mappings
129fn extract_methods(s: &str) -> Result<Vec<ControllerMethod>, SpringControllerParserError> {
130    const ANNOTMETHOD: [&str; 6] = [
131        "@GetMapping",
132        "@PostMapping",
133        "@PutMapping",
134        "@DeleteMapping",
135        "@PatchMapping",
136        "@RequestMapping",
137    ];
138
139    let mut methods = Vec::new();
140
141    for annot in ANNOTMETHOD {
142        let mut start = 0;
143        while let Some(pos) = s[start..].find(annot) {
144            let main_pos = start + pos;
145            methods.push(extract_method(s, annot, main_pos)?);
146            start = main_pos + annot.len();
147        }
148    }
149
150    Ok(methods)
151}
152/// Extracts a single controller method starting at the given position.
153/// Returns a [`ControllerMethod`] with the annotation, arguments, and method header.
154/// # Arguments
155/// * `s` — The full Java controller src text
156/// * `ann` — The mapping annotation being processed
157/// * `start_idx` — The starting index of the annotation within `s`
158///
159/// # Returns
160/// * `Some(ControllerMethod)` if a valid annotated method is found
161/// * `None` if parsing fails due to bad syntax
162///
163fn extract_method(
164    s: &str,
165    ann: &str,
166    start_idx: usize,
167) -> Result<ControllerMethod, SpringControllerParserError> {
168    let after = &s[start_idx..];
169
170    let header = after
171        .split_once('{')
172        .ok_or_else(|| SpringControllerParserError::MethodAnnotationError(ann.into()))?
173        .0
174        .lines()
175        .rev()
176        .find(|l| !l.trim().is_empty())
177        .ok_or_else(|| SpringControllerParserError::MethodAnnotationError(ann.into()))?
178        .trim()
179        .to_string();
180
181    let ann_args = after
182        .split_once('(')
183        .and_then(|(_, rem)| rem.split_once(')'))
184        .map(|(args, _)| args.trim().trim_matches('"').to_string())
185        .ok_or_else(|| SpringControllerParserError::MethodAnnotationError(ann.into()))?;
186
187    Ok(ControllerMethod {
188        annotation: Some(ann.trim_start_matches('@').to_string()),
189        annotation_args: Some(ann_args),
190        header,
191    })
192}