spring_controller_parser/
lib.rs1use pest::{Parser, iterators::Pair};
2use thiserror::Error;
3
4pub mod ast;
5use ast::{Controller, ControllerMethod};
6
7#[derive(pest_derive::Parser)]
9#[grammar = "./grammar.pest"]
10pub struct Grammar;
11
12#[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}
26pub 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
47fn 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}
71fn 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}
91fn 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}
115fn 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}
152fn 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}