Skip to main content

larust_convert/
codegen.rs

1//! Shared "write a generated file and wire it into the module tree"
2//! primitives, used by both `xr make:*` (`larust-cli::generate`) and `xr
3//! convert` (this crate's own converters). Originally lived as private
4//! functions in `larust-cli::generate` - moved here, `pub`, because
5//! `larust-cli` depends on `larust-convert` (not the reverse), so a new
6//! crate generating controllers/models/etc. from a Laravel app couldn't
7//! reach them as private functions in a crate that depends on it. One
8//! source of truth for the real edge-case handling here (rollback-on-
9//! failure, placeholder-collision guards) beats a second copy nothing
10//! keeps in sync.
11
12use anyhow::{Context, Result};
13use std::path::Path;
14
15/// Generates a struct/type-shaped item (controller/model/request): writes
16/// `{dir}/{snake_name}.rs` from `template` (with `__NAME__`/other
17/// placeholders substituted) and registers it in `{dir}/mod.rs`.
18pub fn generate_item(
19    name: &str,
20    dir: &Path,
21    kind: &str,
22    template: &str,
23    extra_replacements: &[(&str, &str)],
24) -> Result<()> {
25    validate_identifier(name)?;
26    let mod_name = to_snake_case(name);
27    let mut content = template.replace("__NAME__", name);
28    for (placeholder, value) in extra_replacements {
29        content = content.replace(placeholder, value);
30    }
31    generate_file(dir, &mod_name, kind, &content, Some(name))
32}
33
34/// Writes `{dir}/{mod_name}.rs` (must not already exist) and registers it
35/// in `{dir}/mod.rs` as `pub mod {mod_name};`, plus `pub use
36/// {mod_name}::{export};` when `export` is `Some` - a struct name for
37/// controllers/models/requests, a function name for middleware. `None` for
38/// a file with nothing nameable to re-export (a policy's trait `impl`
39/// block is globally visible once compiled in; no re-export needed).
40pub fn generate_file(
41    dir: &Path,
42    mod_name: &str,
43    kind: &str,
44    content: &str,
45    export: Option<&str>,
46) -> Result<()> {
47    anyhow::ensure!(
48        dir.is_dir(),
49        "no {} directory found here (run this from a Larust app's root)",
50        dir.display()
51    );
52
53    let path = dir.join(format!("{mod_name}.rs"));
54    anyhow::ensure!(
55        !path.exists(),
56        "a {kind} already exists at {}",
57        path.display()
58    );
59
60    std::fs::write(&path, content).with_context(|| format!("writing {}", path.display()))?;
61
62    if let Err(err) = append_to_mod_rs(&dir.join("mod.rs"), mod_name, export) {
63        // Don't leave an orphaned, unwired (uncompiled/unverified) .rs file
64        // behind - and don't leave the target path blocked for a retry
65        // with a stale "already exists" error either.
66        let _ = std::fs::remove_file(&path);
67        return Err(err);
68    }
69
70    println!("Created {kind}: {}", path.display());
71    Ok(())
72}
73
74/// The nested-directory equivalent of [`generate_file`]: writes
75/// `{root}/{path_segments.join("/")}/{mod_name}.rs`, creating every
76/// intermediate directory and wiring each one's own `mod.rs` (`pub mod
77/// {next_segment};`, chained from `root`'s own `mod.rs` down) along the
78/// way - for a converted structure whose Laravel source used real
79/// subdirectories (`App\Livewire\Pages\Webservices\Compare`) rather than
80/// a flat namespace, so the generated output can mirror that instead of
81/// flattening it into one prefixed filename. `path_segments` empty is
82/// equivalent to calling [`generate_file`] directly.
83pub fn generate_nested_file(
84    root: &Path,
85    path_segments: &[String],
86    mod_name: &str,
87    kind: &str,
88    content: &str,
89    export: Option<&str>,
90) -> Result<()> {
91    let mut dir = root.to_path_buf();
92    for segment in path_segments {
93        let parent_mod_rs = dir.join("mod.rs");
94        std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
95        append_to_mod_rs(&parent_mod_rs, segment, None)?;
96        dir = dir.join(segment);
97    }
98    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
99    generate_file(&dir, mod_name, kind, content, export)
100}
101
102/// Adds `pub mod {mod_name};` to `mod_path` - plus `pub use
103/// {mod_name}::{export};` when `export` is `Some` - creating the file if
104/// it doesn't exist yet. A no-op if the module is already registered
105/// (re-running a generator after manually editing `mod.rs` shouldn't
106/// duplicate the declaration).
107pub fn append_to_mod_rs(mod_path: &Path, mod_name: &str, export: Option<&str>) -> Result<()> {
108    let mut existing = std::fs::read_to_string(mod_path).unwrap_or_default();
109    let mod_line = format!("pub mod {mod_name};");
110    if existing.contains(&mod_line) {
111        return Ok(());
112    }
113
114    if !existing.is_empty() && !existing.ends_with('\n') {
115        existing.push('\n');
116    }
117    existing.push_str(&mod_line);
118    existing.push('\n');
119    if let Some(export) = export {
120        existing.push_str(&format!("\npub use {mod_name}::{export};\n"));
121    }
122
123    std::fs::write(mod_path, existing).with_context(|| format!("writing {}", mod_path.display()))
124}
125
126/// Rust's reserved words (2021 edition strict keywords + words reserved
127/// for future use). Checked against both the name as given (used verbatim
128/// for struct/type names) and its snake_case form (used for module names
129/// and, for middleware, the generated function name) - `to_snake_case` can
130/// turn a charset-valid name like `Type` into the keyword `type`, which
131/// charset validation alone wouldn't catch.
132const RUST_KEYWORDS: &[&str] = &[
133    "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for",
134    "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
135    "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where",
136    "while", "async", "await", "dyn", "abstract", "become", "box", "do", "final", "macro",
137    "override", "priv", "typeof", "unsized", "virtual", "yield", "try",
138];
139
140/// `true` if `name` (verbatim) or its snake_case form is a Rust
141/// keyword - the same double check [`validate_identifier`] makes below,
142/// exposed standalone for a caller that wants to *escape* the collision
143/// (append `_`, Rust's own common idiom for this - `type_`, `match_`, and
144/// so on) rather than reject the name outright. Used by
145/// `blade::expr::translate`'s PHP-variable-name translation, where
146/// rejecting a keyword-shaped variable (`$type`, `$loop`, ...) would flag
147/// the whole containing expression as unsupported for no good reason -
148/// the escaped form is exactly as usable as any other identifier.
149pub(crate) fn is_rust_keyword(name: &str) -> bool {
150    let snake = to_snake_case(name);
151    RUST_KEYWORDS.iter().any(|kw| *kw == name || *kw == snake)
152}
153
154/// Rejects names that aren't valid Rust identifiers, that collide with a
155/// Rust keyword, or that look like one of this file's own `__NAME__`-style
156/// template placeholders - before they get interpolated into generated
157/// source. Fail fast rather than emit unparseable (or, worse, silently
158/// cross-substituted) code.
159pub fn validate_identifier(name: &str) -> Result<()> {
160    let mut chars = name.chars();
161    let starts_ok = matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_');
162    let rest_ok = chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
163    anyhow::ensure!(
164        starts_ok && rest_ok,
165        "invalid name `{name}`: must be a valid Rust identifier (letters, digits, underscore; can't start with a digit)"
166    );
167    anyhow::ensure!(
168        !(name.starts_with("__") && name.ends_with("__")),
169        "invalid name `{name}`: names shaped like `__WORD__` collide with this generator's own template placeholders"
170    );
171
172    let snake = to_snake_case(name);
173    if let Some(keyword) = RUST_KEYWORDS
174        .iter()
175        .find(|kw| **kw == name || **kw == snake)
176    {
177        anyhow::bail!(
178            "invalid name `{name}`: `{keyword}` is a Rust keyword and can't be used as a generated identifier"
179        );
180    }
181
182    Ok(())
183}
184
185/// `Post` -> `"post"`, `BlogPost` -> `"blog_post"`.
186pub fn to_snake_case(name: &str) -> String {
187    let mut result = String::with_capacity(name.len() + 4);
188    for (i, c) in name.chars().enumerate() {
189        if c.is_uppercase() {
190            if i != 0 {
191                result.push('_');
192            }
193            result.extend(c.to_lowercase());
194        } else {
195            result.push(c);
196        }
197    }
198    result
199}
200
201/// A deliberately simple heuristic (not a full English pluralization
202/// engine) covering the common cases: `post` -> `posts`, `category` ->
203/// `categories`, `box` -> `boxes`. Good enough for a default table name;
204/// nothing stops a developer from editing `#[table("...")]` by hand for
205/// words this doesn't handle correctly.
206pub fn pluralize(word: &str) -> String {
207    // "y" preceded by a vowel (day -> days) pluralizes as a plain "s";
208    // "y" preceded by a consonant (category -> categories) becomes "ies".
209    let preceded_by_vowel = word
210        .len()
211        .checked_sub(2)
212        .and_then(|i| word.as_bytes().get(i))
213        .is_some_and(|b| matches!(b, b'a' | b'e' | b'i' | b'o' | b'u'));
214    if word.ends_with('y') && !preceded_by_vowel {
215        format!("{}ies", &word[..word.len() - 1])
216    } else if word.ends_with("ss")
217        || word.ends_with('x')
218        || word.ends_with('z')
219        || word.ends_with("ch")
220        || word.ends_with("sh")
221    {
222        format!("{word}es")
223    } else if word.ends_with('s') {
224        // A bare single trailing "s" (not "ss") is ambiguous between a
225        // genuine singular noun needing "-es" (`bus`, `status`) and a
226        // word that's *already* plural - but real Laravel source hits
227        // the second case far more often here: this only ever runs on
228        // a model's own class name or an FK column's `_id`-stripped
229        // stem, and Eloquent model classes are occasionally named in
230        // plural form directly (real source: `App\Models\Blogs`,
231        // `App\Models\Terms`, both with no explicit `$table` property).
232        // The old unconditional "+es" rule turned those into
233        // `blogses`/`termses` - silently wrong table names nothing else
234        // catches, since there's no migration to cross-check against
235        // (see `models/mod.rs`'s own "no migration creates table ..."
236        // manual-review note). Treated as idempotent instead, matching
237        // Laravel's real `Str::plural`'s behavior for already-plural
238        // input - the tradeoff is a genuine singular word ending in a
239        // bare "s" (`bus`, `status`) is now left unpluralized, same
240        // "verify by hand" expectation this whole heuristic already
241        // carries for words it doesn't handle correctly.
242        word.to_string()
243    } else {
244        format!("{word}s")
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    #[test]
253    fn validate_identifier_accepts_pascal_case() {
254        assert!(validate_identifier("PostController").is_ok());
255        assert!(validate_identifier("_Leading").is_ok());
256    }
257
258    #[test]
259    fn validate_identifier_rejects_invalid_names() {
260        assert!(validate_identifier("").is_err());
261        assert!(validate_identifier("Foo Bar").is_err());
262        assert!(validate_identifier("123Foo").is_err());
263        assert!(validate_identifier("Foo-Bar").is_err());
264    }
265
266    #[test]
267    fn validate_identifier_rejects_keywords_used_directly() {
268        assert!(validate_identifier("type").is_err());
269        assert!(validate_identifier("self").is_err());
270        assert!(validate_identifier("Self").is_err());
271    }
272
273    #[test]
274    fn validate_identifier_rejects_names_that_snake_case_into_a_keyword() {
275        assert!(validate_identifier("Type").is_err());
276        assert!(validate_identifier("Move").is_err());
277        assert!(validate_identifier("Use").is_err());
278    }
279
280    #[test]
281    fn validate_identifier_rejects_names_shaped_like_a_template_placeholder() {
282        assert!(validate_identifier("__NAME__").is_err());
283        assert!(validate_identifier("__USER__").is_err());
284    }
285
286    #[test]
287    fn to_snake_case_converts_pascal_case() {
288        assert_eq!(to_snake_case("PostController"), "post_controller");
289        assert_eq!(to_snake_case("Post"), "post");
290    }
291
292    #[test]
293    fn pluralize_handles_common_cases() {
294        assert_eq!(pluralize("post"), "posts");
295        assert_eq!(pluralize("category"), "categories");
296        assert_eq!(pluralize("box"), "boxes");
297        assert_eq!(pluralize("class"), "classes");
298        assert_eq!(pluralize("day"), "days");
299    }
300
301    #[test]
302    fn pluralize_treats_a_word_already_ending_in_a_bare_s_as_already_plural() {
303        // Real source: `App\Models\Blogs` and `App\Models\Terms`, both
304        // with no explicit `$table` property - the old unconditional
305        // "ends with s -> add es" rule produced `blogses`/`termses`,
306        // silently wrong table names with no migration to cross-check
307        // against. The tradeoff: a genuine singular noun ending in a
308        // bare "s" (`bus`, `status`) is no longer pluralized either -
309        // not observed in any real source this converter has run
310        // against, unlike the already-plural case.
311        assert_eq!(pluralize("blogs"), "blogs");
312        assert_eq!(pluralize("terms"), "terms");
313        assert_eq!(pluralize("bus"), "bus");
314    }
315
316    #[test]
317    fn generate_file_cleans_up_orphaned_rs_file_if_mod_rs_write_fails() {
318        let tmp = tempfile::tempdir().unwrap();
319        let dir = tmp.path();
320        let mod_path = dir.join("mod.rs");
321        std::fs::write(&mod_path, "").unwrap();
322
323        let original_perms = std::fs::metadata(&mod_path).unwrap().permissions();
324        let mut readonly_perms = original_perms.clone();
325        readonly_perms.set_readonly(true);
326        std::fs::set_permissions(&mod_path, readonly_perms).unwrap();
327
328        let result = generate_file(dir, "thing", "widget", "pub struct Thing;\n", Some("Thing"));
329
330        std::fs::set_permissions(&mod_path, original_perms).unwrap();
331
332        assert!(result.is_err());
333        assert!(
334            !dir.join("thing.rs").exists(),
335            "orphaned .rs file should be cleaned up when registering it in mod.rs fails"
336        );
337    }
338
339    #[test]
340    fn generate_nested_file_creates_every_intermediate_directory_and_mod_rs() {
341        let tmp = tempfile::tempdir().unwrap();
342        let root = tmp.path();
343        std::fs::write(root.join("mod.rs"), "").unwrap();
344
345        generate_nested_file(
346            root,
347            &["pages".to_string(), "webservices".to_string()],
348            "compare",
349            "widget",
350            "pub struct Compare;\n",
351            Some("Compare"),
352        )
353        .unwrap();
354
355        assert!(root.join("pages/webservices/compare.rs").exists());
356        assert_eq!(
357            std::fs::read_to_string(root.join("mod.rs")).unwrap(),
358            "pub mod pages;\n"
359        );
360        assert_eq!(
361            std::fs::read_to_string(root.join("pages/mod.rs")).unwrap(),
362            "pub mod webservices;\n"
363        );
364        let leaf_mod = std::fs::read_to_string(root.join("pages/webservices/mod.rs")).unwrap();
365        assert!(leaf_mod.contains("pub mod compare;"));
366        assert!(leaf_mod.contains("pub use compare::Compare;"));
367    }
368
369    #[test]
370    fn generate_nested_file_with_no_segments_behaves_like_generate_file() {
371        let tmp = tempfile::tempdir().unwrap();
372        let root = tmp.path();
373        std::fs::write(root.join("mod.rs"), "").unwrap();
374
375        generate_nested_file(
376            root,
377            &[],
378            "home",
379            "widget",
380            "pub struct Home;\n",
381            Some("Home"),
382        )
383        .unwrap();
384
385        assert!(root.join("home.rs").exists());
386        let mod_rs = std::fs::read_to_string(root.join("mod.rs")).unwrap();
387        assert!(mod_rs.contains("pub mod home;"));
388    }
389
390    #[test]
391    fn generate_nested_file_is_idempotent_across_siblings_sharing_a_directory() {
392        let tmp = tempfile::tempdir().unwrap();
393        let root = tmp.path();
394        std::fs::write(root.join("mod.rs"), "").unwrap();
395
396        generate_nested_file(
397            root,
398            &["pages".to_string()],
399            "blog",
400            "widget",
401            "pub struct Blog;\n",
402            Some("Blog"),
403        )
404        .unwrap();
405        generate_nested_file(
406            root,
407            &["pages".to_string()],
408            "about",
409            "widget",
410            "pub struct About;\n",
411            Some("About"),
412        )
413        .unwrap();
414
415        // `pages` should only be declared once in the root `mod.rs`, even
416        // though two siblings both triggered the same intermediate-
417        // directory wiring step.
418        let mod_rs = std::fs::read_to_string(root.join("mod.rs")).unwrap();
419        assert_eq!(mod_rs.matches("pub mod pages;").count(), 1);
420        let pages_mod = std::fs::read_to_string(root.join("pages/mod.rs")).unwrap();
421        assert!(pages_mod.contains("pub mod blog;"));
422        assert!(pages_mod.contains("pub mod about;"));
423    }
424}