laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
//! Inside each internal crate, the modules form layers: a module names only the modules below it.
//! A reader can then learn a crate from the bottom up, and a change to one module can only break
//! the modules above it.
//!
//! When a method of a low type needs a higher module, define the method in the higher module, in
//! its own `impl` block. `Redirect::back` reads the session, so `session/redirect.rs` defines it.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use regex::Regex;

/// Each crate in `crates/`, with the layers of its modules, lowest first. A module may name the
/// modules of the layers before its own, and the other modules of its own layer.
///
/// Give each module a layer of its own. The one shared layer is the kernel of `core`: the
/// [`Context`](laravel::context::Context) carries the application's configuration, container,
/// clock, and encrypter, and the helpers of those modules read the context they run in, so they
/// are one design.
const LAYERS: &[(&str, &[&[&str]])] = &[
    (
        "core",
        &[
            &["str"],
            &["type_map"],
            &["embed"],
            &["numeric"],
            &["stream"],
            &["html"],
            &["http"],
            &["mail"],
            &["notification"],
            &["tls"],
            &["foundation"],
            &["auth"],
            &["validation"],
            &["testing"],
            &[
                "clock",
                "config",
                "container",
                "context",
                "cookie",
                "crypt",
                "db",
                "error",
                "errors",
                "hash",
                "lottery",
                "time",
            ],
            &["task"],
            &["event"],
        ],
    ),
    ("redis", &[&["redis"]]),
    ("reverb", &[&["reverb"]]),
    ("cache", &[&["cache"], &["rate_limit"]]),
    ("client", &[&["http"]]),
    ("console", &[&["console"]]),
    ("database", &[&["db"], &["pagination"], &["model"], &["crypt"]]),
    (
        "http",
        &[
            &["http"],
            &["cookie"],
            &["head"],
            &["routing"],
            &["url"],
            &["session"],
            &["view"],
            &["storage"],
            &["errors"],
            &["validation"],
            &["auth"],
            &["broadcast"],
            &["inertia"],
            &["defaults"],
        ],
    ),
    ("queue", &[&["queue"]]),
    ("events", &[&["broadcast"], &["event"]]),
    ("feature", &[&["feature"]]),
    ("notifications", &[&["mail"], &["sms"], &["slack"], &["notification"]]),
    ("schedule", &[&["process"], &["schedule"]]),
    ("search", &[&["search"]]),
    ("workflow", &[&["workflow"]]),
];

#[test]
fn a_module_names_only_the_modules_below_it() {
    let crates = Path::new(env!("CARGO_MANIFEST_DIR")).join("crates");
    let mut problems = Vec::new();

    for (name, layers) in LAYERS {
        let source = crates.join(name).join("src");
        let layer_of: BTreeMap<&str, usize> = layers
            .iter()
            .enumerate()
            .flat_map(|(layer, modules)| modules.iter().map(move |module| (*module, layer)))
            .collect();

        for file in rust_files(&source) {
            let module = module_path(&file, &source);
            let Some(from) = module.first() else {
                continue;
            };
            let Some(layer) = layer_of.get(from.as_str()) else {
                problems.push(format!("add the module `{from}` of `crates/{name}` to `LAYERS`"));
                continue;
            };

            let code = code_of(&std::fs::read_to_string(&file).expect("a source file"));
            for (line, to) in named_modules(&code, module.len()) {
                if layer_of.get(to.as_str()).is_some_and(|named| named > layer) {
                    problems.push(format!(
                        "{}:{line}: `{from}` names `{to}`, a module above it. Define this code in `{to}`, or move \
                         what it needs below `{from}`",
                        file.strip_prefix(env!("CARGO_MANIFEST_DIR"))
                            .expect("a file in the repository")
                            .display()
                    ));
                }
            }
        }
    }
    for entry in std::fs::read_dir(&crates).expect("the `crates` directory") {
        let name = entry.expect("a crate's directory").file_name();
        if !LAYERS.iter().any(|(listed, _)| *listed == name) {
            problems.push(format!(
                "add `crates/{}` and its modules to `LAYERS`",
                name.to_string_lossy()
            ));
        }
    }
    problems.sort();
    problems.dedup();

    assert!(problems.is_empty(), "{}", problems.join("\n"));
}

/// The crate's source files, without its tests.
fn rust_files(directory: &Path) -> Vec<PathBuf> {
    let mut files = Vec::new();
    for entry in std::fs::read_dir(directory).expect("a source directory") {
        let path = entry.expect("a directory entry").path();
        let name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default();
        if path.is_dir() {
            if name != "tests" {
                files.extend(rust_files(&path));
            }
        } else if name.ends_with(".rs") && name != "tests.rs" && !name.ends_with("_tests.rs") {
            files.push(path);
        }
    }

    files
}

/// The module a file holds, as its path from the crate's root: `[]` for `lib.rs`, and
/// `["session", "store"]` for `session/store.rs` and for `session/store/mod.rs`.
fn module_path(file: &Path, source: &Path) -> Vec<String> {
    let mut path: Vec<String> = file
        .strip_prefix(source)
        .expect("a file of the crate")
        .with_extension("")
        .iter()
        .map(|segment| segment.to_string_lossy().into_owned())
        .collect();
    if matches!(path.last().map(String::as_str), Some("mod" | "lib")) {
        path.pop();
    }

    path
}

/// The top-level modules of the crate that the code of a module `depth` levels deep names, each
/// with its line: the first segment after `crate::`, after the crate's own name `laravel::`, and
/// after as many `super::` as lead out of the module's top-level module.
fn named_modules(code: &str, depth: usize) -> Vec<(usize, String)> {
    static ROOT: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"\b(crate|laravel|super(?:::super)*)::").expect("a valid pattern"));
    static NAME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_]*").expect("a valid pattern"));

    let mut named = Vec::new();
    for root in ROOT.captures_iter(code) {
        let whole = root.get(0).expect("the match");
        let root = &root[1];
        if root.starts_with("super") && root.split("::").count() != depth {
            continue;
        }

        let line = code[..whole.start()].matches('\n').count() + 1;
        let rest = &code[whole.end()..];
        let paths = match rest.strip_prefix('{') {
            Some(group) => top_level_items(group),
            None => vec![rest],
        };
        for path in paths {
            if let Some(name) = NAME.find(path.trim_start()) {
                named.push((line, name.as_str().to_owned()));
            }
        }
    }

    named
}

/// The items of a `use` group, whose text starts after the group's `{`. Items of nested groups
/// belong to the item that holds them.
fn top_level_items(group: &str) -> Vec<&str> {
    let (mut items, mut depth, mut start) = (Vec::new(), 0_usize, 0);
    for (index, character) in group.char_indices() {
        match character {
            '{' => depth += 1,
            '}' if depth == 0 => {
                items.push(&group[start..index]);
                break;
            }
            '}' => depth -= 1,
            ',' if depth == 0 => {
                items.push(&group[start..index]);
                start = index + 1;
            }
            _ => {}
        }
    }

    items
}

/// The file's code outside its unit tests, with comments and the contents of string and character
/// literals blanked, so a path in a message or a doc link isn't read as code. Lines keep their
/// numbers.
fn code_of(source: &str) -> String {
    static TESTS: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"(?m)^#\[cfg\(test\)\]\s*\n(?:pub(?:\(crate\))? )?mod \w+ \{").expect("a valid pattern")
    });
    let source = TESTS.find(source).map_or(source, |tests| &source[..tests.start()]);

    let characters: Vec<char> = source.chars().collect();
    let mut code = String::with_capacity(source.len());
    let blank = |code: &mut String, characters: &[char]| {
        code.extend(
            characters
                .iter()
                .map(|character| if *character == '\n' { '\n' } else { ' ' }),
        );
    };

    let mut at = 0;
    while at < characters.len() {
        let rest = &characters[at..];
        let end = match rest {
            ['/', '/', ..] => rest
                .iter()
                .position(|character| *character == '\n')
                .unwrap_or(rest.len()),
            ['/', '*', ..] => block_comment_end(rest),
            ['r', '"' | '#', ..] if !is_name_end(characters.get(at.wrapping_sub(1))) => {
                raw_string_end(rest).unwrap_or(0)
            }
            ['"', ..] => string_end(rest),
            ['\'', '\\', ..] => rest[2..]
                .iter()
                .position(|character| *character == '\'')
                .map_or(rest.len(), |end| end + 3),
            ['\'', _, '\'', ..] => 3,
            _ => 0,
        };

        if end == 0 {
            code.push(rest[0]);
            at += 1;
        } else {
            blank(&mut code, &rest[..end]);
            at += end;
        }
    }

    code
}

fn is_name_end(character: Option<&char>) -> bool {
    character.is_some_and(|character| character.is_alphanumeric() || *character == '_')
}

fn block_comment_end(rest: &[char]) -> usize {
    let mut depth = 0_usize;
    let mut at = 0;
    while at + 1 < rest.len() {
        match (rest[at], rest[at + 1]) {
            ('/', '*') => {
                depth += 1;
                at += 2;
            }
            ('*', '/') => {
                depth -= 1;
                at += 2;
                if depth == 0 {
                    return at;
                }
            }
            _ => at += 1,
        }
    }

    rest.len()
}

fn string_end(rest: &[char]) -> usize {
    let mut at = 1;
    while at < rest.len() {
        match rest[at] {
            '\\' => at += 2,
            '"' => return at + 1,
            _ => at += 1,
        }
    }

    rest.len()
}

/// Where a raw string that starts `rest` ends, or `None` when `rest` starts with a name such as
/// `r#type` instead.
fn raw_string_end(rest: &[char]) -> Option<usize> {
    let hashes = rest[1..].iter().take_while(|character| **character == '#').count();
    if rest.get(1 + hashes) != Some(&'"') {
        return None;
    }

    let body = 2 + hashes;
    let end = (body..rest.len()).find(|at| {
        rest[*at] == '"'
            && rest[at + 1..]
                .iter()
                .take(hashes)
                .filter(|character| **character == '#')
                .count()
                == hashes
    });

    Some(end.map_or(rest.len(), |end| end + 1 + hashes))
}