plut-core 2.10.0

Project model, run context and diagnostics for Plut
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::process::Command;

use crate::sourcemap::{self, Instance};
use crate::{Config, Error, Model, RunContext, generated, index, project_file};

/// A package manager dependency, used by the ecosystem rules.
#[derive(Debug, Clone)]
pub struct Dependency {
    pub name: String,
    pub version: Option<String>,
}

/// What a source file is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
    Luau,
    Blink,
}

/// A Luau path alias from `.luaurc`, such as `@game` pointing at `src`.
#[derive(Debug, Clone)]
pub struct Alias {
    /// The alias without its leading `@`, for example `game`.
    pub name: String,
    /// Absolute directory the alias stands for.
    pub path: PathBuf,
}

/// A source file, mapped onto the project model.
#[derive(Debug, Clone)]
pub struct SourceFile {
    pub path: PathBuf,
    pub relative: PathBuf,
    pub kind: FileKind,
    /// Instance path in the sourcemap, such as `ServerScriptService/Admin`.
    pub instance_path: String,
    pub class_name: String,
    pub run_context: RunContext,
}

/// Where the project model came from. Printed under `--verbose` so a wrong context is
/// diagnosable in one line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModelSource {
    Given(PathBuf),
    Existing(PathBuf),
    Generated(PathBuf),
    ProjectFile(PathBuf),
    Suffixes,
    /// A plain Luau tree with no engine model. Context comes from filename suffixes only.
    Plain,
    /// The open place in Roblox Studio, read through its MCP server.
    Studio,
    /// A `.rbxl` or `.rbxlx` place read directly.
    Place,
}

impl ModelSource {
    /// A human-readable description for `--verbose`.
    #[must_use]
    pub fn describe(&self) -> String {
        match self {
            Self::Given(path) => format!("given ({})", path.display()),
            Self::Existing(path) => format!("existing ({})", path.display()),
            Self::Generated(path) => format!("generated with rojo ({})", path.display()),
            Self::ProjectFile(path) => format!("project file ({})", path.display()),
            Self::Suffixes => "filename suffixes only".to_owned(),
            Self::Plain => "plain Luau tree".to_owned(),
            Self::Studio => "Roblox Studio (MCP)".to_owned(),
            Self::Place => "Roblox place file".to_owned(),
        }
    }
}

/// A Rojo project, indexed and ready for rules.
#[derive(Debug)]
pub struct Project {
    pub root: PathBuf,
    pub files: Vec<SourceFile>,
    /// Files skipped because they declare themselves generated.
    pub generated: usize,
    pub dependencies: Vec<Dependency>,
    /// Luau path aliases from `.luaurc`.
    pub aliases: Vec<Alias>,
    pub model: ModelSource,
    /// Non-fatal problems worth telling the user about, such as a failed `rojo sourcemap`.
    pub notes: Vec<String>,
}

impl Project {
    /// Load a project: acquire the model, walk the tree, resolve run context.
    pub fn load(
        root: &Path,
        config: &Config,
        explicit_sourcemap: Option<&Path>,
        generate: bool,
    ) -> Result<Self, Error> {
        let project_files = find_project_files(root);
        let mut notes = Vec::new();
        let (instances, model) = load_model(
            root,
            config,
            explicit_sourcemap,
            generate,
            &project_files,
            &mut notes,
        )?;

        let mut by_file: HashMap<PathBuf, (String, String)> = HashMap::new();
        for instance in &instances {
            for file in &instance.file_paths {
                by_file
                    .entry(normalize(file))
                    .or_insert_with(|| (instance.path.clone(), instance.class_name.clone()));
            }
        }

        let discovered = index::walk(root, config)?;
        let mut files = Vec::with_capacity(discovered.len());

        let allow_path_guessing = model != ModelSource::Plain;
        for file in discovered {
            let key = normalize(&file.relative);
            let (instance_path, class_name) = by_file.get(&key).cloned().unwrap_or_default();
            let run_context =
                RunContext::resolve_in(&file.relative, &instance_path, allow_path_guessing);

            let kind =
                if file.relative.extension().and_then(|value| value.to_str()) == Some("blink") {
                    FileKind::Blink
                } else {
                    FileKind::Luau
                };

            files.push(SourceFile {
                path: file.absolute,
                relative: file.relative,
                kind,
                instance_path,
                class_name,
                run_context,
            });
        }

        let luau = files
            .iter()
            .filter(|file| file.kind == FileKind::Luau)
            .count();
        let unknown = files
            .iter()
            .filter(|file| file.kind == FileKind::Luau && file.run_context == RunContext::Unknown)
            .count();
        if model != ModelSource::Plain && unknown * 2 > luau {
            notes.push(format!(
                "{unknown} of {luau} files have no run context; check the Rojo project file or pass --sourcemap"
            ));
        }
        if model == ModelSource::Plain {
            notes.push(
                "plain model: run context comes from filename suffixes only (for example .server.luau)"
                    .to_owned(),
            );
        }

        let (generated, files): (Vec<_>, Vec<_>) = files
            .into_iter()
            .partition(|file| generated::is_generated(&file.path));
        if !generated.is_empty() {
            notes.push(format!(
                "{} generated files were not analyzed",
                generated.len()
            ));
        }

        Ok(Self {
            root: root.to_path_buf(),
            files,
            generated: generated.len(),
            dependencies: read_dependencies(root, &mut notes),
            aliases: read_aliases(root, &mut notes),
            model,
            notes,
        })
    }

    /// Count files per run context, in the order server, client, shared, unknown.
    #[must_use]
    pub fn context_counts(&self) -> [usize; 4] {
        let mut counts = [0; 4];
        for file in &self.files {
            let index = match file.run_context {
                RunContext::Server => 0,
                RunContext::Client => 1,
                RunContext::Shared => 2,
                RunContext::Unknown => 3,
            };
            counts[index] += 1;
        }
        counts
    }
}

fn load_model(
    root: &Path,
    config: &Config,
    explicit_sourcemap: Option<&Path>,
    generate: bool,
    project_files: &[PathBuf],
    notes: &mut Vec<String>,
) -> Result<(Vec<Instance>, ModelSource), Error> {
    if config.project.model == Model::Plain {
        if explicit_sourcemap.is_some() || config.project.sourcemap != "auto" {
            notes.push("plain model: the configured sourcemap is ignored".to_owned());
        }
        return Ok((Vec::new(), ModelSource::Plain));
    }

    if let Some(path) = explicit_sourcemap {
        return Ok((
            sourcemap::load(path)?,
            ModelSource::Given(path.to_path_buf()),
        ));
    }

    if config.project.sourcemap != "auto" {
        let path = root.join(&config.project.sourcemap);
        return Ok((sourcemap::load(&path)?, ModelSource::Given(path)));
    }

    // Generation comes before a checked-in `sourcemap.json`: that file is frequently stale
    // or built from a different project file in the same repository, and trusting it maps
    // files to the wrong instances.
    // A repository can hold several places: `default.project.json` for the game and
    // `hub.project.json` for a second one. Every project contributes, and the first
    // mapping of a file wins, so the default project has priority.
    if generate && !project_files.is_empty() {
        match generate_sourcemaps(root, project_files) {
            Ok((instances, path)) => {
                return Ok((instances, ModelSource::Generated(path)));
            }
            Err(error) => {
                notes.push(format!("rojo sourcemap failed, falling back: {error}"));
            }
        }
    }

    let existing = root.join("sourcemap.json");
    if existing.is_file() {
        return Ok((sourcemap::load(&existing)?, ModelSource::Existing(existing)));
    }

    if let Some(first) = project_files.first() {
        let mut merged = Vec::new();
        for project in project_files {
            merged.extend(project_file::instances(project)?);
        }
        return Ok((merged, ModelSource::ProjectFile(first.clone())));
    }

    if config.project.model == Model::Auto {
        Ok((Vec::new(), ModelSource::Plain))
    } else {
        Ok((Vec::new(), ModelSource::Suffixes))
    }
}

fn generate_sourcemaps(
    root: &Path,
    project_files: &[PathBuf],
) -> Result<(Vec<Instance>, PathBuf), Error> {
    let mut merged = Vec::new();
    let mut first = None;

    for project in project_files {
        let path = generate_sourcemap(root, project)?;
        merged.extend(sourcemap::load(&path)?);
        if first.is_none() {
            first = Some(path);
        }
    }

    first.map_or_else(
        || Err(Error::NoProject(root.to_path_buf())),
        |path| Ok((merged, path)),
    )
}

/// Find every Rojo project in the root: `default.project.json` first, then the rest.
#[must_use]
pub fn find_project_files(root: &Path) -> Vec<PathBuf> {
    let default = root.join("default.project.json");
    let mut candidates = Vec::new();

    if default.is_file() {
        candidates.push(default.clone());
    }

    let Ok(entries) = std::fs::read_dir(root) else {
        return candidates;
    };

    let mut others: Vec<PathBuf> = entries
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| {
            path.file_name()
                .and_then(|name| name.to_str())
                .is_some_and(|name| name.ends_with(".project.json"))
        })
        .filter(|path| *path != default)
        .collect();

    others.sort();
    candidates.extend(others);
    candidates
}

fn generate_sourcemap(root: &Path, project: &Path) -> Result<PathBuf, Error> {
    let cache = root.join(".plut");
    std::fs::create_dir_all(&cache).map_err(|source| Error::Write {
        path: cache.clone(),
        source,
    })?;

    let stem = project
        .file_stem()
        .and_then(|name| name.to_str())
        .unwrap_or("project");
    let output = cache.join(format!("{stem}.sourcemap.json"));
    let result = Command::new("rojo")
        .arg("sourcemap")
        .arg(project)
        .arg("--output")
        .arg(&output)
        .current_dir(root)
        .output()
        .map_err(Error::Rojo)?;

    if !result.status.success() {
        return Err(Error::RojoFailed {
            code: result.status.code().unwrap_or(-1),
            stderr: String::from_utf8_lossy(&result.stderr).trim().to_owned(),
        });
    }

    Ok(output)
}

fn normalize(path: &Path) -> PathBuf {
    path.components()
        .filter(|component| !matches!(component, Component::CurDir))
        .collect()
}

fn read_aliases(root: &Path, notes: &mut Vec<String>) -> Vec<Alias> {
    let path = root.join(".luaurc");
    if !path.is_file() {
        return Vec::new();
    }

    let text = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(error) => {
            notes.push(format!(".luaurc could not be read: {error}"));
            return Vec::new();
        }
    };

    // `.luaurc` is JSON with comments in some editors' versions. The Luau tooling writes
    // plain JSON, so a strict parse is enough; a broken file only costs alias resolution.
    let value: serde_json::Value = match serde_json::from_str(&text) {
        Ok(value) => value,
        Err(error) => {
            notes.push(format!(".luaurc could not be parsed: {error}"));
            return Vec::new();
        }
    };

    let Some(aliases) = value.get("aliases").and_then(serde_json::Value::as_object) else {
        return Vec::new();
    };

    let mut out = Vec::new();
    for (name, target) in aliases {
        let Some(target) = target.as_str() else {
            continue;
        };

        let target = target.strip_prefix('~').map_or_else(
            || PathBuf::from(target),
            |rest| {
                std::env::var_os("HOME").map_or_else(
                    || PathBuf::from(target),
                    |home| PathBuf::from(home).join(rest.trim_start_matches('/')),
                )
            },
        );
        let target = if target.is_absolute() {
            target
        } else {
            root.join(target)
        };

        out.push(Alias {
            name: name.trim_start_matches('@').to_owned(),
            path: normalize(&target),
        });
    }

    out.sort_by(|left, right| left.name.cmp(&right.name));
    out
}

fn read_dependencies(root: &Path, notes: &mut Vec<String>) -> Vec<Dependency> {
    let mut out = Vec::new();

    for manifest in ["pesde.toml", "wally.toml"] {
        let path = root.join(manifest);
        if !path.is_file() {
            continue;
        }

        let text = match std::fs::read_to_string(&path) {
            Ok(text) => text,
            Err(error) => {
                notes.push(format!("{manifest} could not be read: {error}"));
                continue;
            }
        };

        let value: toml::Value = match toml::from_str(&text) {
            Ok(value) => value,
            Err(error) => {
                notes.push(format!("{manifest} could not be parsed: {error}"));
                continue;
            }
        };

        let Some(dependencies) = value.get("dependencies").and_then(toml::Value::as_table) else {
            continue;
        };

        for (name, entry) in dependencies {
            // pesde maps an alias to a package: `KeepBlox = { name = "xopoiii/keepblox" }`.
            let package = entry
                .get("name")
                .and_then(toml::Value::as_str)
                .map_or_else(|| name.clone(), ToOwned::to_owned);

            let version = entry.as_str().map(ToOwned::to_owned).or_else(|| {
                entry
                    .get("version")
                    .and_then(toml::Value::as_str)
                    .map(ToOwned::to_owned)
            });

            out.push(Dependency {
                name: package,
                version,
            });
        }
    }

    out.sort_by(|left, right| left.name.cmp(&right.name));
    out.dedup_by(|left, right| left.name == right.name);
    out
}