Skip to main content

no_mistakes_postgres_engine/catalog/
function.rs

1use super::{function_body::BodyForm, model::CatalogFunction};
2use std::borrow::Cow;
3
4impl CatalogFunction {
5    pub fn body_as_statements(&self) -> Option<Cow<'_, str>> {
6        let body = self.body.as_deref()?;
7        Some(if self.body_is_expression {
8            Cow::Owned(format!("SELECT {body}"))
9        } else {
10            Cow::Borrowed(body)
11        })
12    }
13}
14
15pub(super) fn function_from_definition(key: &str, definition: &str) -> CatalogFunction {
16    let (name, signature) = split_key(key);
17    let (header, body, body_span, form) = match super::function_body::split_body(definition) {
18        Some(((header, body, span), form)) => (header, Some(body), Some(span), Some(form)),
19        None => (definition.to_string(), None, None, None),
20    };
21    let plain = strip_quotes_and_comments(&header);
22    let modes = super::function_clauses::header_modes(definition, body_span);
23    let routine_language = if matches!(form, Some(BodyForm::Atomic | BodyForm::Return)) {
24        inline_language(super::function_outputs::after_parameter_list(&header))
25            .or_else(|| body_span.and_then(|(_, end)| inline_language(&definition[end..])))
26            .or_else(|| Some("sql".to_string()))
27    } else {
28        language(definition, body_span)
29    };
30    CatalogFunction {
31        key: key.to_string(),
32        name,
33        signature,
34        language: routine_language,
35        returns_set: None,
36        returns_trigger: returns_clause(&plain, "trigger"),
37        returns_event_trigger: returns_clause(&plain, "event_trigger"),
38        definition: definition.to_string(),
39        body,
40        body_is_expression: matches!(form, Some(BodyForm::Return)),
41        null_input: modes.null_input,
42        security: modes.security,
43        parallel: modes.parallel,
44        leakproof: modes.leakproof,
45        volatility: modes.volatility,
46        return_contract: modes.return_contract,
47        planner: modes.planner,
48        body_span,
49    }
50}
51
52fn split_key(key: &str) -> (String, Option<String>) {
53    let mut quoted = false;
54    let mut chars = key.char_indices().peekable();
55    while let Some((index, character)) = chars.next() {
56        if character == '"' {
57            if quoted && chars.peek().is_some_and(|(_, next)| *next == '"') {
58                chars.next();
59                continue;
60            }
61            quoted = !quoted;
62            continue;
63        }
64        if character == '(' && !quoted {
65            let name = key[..index].trim().to_string();
66            let rest = key[index + 1..].trim();
67            let signature = rest.strip_suffix(')').unwrap_or(rest).trim();
68            return (name, Some(signature.to_string()));
69        }
70    }
71    (key.trim().to_string(), None)
72}
73
74fn language(definition: &str, span: Option<(usize, usize)>) -> Option<String> {
75    let bytes = definition.as_bytes();
76    let mut index = 0;
77    let mut depth = 0i32;
78    while index < definition.len() {
79        if let Some((start, end)) = span {
80            if index >= start && index < end {
81                index = end;
82                continue;
83            }
84        }
85        if let Some(end) = super::function_body::skip_noise(definition, index) {
86            index = end;
87            continue;
88        }
89        match bytes[index] {
90            b'(' => depth += 1,
91            b')' => depth -= 1,
92            _ => {}
93        }
94        if depth == 0 && is_word_at(definition, index, "language") {
95            let cursor = super::function_body::skip_as_gap(definition, index + "language".len());
96            if let Some(name) = language_name(definition, cursor) {
97                return Some(name);
98            }
99        }
100        index += definition[index..].chars().next()?.len_utf8();
101    }
102    None
103}
104
105fn language_name(definition: &str, mut cursor: usize) -> Option<String> {
106    let rest = definition.get(cursor..)?;
107    if rest.starts_with('\'') || rest.starts_with('"') {
108        let quote = rest.chars().next()?;
109        let end = super::function_comment::quoted_end(definition, cursor, quote)?;
110        let inner = &definition[cursor + quote.len_utf8()..end - quote.len_utf8()];
111        return (!inner.is_empty()).then(|| {
112            if quote == '"' {
113                inner.to_string()
114            } else {
115                inner.to_ascii_lowercase()
116            }
117        });
118    }
119    let start = cursor;
120    while definition.as_bytes().get(cursor).is_some_and(is_ident_byte) {
121        cursor += 1;
122    }
123    (cursor > start).then(|| definition[start..cursor].to_ascii_lowercase())
124}
125
126fn inline_language(tail: &str) -> Option<String> {
127    let after_keyword = no_mistakes_postgres_sql::source::inline_language_keyword(tail)?;
128    language_name(tail, super::function_body::skip_as_gap(tail, after_keyword))
129}
130
131fn strip_quotes_and_comments(text: &str) -> String {
132    let mut out = String::with_capacity(text.len());
133    let mut index = 0;
134    while index < text.len() {
135        if let Some(end) = super::function_body::skip_noise(text, index) {
136            out.push(' ');
137            index = end;
138            continue;
139        }
140        let Some(character) = text[index..].chars().next() else {
141            break;
142        };
143        out.push(character);
144        index += character.len_utf8();
145    }
146    out
147}
148
149fn returns_clause(header: &str, word: &str) -> bool {
150    let lower = header.to_ascii_lowercase();
151    let mut rest = lower.as_str();
152    while let Some(index) = rest.find("returns") {
153        let before = index == 0 || !is_ident_byte(&rest.as_bytes()[index - 1]);
154        let after = rest[index + "returns".len()..].trim_start();
155        if before && word_starts(after, word) {
156            return true;
157        }
158        rest = &rest[index + "returns".len()..];
159    }
160    false
161}
162
163fn word_starts(text: &str, word: &str) -> bool {
164    let Some(rest) = text.get(..word.len()) else {
165        return false;
166    };
167    if !rest.eq_ignore_ascii_case(word) {
168        return false;
169    }
170    text.as_bytes()
171        .get(word.len())
172        .is_none_or(|byte| !is_ident_byte(byte))
173}
174
175fn is_word_at(text: &str, index: usize, word: &str) -> bool {
176    let Some(slice) = text.get(index..index + word.len()) else {
177        return false;
178    };
179    if !slice.eq_ignore_ascii_case(word) {
180        return false;
181    }
182    let before_ok = index == 0 || !is_ident_byte(&text.as_bytes()[index - 1]);
183    let after = text.as_bytes().get(index + word.len());
184    before_ok && after.is_none_or(|byte| !is_ident_byte(byte))
185}
186
187fn is_ident_byte(byte: &u8) -> bool {
188    byte.is_ascii_alphanumeric() || *byte == b'_'
189}