plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
4164644
— Peter John
2026-11-10T23:12:38+05:30
plum format: keep a string's text and a trailing comment's place
Generated files not shown: Cargo.lock
compiler/cli/Cargo.toml
CHANGED
|
@@ -10,13 +10,10 @@ path = "src/main.rs"
|
|
|
10
10
|
|
|
11
11
|
[dependencies]
|
|
12
12
|
plum-core = { path = "../core" }
|
|
13
|
-
plum-checker = { path = "../checker" }
|
|
14
13
|
plum-driver = { path = "../driver" }
|
|
15
14
|
plum-wasm-codegen = { path = "../wasm-codegen" }
|
|
16
15
|
clap = { version = "4", features = ["derive"] }
|
|
17
16
|
anyhow = "1"
|
|
18
|
-
tree-sitter = "0.26"
|
|
19
|
-
tree-sitter-plum = { path = "../tooling/tree-sitter-plum" }
|
|
20
17
|
toml_edit = "0.22"
|
|
21
18
|
wasmtime = "47"
|
|
22
19
|
plum-host = { path = "../host" }
|
|
@@ -25,3 +22,6 @@ plum-game = { path = "../game" }
|
|
|
25
22
|
|
|
26
23
|
[dev-dependencies]
|
|
27
24
|
plum-test-support = { path = "../test-support" }
|
|
25
|
+
# tests/cli/format_repo_test.rs reads the tokens of every file it formats.
|
|
26
|
+
tree-sitter = "0.26"
|
|
27
|
+
tree-sitter-plum = { path = "../tooling/tree-sitter-plum" }
|
compiler/cli/tests/cli/format_repo_test.rs
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
//! `plum format` over every Plum file in the repository, in memory (no file is written):
|
|
2
|
+
//! formatting is idempotent and changes only layout. The tokens, string literals as
|
|
3
|
+
//! written and comments come out in the same order, and a trailing comment stays on the
|
|
4
|
+
//! line of the code before it.
|
|
5
|
+
use crate::common::root;
|
|
6
|
+
use std::path::{Path, PathBuf};
|
|
7
|
+
|
|
8
|
+
fn plumFiles(dir: &Path, out: &mut Vec<PathBuf>) {
|
|
9
|
+
for entry in std::fs::read_dir(dir).unwrap() {
|
|
10
|
+
let p = entry.unwrap().path();
|
|
11
|
+
if p.is_dir() {
|
|
12
|
+
plumFiles(&p, out);
|
|
13
|
+
} else if p.extension().is_some_and(|e| e == "plum") {
|
|
14
|
+
out.push(p);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
fn parse(source: &str) -> tree_sitter::Tree {
|
|
20
|
+
let mut parser = tree_sitter::Parser::new();
|
|
21
|
+
parser.set_language(&tree_sitter_plum::LANGUAGE.into()).unwrap();
|
|
22
|
+
parser.parse(source, None).unwrap()
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// The source's tokens in order, whitespace left out, each with the kind of node it is in:
|
|
26
|
+
/// a string literal is one token, as written, and a comment is marked trailing when code
|
|
27
|
+
/// precedes it on its line.
|
|
28
|
+
fn tokens(source: &str) -> Vec<String> {
|
|
29
|
+
let tree = parse(source);
|
|
30
|
+
let mut out = Vec::new();
|
|
31
|
+
let mut lastRow = usize::MAX;
|
|
32
|
+
let mut stack = vec![tree.root_node()];
|
|
33
|
+
while let Some(node) = stack.pop() {
|
|
34
|
+
let atom = node.kind() == "string" || node.kind() == "comment" || node.child_count() == 0;
|
|
35
|
+
if !atom {
|
|
36
|
+
let mut cursor = node.walk();
|
|
37
|
+
let children: Vec<_> = node.children(&mut cursor).collect();
|
|
38
|
+
stack.extend(children.into_iter().rev());
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
let text = &source[node.byte_range()];
|
|
42
|
+
if text.trim().is_empty() {
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
let row = node.start_position().row;
|
|
46
|
+
if node.kind() == "comment" {
|
|
47
|
+
out.push(format!("{}{}", if row == lastRow { "trailing " } else { "" }, text.trim_end()));
|
|
48
|
+
} else {
|
|
49
|
+
// With the parent's kind: `List<Int>` and `List < Int >` are the same text.
|
|
50
|
+
out.push(format!("{} {text}", node.parent().map_or("", |p| p.kind())));
|
|
51
|
+
}
|
|
52
|
+
lastRow = node.end_position().row;
|
|
53
|
+
}
|
|
54
|
+
out
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
#[test]
|
|
58
|
+
fn formattingTheRepositoryChangesOnlyLayout() {
|
|
59
|
+
let root = root();
|
|
60
|
+
let mut files = Vec::new();
|
|
61
|
+
for dir in ["std", "examples", "tests", "benchmarks"] {
|
|
62
|
+
plumFiles(&root.join(dir), &mut files);
|
|
63
|
+
}
|
|
64
|
+
files.sort();
|
|
65
|
+
let jobs = std::thread::available_parallelism().map_or(4, |n| n.get());
|
|
66
|
+
let root = &root;
|
|
67
|
+
let chunks: Vec<&[PathBuf]> = files.chunks(files.len().div_ceil(jobs)).collect();
|
|
68
|
+
let results: Vec<(usize, Vec<String>)> = std::thread::scope(|s| {
|
|
69
|
+
let handles: Vec<_> = chunks
|
|
70
|
+
.iter()
|
|
71
|
+
.map(|chunk| {
|
|
72
|
+
s.spawn(move || {
|
|
73
|
+
let (mut formatted, mut problems) = (0, Vec::new());
|
|
74
|
+
for file in chunk.iter() {
|
|
75
|
+
let name = file.strip_prefix(root).unwrap().display().to_string();
|
|
76
|
+
let source = std::fs::read_to_string(file).unwrap();
|
|
77
|
+
let Ok(once) = plum_core::formatSource(&source) else {
|
|
78
|
+
// Only a file the parser rejects (the old syntax kept for comparison).
|
|
79
|
+
if !parse(&source).root_node().has_error() {
|
|
80
|
+
problems.push(format!("{name}: the formatter fails on a file that parses"));
|
|
81
|
+
}
|
|
82
|
+
continue;
|
|
83
|
+
};
|
|
84
|
+
formatted += 1;
|
|
85
|
+
match plum_core::formatSource(&once) {
|
|
86
|
+
Ok(twice) if twice == once => {}
|
|
87
|
+
Ok(_) => problems.push(format!("{name}: formatting the formatted file changes it again")),
|
|
88
|
+
Err(e) => problems.push(format!("{name}: the formatted file does not parse: {e}")),
|
|
89
|
+
}
|
|
90
|
+
let (before, after) = (tokens(&source), tokens(&once));
|
|
91
|
+
if before != after {
|
|
92
|
+
let at = before.iter().zip(&after).position(|(a, b)| a != b).unwrap_or(before.len().min(after.len()));
|
|
93
|
+
problems.push(format!(
|
|
94
|
+
"{name}: token {at} was {:?}, formatted {:?}",
|
|
95
|
+
before.get(at),
|
|
96
|
+
after.get(at)
|
|
97
|
+
));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
(formatted, problems)
|
|
101
|
+
})
|
|
102
|
+
})
|
|
103
|
+
.collect();
|
|
104
|
+
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
|
105
|
+
});
|
|
106
|
+
let formatted: usize = results.iter().map(|r| r.0).sum();
|
|
107
|
+
let problems: Vec<&String> = results.iter().flat_map(|r| &r.1).collect();
|
|
108
|
+
assert!(problems.is_empty(), "{} problems:\n{}", problems.len(), problems.iter().map(|p| p.as_str()).collect::<Vec<_>>().join("\n"));
|
|
109
|
+
assert!(formatted > 200, "only {formatted} of {} files formatted", files.len());
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// The two ways the formatter damaged std: text between a string's escapes was dropped,
|
|
113
|
+
/// and a trailing comment moved onto the next line.
|
|
114
|
+
#[test]
|
|
115
|
+
fn stringsAndTrailingCommentsAreKept() {
|
|
116
|
+
let source = "import std/Str\n\nfun f(b: Int) -> Str =\n x := \"h\\u00e9<a href=\\\"x\\\">{b} & y\" # one\n y := 2\n # alone\n x # last\n";
|
|
117
|
+
let formatted = plum_core::formatSource(source).unwrap();
|
|
118
|
+
assert_eq!(formatted, source);
|
|
119
|
+
}
|
compiler/cli/tests/cli/main.rs
CHANGED
|
@@ -7,6 +7,7 @@ mod compile_tests;
|
|
|
7
7
|
mod crash_test;
|
|
8
8
|
mod determinism_test;
|
|
9
9
|
mod explain_layout_test;
|
|
10
|
+
mod format_repo_test;
|
|
10
11
|
mod fusion_agree_test;
|
|
11
12
|
mod game_entry_test;
|
|
12
13
|
mod game_web_test;
|
compiler/tooling/tree-sitter-plum/queries/plum/format.scm
CHANGED
|
@@ -222,6 +222,11 @@
|
|
|
222
222
|
|
|
223
223
|
(comment) @prepend_input_softline
|
|
224
224
|
|
|
225
|
+
; A string is printed as written. Its text between escapes and interpolations is a
|
|
226
|
+
; hidden node, which Topiary would drop (`"hé"` became `"é"`), and
|
|
227
|
+
; nothing inside the quotes is layout.
|
|
228
|
+
(string) @leaf
|
|
229
|
+
|
|
225
230
|
; ============================================================
|
|
226
231
|
; Separators — no space before, one space after
|
|
227
232
|
; ============================================================
|
|
@@ -335,8 +340,17 @@
|
|
|
335
340
|
; Function body — each statement on its own line
|
|
336
341
|
; ============================================================
|
|
337
342
|
|
|
343
|
+
; A comment in a body keeps its own placement (`@prepend_input_softline` above):
|
|
344
|
+
; forcing a line break before it would move a trailing comment (`x := 1 # one`)
|
|
345
|
+
; onto the next line, where it reads as the next statement's comment.
|
|
346
|
+
; A body's first child sits after the indent, so a comment there is on its own line.
|
|
347
|
+
(body
|
|
348
|
+
(_) @prepend_hardline
|
|
349
|
+
(#not-match? @prepend_hardline "^#"))
|
|
350
|
+
|
|
338
351
|
(body
|
|
352
|
+
.
|
|
339
|
-
(
|
|
353
|
+
(comment) @prepend_hardline)
|
|
340
354
|
|
|
341
355
|
; ============================================================
|
|
342
356
|
; Indentation — body blocks
|