kinetics_parser/
parser.rs

1use crate::{environment::Environment, Cron, Endpoint, Worker};
2use syn::{
3    parse::Parse,
4    visit::Visit,
5    {Attribute, ItemFn},
6};
7
8/// Represents a function in the source code
9#[derive(Debug)]
10pub struct ParsedFunction {
11    /// Name of the function, parsed from the function definition
12    pub rust_function_name: String,
13
14    /// Path to the file where function is defined
15    pub relative_path: String,
16
17    /// Parsed from kinetics_macro macro definition
18    pub role: Role,
19}
20
21impl ParsedFunction {
22    /// Generate lambda function name out of Rust function name or macro attribute
23    ///
24    /// By default use the Rust function plus crate path as the function name. Convert
25    /// some-name to SomeName, and do other transformations in order to comply with Lambda
26    /// function name requirements.
27    pub fn func_name(&self, is_local: bool) -> String {
28        let rust_name = &self.rust_function_name;
29        let full_path = format!("{}/{rust_name}", self.relative_path);
30
31        let default_func_name = full_path
32            .as_str()
33            .replace("_", "Undrscr")
34            .replace("_", "Dash")
35            .split(&['.', '/'])
36            .filter(|s| !s.eq(&"rs"))
37            .map(|s| match s.chars().next() {
38                Some(first) => first.to_uppercase().collect::<String>() + &s[1..],
39                None => String::new(),
40            })
41            .collect::<String>()
42            .replacen("Src", "", 1);
43
44        // TODO Check the name for uniqueness
45        format!(
46            "{}{}",
47            self.role.name().unwrap_or(&default_func_name),
48            if is_local { "Local" } else { "" }
49        )
50    }
51}
52
53#[derive(Debug)]
54pub enum Role {
55    Endpoint(Endpoint),
56    Cron(Cron),
57    Worker(Worker),
58}
59
60impl Role {
61    pub fn name(&self) -> Option<&String> {
62        match self {
63            Role::Endpoint(params) => params.name.as_ref(),
64            Role::Cron(params) => params.name.as_ref(),
65            Role::Worker(params) => params.name.as_ref(),
66        }
67    }
68
69    pub fn environment(&self) -> &Environment {
70        match self {
71            Role::Endpoint(params) => &params.environment,
72            Role::Cron(params) => &params.environment,
73            Role::Worker(params) => &params.environment,
74        }
75    }
76}
77
78#[derive(Debug, Default)]
79pub struct Parser {
80    /// All found functions in the source code
81    pub functions: Vec<ParsedFunction>,
82
83    /// Relative path to currently processing file
84    pub relative_path: String,
85}
86
87impl Parser {
88    pub fn new() -> Self {
89        Default::default()
90    }
91
92    pub fn set_relative_path(&mut self, file_path: Option<&str>) {
93        self.relative_path = file_path.map_or_else(|| "".to_string(), |s| s.to_string());
94    }
95
96    fn parse_endpoint(&mut self, attr: &Attribute) -> syn::Result<Endpoint> {
97        attr.parse_args_with(Endpoint::parse)
98    }
99
100    fn parse_worker(&mut self, attr: &Attribute) -> syn::Result<Worker> {
101        attr.parse_args_with(Worker::parse)
102    }
103
104    fn parse_cron(&mut self, attr: &Attribute) -> syn::Result<Cron> {
105        attr.parse_args_with(Cron::parse)
106    }
107
108    /// Checks if the input is a valid kinetics_macro definition and returns its role
109    /// Checks if the input is a valid kinetics_macro definition
110    /// Known definitions:
111    /// kinetics_macro::<role> or <role>
112    fn parse_attr_role(&self, input: &Attribute) -> String {
113        let path = input.path();
114
115        if path.segments.len() == 1 {
116            let ident = &path.segments[0].ident;
117            return ident.to_string();
118        }
119
120        if path.segments.len() == 2 && &path.segments[0].ident == "kinetics_macro" {
121            let ident = &path.segments[1].ident;
122            return ident.to_string();
123        }
124
125        "".to_string()
126    }
127}
128
129impl Visit<'_> for Parser {
130    /// Visits function definitions
131    fn visit_item_fn(&mut self, item: &ItemFn) {
132        for attr in &item.attrs {
133            // Skip non-endpoint or non-worker attributes
134            let role = match self.parse_attr_role(attr).as_str() {
135                "endpoint" => {
136                    let params = self.parse_endpoint(attr).unwrap();
137                    Role::Endpoint(params)
138                }
139                "worker" => {
140                    let params = self.parse_worker(attr).unwrap();
141                    Role::Worker(params)
142                }
143                "cron" => {
144                    let params = self.parse_cron(attr).unwrap();
145                    Role::Cron(params)
146                }
147                _ => continue,
148            };
149
150            self.functions.push(ParsedFunction {
151                role,
152                rust_function_name: item.sig.ident.to_string(),
153                relative_path: self.relative_path.clone(),
154            });
155        }
156
157        // We don't need to parse the function body (in case nested functions), so just exit here
158    }
159}