Skip to main content

multicast_codemode/
normalize.rs

1/// Normalizes model-generated JavaScript into an async zero-argument function.
2pub fn normalize_code(code: &str) -> String {
3    let source = strip_fence(code.trim()).trim();
4    if source.is_empty() {
5        return "async () => {}".to_string();
6    }
7    if is_arrow(source) {
8        return source.to_string();
9    }
10    if let Some(inner) = source.strip_prefix("export default ") {
11        return normalize_code(inner.trim_end_matches(';'));
12    }
13    if let Some(name) = single_function_name(source) {
14        return format!("async () => {{\n{source}\nreturn {name}();\n}}");
15    }
16    if let Some((before, expression)) = split_last_expression(source) {
17        return format!("async () => {{\n{before}return ({expression})\n}}");
18    }
19    format!("async () => {{\n{source}\n}}")
20}
21
22fn strip_fence(source: &str) -> &str {
23    let Some(after) = source.strip_prefix("```") else {
24        return source;
25    };
26    let Some(newline) = after.find('\n') else {
27        return source;
28    };
29    let body = &after[newline + 1..];
30    body.strip_suffix("```")
31        .map(str::trim_end)
32        .unwrap_or(source)
33}
34
35fn is_arrow(source: &str) -> bool {
36    let Some(arrow) = top_level_arrow(source) else {
37        return false;
38    };
39    let prefix = source[..arrow].trim();
40    // `async` may be followed by a space or directly by the parameter list:
41    // `async()=>{...}` is as much an arrow as `async () => {...}`.
42    let prefix = match prefix.strip_prefix("async") {
43        Some(rest) if rest.starts_with('(') || rest.starts_with(char::is_whitespace) => {
44            rest.trim_start()
45        }
46        _ => prefix,
47    };
48    // The prefix has to be the arrow's own parameter list and nothing else.
49    //
50    // Testing only that it ends with `)` accepted any program whose first
51    // top-level `=>` happened to follow a parenthesised group, so
52    // `const f = (a) => a; return f(1);` was mistaken for a single arrow
53    // expression, left unwrapped, and failed to parse — while the same program
54    // written `const f = a => a;` worked. A parameter list is either a bare
55    // identifier or one balanced group spanning the whole prefix.
56    is_identifier(prefix) || is_parameter_list(prefix)
57}
58
59/// Returns whether the text is exactly one parenthesised group.
60///
61/// The group must open at the first character and close at the last, so
62/// `(a, b)` qualifies while `const f = (a)` and `(a) + (b)` do not.
63fn is_parameter_list(prefix: &str) -> bool {
64    if !prefix.starts_with('(') || !prefix.ends_with(')') {
65        return false;
66    }
67    let mut depth = 0usize;
68    for (index, ch) in prefix.char_indices() {
69        match ch {
70            '(' | '[' | '{' => depth += 1,
71            ')' | ']' | '}' => {
72                depth = depth.saturating_sub(1);
73                if depth == 0 && index + ch.len_utf8() != prefix.len() {
74                    return false;
75                }
76            }
77            _ => {}
78        }
79    }
80    depth == 0
81}
82
83fn top_level_arrow(source: &str) -> Option<usize> {
84    let mut depth = 0;
85    let mut quote = None;
86    let mut escaped = false;
87    let mut chars = source.char_indices().peekable();
88    while let Some((index, ch)) = chars.next() {
89        if let Some(active) = quote {
90            if escaped {
91                escaped = false;
92            } else if ch == '\\' {
93                escaped = true;
94            } else if ch == active {
95                quote = None;
96            }
97            continue;
98        }
99        match ch {
100            '\'' | '"' | '`' => quote = Some(ch),
101            '(' | '[' | '{' => depth += 1,
102            ')' | ']' | '}' => depth -= 1,
103            '=' if depth == 0 && chars.peek().is_some_and(|(_, next)| *next == '>') => {
104                return Some(index);
105            }
106            _ => {}
107        }
108    }
109    None
110}
111
112fn single_function_name(source: &str) -> Option<&str> {
113    let rest = source
114        .strip_prefix("async function ")
115        .or_else(|| source.strip_prefix("function "))?;
116    let end = rest.find('(')?;
117    let name = rest[..end].trim();
118    if is_identifier(name) && balanced(source) {
119        Some(name)
120    } else {
121        None
122    }
123}
124
125fn split_last_expression(source: &str) -> Option<(&str, &str)> {
126    if !balanced(source) || source.ends_with('}') {
127        return None;
128    }
129    let mut depth = 0;
130    let mut quote = None;
131    let mut escaped = false;
132    let mut split = None;
133    for (index, ch) in source.char_indices() {
134        if let Some(active) = quote {
135            if escaped {
136                escaped = false;
137            } else if ch == '\\' {
138                escaped = true;
139            } else if ch == active {
140                quote = None;
141            }
142            continue;
143        }
144        match ch {
145            '\'' | '"' | '`' => quote = Some(ch),
146            '(' | '[' | '{' => depth += 1,
147            ')' | ']' | '}' => depth -= 1,
148            ';' if depth == 0 => split = Some(index + 1),
149            _ => {}
150        }
151    }
152    let mut index = split.unwrap_or(0);
153    while source[index..]
154        .chars()
155        .next()
156        .is_some_and(char::is_whitespace)
157    {
158        index += source[index..].chars().next().unwrap().len_utf8();
159    }
160    let expression = source[index..].trim().trim_end_matches(';').trim();
161    if expression.is_empty() || starts_statement(expression) {
162        None
163    } else {
164        Some((&source[..index], expression))
165    }
166}
167
168fn starts_statement(source: &str) -> bool {
169    [
170        "const ",
171        "let ",
172        "var ",
173        "return ",
174        "throw ",
175        "if ",
176        "for ",
177        "while ",
178        "class ",
179        "function ",
180        "import ",
181        "export ",
182        "try ",
183        "switch ",
184    ]
185    .iter()
186    .any(|prefix| source.starts_with(prefix))
187}
188
189fn balanced(source: &str) -> bool {
190    let mut stack = Vec::new();
191    let mut quote = None;
192    let mut escaped = false;
193    for ch in source.chars() {
194        if let Some(active) = quote {
195            if escaped {
196                escaped = false;
197            } else if ch == '\\' {
198                escaped = true;
199            } else if ch == active {
200                quote = None;
201            }
202            continue;
203        }
204        match ch {
205            '\'' | '"' | '`' => quote = Some(ch),
206            '(' | '[' | '{' => stack.push(ch),
207            ')' if stack.pop() != Some('(') => return false,
208            ']' if stack.pop() != Some('[') => return false,
209            '}' if stack.pop() != Some('{') => return false,
210            _ => {}
211        }
212    }
213    stack.is_empty() && quote.is_none()
214}
215
216fn is_identifier(value: &str) -> bool {
217    let mut chars = value.chars();
218    chars
219        .next()
220        .is_some_and(|ch| ch == '_' || ch == '$' || ch.is_ascii_alphabetic())
221        && chars.all(|ch| ch == '_' || ch == '$' || ch.is_ascii_alphanumeric())
222}
223
224#[cfg(test)]
225mod tests {
226
227    /// A program that names an arrow with a parenthesised parameter list was
228    /// mistaken for a single arrow expression and left unwrapped, so it reached
229    /// the sandbox as a statement list in expression position and failed with an
230    /// opaque "Exception generated by QuickJS". Writing the same program with a
231    /// bare parameter worked, which is what made it look like a sandbox fault
232    /// rather than a normalisation one.
233    #[test]
234    fn a_named_arrow_with_a_parenthesised_parameter_is_still_a_program() {
235        for source in [
236            "const f = (a) => a + 1; return f(1);",
237            "const f = (a, b) => a + b; return f(1, 2);",
238            "const run = (dir, t) => dir + t;\nreturn run(\"a\", \"b\");",
239            "const f = async (a) => a; return await f(1);",
240        ] {
241            let normalized = normalize_code(source);
242            assert!(
243                normalized.starts_with("async () => {"),
244                "must be wrapped as a program, got: {normalized}"
245            );
246        }
247    }
248
249    /// The other half of the same boundary: a source that really is one arrow
250    /// must still be passed through untouched.
251    #[test]
252    fn a_bare_arrow_expression_is_left_alone() {
253        for source in [
254            "(a) => a + 1",
255            "(a, b) => a + b",
256            "async (a) => a",
257            "a => a + 1",
258            "async () => { return 1; }",
259            "async()=>{ return 1; }",
260            "async(a)=>a",
261        ] {
262            assert_eq!(
263                normalize_code(source),
264                source,
265                "a genuine arrow must not be wrapped"
266            );
267        }
268    }
269
270    /// A parenthesised group that is not a parameter list must not be read as one.
271    #[test]
272    fn a_parenthesised_expression_before_an_arrow_is_not_a_parameter_list() {
273        assert!(!is_parameter_list("const f = (a)"));
274        assert!(!is_parameter_list("(a) + (b)"));
275        assert!(is_parameter_list("(a)"));
276        assert!(is_parameter_list("(a, b = (1))"));
277    }
278    use super::*;
279
280    #[test]
281    fn normalizes_common_model_outputs() {
282        assert_eq!(normalize_code(""), "async () => {}");
283        assert_eq!(normalize_code("async () => 1"), "async () => 1");
284        assert_eq!(
285            normalize_code("const x = 1;\nx + 2"),
286            "async () => {\nconst x = 1;\nreturn (x + 2)\n}"
287        );
288        assert_eq!(
289            normalize_code("```js\nstate.read({ id: 1 })\n```"),
290            "async () => {\nreturn (state.read({ id: 1 }))\n}"
291        );
292        assert_eq!(
293            normalize_code(
294                "const token = await codemode.step(\"token\", async () => \"stable\");\nreturn token;"
295            ),
296            "async () => {\nconst token = await codemode.step(\"token\", async () => \"stable\");\nreturn token;\n}"
297        );
298    }
299}