#![doc = include_str!("../docs.md")]
use pest::{Parser, iterators::Pair};
use thiserror::Error;
pub mod ast;
use ast::{Controller, ControllerMethod};
#[derive(pest_derive::Parser)]
#[grammar = "./grammar.pest"]
pub struct Grammar;
#[derive(Error, Debug)]
pub enum SpringControllerParserError {
#[error("parsing error: {0}")]
PestError(#[from] Box<pest::error::Error<Rule>>),
#[error("no controllers found error")]
NoControllers,
#[error("failed to extract annotation arguments for method: {0}")]
MethodAnnotationError(String),
#[error("failed to extract class name")]
ClassNameError,
#[error("extraction error: {0}")]
ExtractionError(String),
}
pub fn parse_controllers(src: &str) -> Result<Vec<Controller>, SpringControllerParserError> {
let parse_result = Grammar::parse(Rule::controller_file, src)
.map_err(|e| SpringControllerParserError::PestError(Box::new(e)))?;
let mut controllers = Vec::new();
for pair in parse_result {
controllers.push(extract_controller(pair)?);
}
if controllers.is_empty() {
Err(SpringControllerParserError::NoControllers)
} else {
Ok(controllers)
}
}
fn extract_controller(pair: Pair<Rule>) -> Result<Controller, SpringControllerParserError> {
let parsed = pair.as_str();
if !(parsed.contains("@Controller") || parsed.contains("@RestController")) {
return Err(SpringControllerParserError::NoControllers);
}
let name = extract_name(parsed)?;
let class_mapping = extract_mapping(parsed)?;
let methods = extract_methods(parsed)?;
Ok(Controller {
name,
class_mapping,
methods,
})
}
fn extract_name(text: &str) -> Result<String, SpringControllerParserError> {
let words: Vec<&str> = text.split_whitespace().collect();
for i in 0..words.len() {
if words[i] == "class"
&& let Some(name) = words.get(i + 1)
{
return Ok(name.trim_end_matches('{').to_string());
}
}
Err(SpringControllerParserError::ClassNameError)
}
fn extract_mapping(text: &str) -> Result<Option<String>, SpringControllerParserError> {
if let Some(idx) = text.find("@RequestMapping") {
let args = text[idx..]
.split_once('(')
.and_then(|(_, rem)| rem.split_once(')'))
.ok_or_else(|| {
SpringControllerParserError::ExtractionError("@RequestMapping args".into())
})?
.0
.trim()
.trim_matches('"')
.to_string();
Ok(Some(args))
} else {
Ok(None)
}
}
fn extract_methods(s: &str) -> Result<Vec<ControllerMethod>, SpringControllerParserError> {
const ANNOTMETHOD: [&str; 6] = [
"@GetMapping",
"@PostMapping",
"@PutMapping",
"@DeleteMapping",
"@PatchMapping",
"@RequestMapping",
];
let mut methods = Vec::new();
for annot in ANNOTMETHOD {
let mut start = 0;
while let Some(pos) = s[start..].find(annot) {
let main_pos = start + pos;
methods.push(extract_method(s, annot, main_pos)?);
start = main_pos + annot.len();
}
}
Ok(methods)
}
fn extract_method(
s: &str,
ann: &str,
start_idx: usize,
) -> Result<ControllerMethod, SpringControllerParserError> {
let after = &s[start_idx..];
let header = after
.split_once('{')
.ok_or_else(|| SpringControllerParserError::MethodAnnotationError(ann.into()))?
.0
.lines()
.rev()
.find(|l| !l.trim().is_empty())
.ok_or_else(|| SpringControllerParserError::MethodAnnotationError(ann.into()))?
.trim()
.to_string();
let ann_args = after
.split_once('(')
.and_then(|(_, rem)| rem.split_once(')'))
.map(|(args, _)| args.trim().trim_matches('"').to_string())
.ok_or_else(|| SpringControllerParserError::MethodAnnotationError(ann.into()))?;
Ok(ControllerMethod {
annotation: Some(ann.trim_start_matches('@').to_string()),
annotation_args: Some(ann_args),
header,
})
}