plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


127ff74 — Peter John 2026-11-10T11:17:18+05:30
One --lib-path default for every tool; plum-lsp: load errors, debounce, versions, UTF-16, go to definition
compiler/cli/src/game.rs CHANGED
@@ -17,14 +17,6 @@ const BRIDGE_JS: &str = include_str!("../../game/web/plum_bridge.js");
17
17
  /// of a `plum build` never mention it.
18
18
  const DEV_JS: &str = include_str!("../../game/web/plum_dev.js");
19
19
 
20
- /// The repository root, fixed when plum-cli is compiled.
21
- pub fn repoRoot() -> PathBuf {
22
- Path::new(env!("CARGO_MANIFEST_DIR"))
23
- .ancestors().nth(2)
24
- .expect("plum-cli lives inside the repository")
25
- .to_path_buf()
26
- }
27
-
28
20
  /// The asset root: `--assets`, else the nearest `assets` directory beside the source file or in
29
21
  /// a parent folder (so games in subfolders share one), else `assets` beside the source file.
30
22
  fn assetRoot(file: &Path, cli: Option<PathBuf>) -> PathBuf {
compiler/cli/src/main.rs CHANGED
@@ -45,9 +45,10 @@ enum Command {
45
45
  /// Output path (default: input with .wasm extension)
46
46
  #[arg(short, long)]
47
47
  output: Option<std::path::PathBuf>,
48
- /// Root directory `import <path>` is resolved against (`import std/x` -> `<lib-path>/std/x.plum`)
48
+ /// Root directory `import <path>` is resolved against (`import std/x` -> `<lib-path>/std/x.plum`;
49
- #[arg(long, default_value = ".")]
49
+ /// default: `.` when it holds `std`, else the repository plum was built from)
50
+ #[arg(long)]
50
- lib_path: std::path::PathBuf,
51
+ lib_path: Option<std::path::PathBuf>,
51
52
  /// No in-place updates: every spread copies and no cell is reused
52
53
  #[arg(long)]
53
54
  no_fbip: bool,
@@ -81,7 +82,7 @@ enum Command {
81
82
  #[arg(long)]
82
83
  replay: Option<std::path::PathBuf>,
83
84
  /// Root directory `import <path>` is resolved against (`import std/x` -> `<lib-path>/std/x.plum`;
84
- /// default: the repository root for a game, `.` otherwise)
85
+ /// default: `.` when it holds `std`, else the repository plum was built from)
85
86
  #[arg(long)]
86
87
  lib_path: Option<std::path::PathBuf>,
87
88
  /// Arguments for the program, after `--` (`plum run app.plum -- a b`): `io.args()`
@@ -107,7 +108,7 @@ enum Command {
107
108
  /// Games: asset root (default: the nearest `assets` folder beside the source or above it); all of it is bundled
108
109
  #[arg(long)]
109
110
  assets: Option<std::path::PathBuf>,
110
- /// Root directory `import <path>` is resolved against (default: the repository root for a game, `.` otherwise)
111
+ /// Root directory `import <path>` is resolved against (default: `.` when it holds `std`, else the repository plum was built from)
111
112
  #[arg(long)]
112
113
  lib_path: Option<std::path::PathBuf>,
113
114
  },
@@ -126,9 +127,10 @@ enum Command {
126
127
  /// No in-place updates: every spread copies and no cell is reused
127
128
  #[arg(long)]
128
129
  no_fbip: bool,
129
- /// Root directory `import <path>` is resolved against (`import std/x` -> `<lib-path>/std/x.plum`)
130
+ /// Root directory `import <path>` is resolved against (`import std/x` -> `<lib-path>/std/x.plum`;
130
- #[arg(long, default_value = ".")]
131
+ /// default: `.` when it holds `std`, else the repository plum was built from)
132
+ #[arg(long)]
131
- lib_path: std::path::PathBuf,
133
+ lib_path: Option<std::path::PathBuf>,
132
134
  /// Seconds one test may run before it fails as timed out (default: `PLUM_TEST_TIMEOUT`, else 60; 0 = no limit)
133
135
  #[arg(long)]
134
136
  timeout: Option<f64>,
@@ -187,7 +189,7 @@ fn run() -> Result<()> {
187
189
  output,
188
190
  lib_path,
189
191
  no_fbip,
190
- } => cmdCompile(file, output, lib_path, no_fbip),
192
+ } => cmdCompile(file, output, libPathOrDefault(lib_path), no_fbip),
191
193
  Command::Run { file, lib_path, explain_fusion, no_fusion, no_fbip, assets, port, no_open, no_watch, replay, args } => {
192
194
  plum_host::setProgramArgs(args);
193
195
  cmdRun(file, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port, noOpen: no_open, noWatch: no_watch, output: None, replay })
@@ -196,7 +198,7 @@ fn run() -> Result<()> {
196
198
  cmdBuild(file, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port: None, noOpen: false, noWatch: false, output, replay: None })
197
199
  }
198
200
  Command::Test { paths, lib_path, explain_fusion, no_fusion, no_fbip, timeout } => {
199
- cmdTest(paths, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), testTimeout(timeout)?)
201
+ cmdTest(paths, libPathOrDefault(lib_path), fusionFlags(explain_fusion, no_fusion, no_fbip), testTimeout(timeout)?)
200
202
  }
201
203
  Command::Editor { editor, insiders } => editor::install(editor, insiders),
202
204
  }
@@ -277,11 +279,10 @@ impl GameOptions {
277
279
  }
278
280
 
279
281
  /// Without `--lib-path`, imports resolve against `.` when it holds a `std` folder (the
280
- /// repository root), else against the repository this `plum` was built from.
282
+ /// repository root), else against the repository this `plum` was built from; `plum-lsp`
283
+ /// uses the same default.
281
284
  fn libPathOrDefault(lib_path: Option<std::path::PathBuf>) -> std::path::PathBuf {
282
- lib_path.unwrap_or_else(|| {
285
+ plum_core::loader::libPathOrDefault(lib_path)
283
- if std::path::Path::new("std").is_dir() { std::path::PathBuf::from(".") } else { game::repoRoot() }
284
- })
285
286
  }
286
287
 
287
288
  fn compileToTestWasm(
compiler/cli/src/replay.rs CHANGED
@@ -46,7 +46,7 @@ mod tests {
46
46
  use super::*;
47
47
 
48
48
  fn exampleWasm(path: &str) -> (Vec<u8>, PathBuf) {
49
- let root = crate::game::repoRoot();
49
+ let root = plum_core::loader::builtRepoRoot();
50
50
  let file = root.join("examples/games").join(path);
51
51
  let wasm = crate::program::compileProgram(&file, &root, plum_driver::PassOptions::default()).unwrap().wasm;
52
52
  (wasm, crate::game::gameAssets(&file, None).unwrap())
compiler/cli/tests/cli/test_scope_test.rs CHANGED
@@ -67,3 +67,16 @@ fn failingImportedTestDoesNotFailImporter() {
67
67
  assert!(ok, "{out}");
68
68
  assert!(out.contains("1 passed, 0 failed"), "{out}");
69
69
  }
70
+
71
+ /// Without `--lib-path`, `plum test` and `plum compile` outside a checkout resolve std
72
+ /// against the repository plum was built from (as `plum run` and `plum-lsp` do).
73
+ #[test]
74
+ fn libPathDefaultsToTheBuiltRepositoryOutsideACheckout() {
75
+ let dir = scratch("nolib");
76
+ std::fs::write(dir.join("a.plum"), TWO).unwrap();
77
+ let out = Command::new(plumBin()).current_dir(&dir).args(["test", "a.plum"]).output().unwrap();
78
+ assert!(out.status.success(), "{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
79
+ let out = Command::new(plumBin()).current_dir(&dir).args(["compile", "a.plum"]).output().unwrap();
80
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
81
+ assert!(dir.join("a.wasm").is_file());
82
+ }
compiler/core/src/loader.rs CHANGED
@@ -783,3 +783,15 @@ fn checkExtends(path: &Path, source: &Source, lib_path: &Path) -> Loaded_<()> {
783
783
  }
784
784
  Ok(())
785
785
  }
786
+
787
+ /// The root `import <path>` resolves against when a tool (`plum`, `plum-lsp`) is given no
788
+ /// `--lib-path`: `.` when it holds a `std` folder (a checkout's root), else the repository
789
+ /// these tools were built from.
790
+ pub fn libPathOrDefault(given: Option<PathBuf>) -> PathBuf {
791
+ given.unwrap_or_else(|| if Path::new("std").is_dir() { PathBuf::from(".") } else { builtRepoRoot() })
792
+ }
793
+
794
+ /// The repository these crates were compiled from.
795
+ pub fn builtRepoRoot() -> PathBuf {
796
+ Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).expect("plum-core lives inside the repository").to_path_buf()
797
+ }
compiler/lsp/Cargo.toml CHANGED
@@ -14,4 +14,4 @@ plum-driver = { path = "../driver" }
14
14
  tree-sitter = "0.26"
15
15
  tree-sitter-plum = { path = "../tooling/tree-sitter-plum" }
16
16
  tower-lsp = "0.20"
17
- tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std"] }
17
+ tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "time"] }
compiler/lsp/src/completion.rs CHANGED
@@ -291,8 +291,8 @@ pub fn sanitizeForParsing(text: &str, pos: Position) -> String {
291
291
 
292
292
  /// If the cursor sits right after `<ident>.<partial>` (or `<ident>.`),
293
293
  /// returns `<ident>`. `line` is just the cursor's own line text, `char_idx`
294
- /// its column treated as a char index (not real UTF-16 offset math — fine
294
+ /// its column as a char index (the caller converts the client's UTF-16 column
295
- /// for the ASCII identifiers this looks for).
295
+ /// with `position::charCol`).
296
296
  pub fn receiverBeforeDot(line: &str, char_idx: usize) -> Option<String> {
297
297
  let chars: Vec<char> = line.chars().collect();
298
298
  let mut i = char_idx.min(chars.len());
compiler/lsp/src/definition.rs ADDED
@@ -0,0 +1,204 @@
1
+ //! Go to definition: top-level functions, types, traits, constants and methods,
2
+ //! in the document or in a file it imports (directly or through other imports).
3
+
4
+ use std::collections::HashSet;
5
+ use std::path::{Path, PathBuf};
6
+
7
+ use plum_core::ast;
8
+ use tower_lsp::lsp_types::{Location, Position, Range, Url};
9
+
10
+ use crate::position;
11
+
12
+ /// What the word under the cursor names.
13
+ #[derive(Debug, PartialEq)]
14
+ enum Target {
15
+ /// A bare name: a function, type, trait or constant.
16
+ Name(String),
17
+ /// `receiver.name`: a method or static (`Type.name`, `value.name`) or a module's member.
18
+ Member { receiver: String, name: String },
19
+ }
20
+
21
+ fn isIdent(c: u8) -> bool {
22
+ c.is_ascii_alphanumeric() || c == b'_'
23
+ }
24
+
25
+ /// The identifier at byte `col` of `line` (or ending there), as (start, end) bytes.
26
+ fn wordAt(line: &str, col: usize) -> Option<(usize, usize)> {
27
+ let b = line.as_bytes();
28
+ let mut col = col.min(b.len());
29
+ if col == b.len() || !isIdent(b[col]) {
30
+ if col > 0 && isIdent(b[col - 1]) {
31
+ col -= 1;
32
+ } else {
33
+ return None;
34
+ }
35
+ }
36
+ let mut s = col;
37
+ while s > 0 && isIdent(b[s - 1]) {
38
+ s -= 1;
39
+ }
40
+ let mut e = col;
41
+ while e < b.len() && isIdent(b[e]) {
42
+ e += 1;
43
+ }
44
+ Some((s, e))
45
+ }
46
+
47
+ fn targetAt(line: &str, col: usize) -> Option<Target> {
48
+ let (s, e) = wordAt(line, col)?;
49
+ let name = line[s..e].to_string();
50
+ if s > 0 && line.as_bytes()[s - 1] == b'.' {
51
+ let (rs, re) = wordAt(line, s - 1).filter(|&(_, re)| re == s - 1).unwrap_or((s - 1, s - 1));
52
+ return Some(Target::Member { receiver: line[rs..re].to_string(), name });
53
+ }
54
+ Some(Target::Name(name))
55
+ }
56
+
57
+ fn parse(text: &str) -> ast::Source {
58
+ let mut parser = tree_sitter::Parser::new();
59
+ parser.set_language(&tree_sitter_plum::LANGUAGE.into()).expect("failed to load plum grammar");
60
+ let tree = parser.parse(text, None).expect("tree-sitter parse returned None");
61
+ plum_core::AstParser::new(text).parseSourceRaw(tree.root_node())
62
+ }
63
+
64
+ /// One parsed file the search looks in.
65
+ struct File {
66
+ path: PathBuf,
67
+ text: String,
68
+ source: ast::Source,
69
+ /// The import path it was reached by (`None` for the document itself).
70
+ importPath: Option<String>,
71
+ }
72
+
73
+ /// The document, then every file it imports, breadth first (each file once).
74
+ fn files(path: &Path, text: &str, libPath: &Path) -> Vec<File> {
75
+ let mut out = vec![File { path: path.to_path_buf(), text: text.to_string(), source: parse(text), importPath: None }];
76
+ let mut seen: HashSet<PathBuf> = HashSet::new();
77
+ seen.insert(std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()));
78
+ let mut i = 0;
79
+ while i < out.len() && out.len() < 1000 {
80
+ let imports: Vec<String> = out[i].source.imports.iter().map(|im| im.path.clone()).collect();
81
+ for imp in imports {
82
+ let p = libPath.join(format!("{imp}.plum"));
83
+ let canon = std::fs::canonicalize(&p).unwrap_or_else(|_| p.clone());
84
+ if !seen.insert(canon.clone()) {
85
+ continue;
86
+ }
87
+ if let Ok(t) = std::fs::read_to_string(&canon) {
88
+ out.push(File { source: parse(&t), path: canon, text: t, importPath: Some(imp) });
89
+ }
90
+ }
91
+ i += 1;
92
+ }
93
+ out
94
+ }
95
+
96
+ /// A 1-based line and byte column in `file` (0 = unknown) as a location.
97
+ fn location(file: &File, line: usize, column: usize) -> Option<Location> {
98
+ let line0 = line.saturating_sub(1);
99
+ let start = position::fromByte(&file.text, line0, column.saturating_sub(1));
100
+ let end = Position::new(line0 as u32, position::utf16Col(position::lineOf(&file.text, line0), usize::MAX));
101
+ Some(Location { uri: Url::from_file_path(&file.path).ok()?, range: Range { start, end: if line == 0 { start } else { end } } })
102
+ }
103
+
104
+ /// Where `name` is declared at the top level of `file`.
105
+ fn topLevel(file: &File, name: &str) -> Option<Location> {
106
+ for item in &file.source.items {
107
+ let at = match item {
108
+ ast::Item::Fn(f) if f.type_param.is_none() && !f.is_test && f.name == name => Some((f.line, f.column)),
109
+ ast::Item::Enum(e) if e.name == name => Some((e.line, e.column)),
110
+ ast::Item::Trait(t) if t.name == name => Some((t.line, t.column)),
111
+ ast::Item::Const(c) if c.name == name => Some((c.line, 0)),
112
+ _ => None,
113
+ };
114
+ if let Some((line, column)) = at {
115
+ return location(file, line, column);
116
+ }
117
+ }
118
+ None
119
+ }
120
+
121
+ /// A method or static `name`; of type `owner` when it is known.
122
+ fn method(file: &File, owner: Option<&str>, name: &str) -> Option<Location> {
123
+ file.source.items.iter().find_map(|item| match item {
124
+ ast::Item::Fn(f) if f.name == name && f.type_param.as_deref().is_some_and(|t| owner.is_none_or(|o| o == t)) => {
125
+ location(file, f.line, f.column)
126
+ }
127
+ _ => None,
128
+ })
129
+ }
130
+
131
+ /// The declaration the word at `pos` of the document `text` (at `path`) names.
132
+ pub fn definitionAt(path: &Path, libPath: &Path, text: &str, pos: Position) -> Option<Location> {
133
+ let line = position::lineOf(text, pos.line as usize);
134
+ let target = targetAt(line, position::byteCol(line, pos.character))?;
135
+ let all = files(path, text, libPath);
136
+ match target {
137
+ Target::Name(name) => all.iter().find_map(|f| topLevel(f, &name)),
138
+ Target::Member { receiver, name } => {
139
+ // `module.name`: a function or constant of that imported module.
140
+ if receiver.starts_with(|c: char| c.is_ascii_lowercase()) {
141
+ if let Some(found) = all
142
+ .iter()
143
+ .filter(|f| f.importPath.as_deref().is_some_and(|p| plum_core::modules::moduleAlias(p) == receiver))
144
+ .find_map(|f| topLevel(f, &name))
145
+ {
146
+ return Some(found);
147
+ }
148
+ }
149
+ // `Type.name`: that type's static or constant; `value.name`: a method of any type.
150
+ let owner = receiver.starts_with(|c: char| c.is_ascii_uppercase()).then_some(receiver.as_str());
151
+ all.iter()
152
+ .find_map(|f| method(f, owner, &name))
153
+ .or_else(|| all.iter().find_map(|f| method(f, None, &name)))
154
+ }
155
+ }
156
+ }
157
+
158
+ #[cfg(test)]
159
+ mod tests {
160
+ use super::*;
161
+
162
+ fn repoRoot() -> PathBuf {
163
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..").canonicalize().unwrap()
164
+ }
165
+
166
+ #[test]
167
+ fn theWordAndItsReceiver() {
168
+ assert_eq!(targetAt(" x := foo(1)", 8), Some(Target::Name("foo".into())));
169
+ assert_eq!(targetAt(" a.len()", 5), Some(Target::Member { receiver: "a".into(), name: "len".into() }));
170
+ assert_eq!(targetAt(" ", 1), None);
171
+ }
172
+
173
+ /// A function, a type and a method of the document; a function of an imported
174
+ /// module; a std method; and a line with non-ASCII text before the name.
175
+ #[test]
176
+ fn findsDeclarationsHereAndInImports() {
177
+ let dir = std::env::temp_dir().join(format!("plum_lsp_def_{}", std::process::id()));
178
+ std::fs::create_dir_all(&dir).unwrap();
179
+ let path = dir.join("t.plum");
180
+ let text = "import std/Int\nimport std/Str\nimport tests/modules/mathx\n\nstruct Ship(x: Int) =\n fun moved(self) -> Ship =\n Ship(x: self.x + 1)\n\nfun helper() -> Int = 1\n\nfun main() -> Int =\n s := Ship(x: helper())\n _ := s.moved()\n _ := \"é😀\".length() + mathx.twice(2)\n 0\n";
181
+ std::fs::write(&path, text).unwrap();
182
+ let at = |line: u32, col: u32| definitionAt(&path, &repoRoot(), text, Position::new(line, col));
183
+ let here = Url::from_file_path(&path).unwrap();
184
+ // `helper` in `Ship(x: helper())`.
185
+ let l = at(11, 16).expect("helper");
186
+ assert_eq!((l.uri.clone(), l.range.start), (here.clone(), Position::new(8, 0)));
187
+ // `Ship` in `s := Ship(`.
188
+ let l = at(11, 8).expect("Ship");
189
+ assert_eq!((l.uri.clone(), l.range.start.line), (here.clone(), 4));
190
+ // `moved` in `s.moved()`.
191
+ let l = at(12, 10).expect("moved");
192
+ assert_eq!((l.uri.clone(), l.range.start), (here, Position::new(5, 2)));
193
+ // `twice` in `mathx.twice(2)`, after "é😀" (3 UTF-16 units, 6 bytes).
194
+ let line = position::lineOf(text, 13);
195
+ let col = position::utf16Col(line, line.find("twice").unwrap());
196
+ let l = at(13, col + 1).expect("twice");
197
+ assert!(l.uri.path().ends_with("tests/modules/mathx.plum"), "{}", l.uri);
198
+ // `length` of Str, in std.
199
+ let col = position::utf16Col(line, line.find("length").unwrap());
200
+ let l = at(13, col).expect("length");
201
+ assert!(l.uri.path().ends_with("std/Str.plum"), "{}", l.uri);
202
+ let _ = std::fs::remove_dir_all(&dir);
203
+ }
204
+ }
compiler/lsp/src/main.rs CHANGED
@@ -8,7 +8,11 @@
8
8
  // diagnostic range spans start to end, falling back to the end of the
9
9
  // start line when the end is unknown.
10
10
  //
11
- // Both are republished on every `did_open`/`did_change`/`did_save`. Type
11
+ // Both are republished on every `did_open`/`did_save`, and on `did_change` once the
12
+ // edits pause (`DEBOUNCE`); the work runs on a blocking thread, a checker panic
13
+ // becomes a diagnostic, and a result for an older version of the text is dropped.
14
+ // Positions are converted between the compiler's bytes and LSP's UTF-16 columns in
15
+ // `position.rs`. Type
12
16
  // checking goes through `plum_core::loadAndMergeWithOverridesDiag`, passing the
13
17
  // live in-memory buffer for the edited document while every other
14
18
  // (transitively imported) file still reads from disk — so it reflects
@@ -23,7 +27,8 @@
23
27
 
24
28
  use std::collections::HashMap;
25
29
  use std::path::{Path, PathBuf};
26
- use std::sync::OnceLock;
30
+ use std::sync::{Arc, OnceLock};
31
+ use std::time::Duration;
27
32
 
28
33
  use tokio::sync::Mutex;
29
34
  use tower_lsp::jsonrpc::Result as RpcResult;
@@ -31,12 +36,25 @@ use tower_lsp::lsp_types::*;
31
36
  use tower_lsp::{Client, LanguageServer, LspService, Server};
32
37
 
33
38
  mod completion;
39
+ mod definition;
40
+ mod position;
34
41
 
35
42
  use plum_core::ast;
36
43
 
44
+ /// An open document: its text and the version the client gave it.
45
+ struct Doc {
46
+ text: String,
47
+ version: i32,
48
+ }
49
+
50
+ type Docs = Arc<Mutex<HashMap<Url, Doc>>>;
51
+
52
+ /// How long the edits must pause before a changed document is checked again.
53
+ const DEBOUNCE: Duration = Duration::from_millis(250);
54
+
37
55
  struct Backend {
38
56
  client: Client,
39
- docs: Mutex<HashMap<Url, String>>,
57
+ docs: Docs,
40
58
  libPath: PathBuf,
41
59
  /// Lazily built on first completion request and kept for the server's
42
60
  /// lifetime — the std lib doesn't change while `plum-lsp` is running.
@@ -68,8 +86,8 @@ impl Backend {
68
86
  }
69
87
  Diagnostic {
70
88
  range: Range {
71
- start: Position::new(start.row as u32, start.column as u32),
89
+ start: position::fromByte(source, start.row, start.column),
72
- end: Position::new(e.end.row as u32, e.end.column as u32),
90
+ end: position::fromByte(source, e.end.row, e.end.column),
73
91
  },
74
92
  severity: Some(DiagnosticSeverity::ERROR),
75
93
  source: Some("plum-syntax".into()),
@@ -80,18 +98,6 @@ impl Backend {
80
98
  .collect()
81
99
  }
82
100
 
83
- /// Diagnostics from `plum_checker::checkSource`, run against the live
84
- /// in-memory buffer (via `loadAndMergeWithOverridesDiag`) rather than
85
- /// whatever's on disk, so an unsaved edit is reflected immediately.
86
- /// Every other (transitively imported) file still resolves from disk.
87
- /// Returns `None` (rather than an error) if the document has no on-disk
88
- /// path or fails to load — those aren't type errors, so we don't want to
89
- /// flash a bogus diagnostic.
90
- fn typeDiagnostics(&self, uri: &Url, text: &str) -> Option<Vec<Diagnostic>> {
91
- let path = uri.to_file_path().ok()?;
92
- typeDiagnosticsFor(&path, &self.libPath, text)
93
- }
94
-
95
101
  /// Builds `plum_checker`'s global tables for the live buffer, the same
96
102
  /// way `typeDiagnostics` does — used by member/std-lib completion, which
97
103
  /// both need method/field/import-target lookups, not just the document's
@@ -106,10 +112,12 @@ impl Backend {
106
112
 
107
113
  async fn completionItems(&self, uri: &Url, pos: Position) -> Vec<CompletionItem> {
108
114
  let text = match self.docs.lock().await.get(uri) {
109
- Some(t) => t.clone(),
115
+ Some(d) => d.text.clone(),
110
116
  None => return Vec::new(),
111
117
  };
112
- let line_text = text.lines().nth(pos.line as usize).unwrap_or("");
118
+ let line_text = position::lineOf(&text, pos.line as usize);
119
+ // The scanners below count chars; the client counts UTF-16 units.
120
+ let pos = Position::new(pos.line, position::charCol(line_text, pos.character) as u32);
113
121
  let sanitized = completion::sanitizeForParsing(&text, pos);
114
122
  let tree = Self::parseTree(&sanitized);
115
123
  let own_source = plum_core::AstParser::new(&sanitized).parseSourceRaw(tree.root_node());
@@ -176,24 +184,59 @@ impl Backend {
176
184
  items
177
185
  }
178
186
 
187
+ /// Checks `uri` after `delay` on a blocking thread, unless a newer version
188
+ /// arrived meanwhile (its own check follows), and publishes the result if the
189
+ /// text is still that version.
179
- async fn publishAll(&self, uri: Url) {
190
+ async fn schedulePublish(&self, uri: Url, delay: Duration) {
191
+ let (client, docs, libPath) = (self.client.clone(), self.docs.clone(), self.libPath.clone());
180
- let text = match self.docs.lock().await.get(&uri) {
192
+ let Some(scheduled) = docs.lock().await.get(&uri).map(|d| d.version) else {
181
- Some(t) => t.clone(),
182
- None => return,
193
+ return;
183
194
  };
184
- let tree = Self::parseTree(&text);
195
+ tokio::spawn(async move {
185
- let mut diagnostics = Self::syntaxDiagnostics(&tree, &text);
186
- if diagnostics.is_empty() {
196
+ if !delay.is_zero() {
187
- if let Some(mut typeErrors) = self.typeDiagnostics(&uri, &text) {
188
- diagnostics.append(&mut typeErrors);
197
+ tokio::time::sleep(delay).await;
189
198
  }
199
+ let Some((text, version)) = docs.lock().await.get(&uri).map(|d| (d.text.clone(), d.version)) else {
200
+ return;
201
+ };
202
+ if version != scheduled {
203
+ return;
190
- }
204
+ }
191
- self.client
192
- .publish_diagnostics(uri, diagnostics, None)
205
+ let path = uri.to_file_path().ok();
206
+ let diagnostics = tokio::task::spawn_blocking(move || diagnosticsFor(path.as_deref(), &libPath, &text))
193
- .await;
207
+ .await
208
+ .unwrap_or_default();
209
+ if docs.lock().await.get(&uri).map(|d| d.version) != Some(version) {
210
+ return;
211
+ }
212
+ client.publish_diagnostics(uri, diagnostics, Some(version)).await;
213
+ });
194
214
  }
195
215
  }
196
216
 
217
+ /// Every diagnostic of the document `text` (at `path`, when it has one): syntax
218
+ /// errors, else load and type errors. A panic in the compiler becomes a diagnostic.
219
+ fn diagnosticsFor(path: Option<&Path>, libPath: &Path, text: &str) -> Vec<Diagnostic> {
220
+ let run = || {
221
+ let tree = Backend::parseTree(text);
222
+ let syntax = Backend::syntaxDiagnostics(&tree, text);
223
+ match path {
224
+ Some(path) if syntax.is_empty() => typeDiagnosticsFor(path, libPath, text),
225
+ _ => syntax,
226
+ }
227
+ };
228
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)).unwrap_or_else(|p| {
229
+ let what = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned());
230
+ vec![Diagnostic {
231
+ range: Range { start: Position::new(0, 0), end: Position::new(0, 0) },
232
+ severity: Some(DiagnosticSeverity::ERROR),
233
+ source: Some("plum-lsp".into()),
234
+ message: format!("the compiler panicked: {}", what.unwrap_or_else(|| "unknown cause".into())),
235
+ ..Default::default()
236
+ }]
237
+ })
238
+ }
239
+
197
240
  #[tower_lsp::async_trait]
198
241
  impl LanguageServer for Backend {
199
242
  async fn initialize(&self, _: InitializeParams) -> RpcResult<InitializeResult> {
@@ -207,6 +250,7 @@ impl LanguageServer for Backend {
207
250
  ..Default::default()
208
251
  }),
209
252
  hover_provider: Some(HoverProviderCapability::Simple(true)),
253
+ definition_provider: Some(OneOf::Left(true)),
210
254
  ..Default::default()
211
255
  },
212
256
  server_info: Some(ServerInfo {
@@ -227,37 +271,56 @@ impl LanguageServer for Backend {
227
271
  }
228
272
 
229
273
  async fn did_open(&self, params: DidOpenTextDocumentParams) {
230
- let uri = params.text_document.uri;
274
+ let doc = params.text_document;
231
- self.docs
232
- .lock()
233
- .await
234
- .insert(uri.clone(), params.text_document.text);
275
+ self.docs.lock().await.insert(doc.uri.clone(), Doc { text: doc.text, version: doc.version });
235
- self.publishAll(uri).await;
276
+ self.schedulePublish(doc.uri, Duration::ZERO).await;
236
277
  }
237
278
 
238
279
  async fn did_change(&self, mut params: DidChangeTextDocumentParams) {
239
- let uri = params.text_document.uri;
280
+ let doc = params.text_document;
240
281
  // FULL sync: the last content change carries the whole new text.
241
282
  if let Some(change) = params.content_changes.pop() {
242
- self.docs.lock().await.insert(uri.clone(), change.text);
283
+ self.docs.lock().await.insert(doc.uri.clone(), Doc { text: change.text, version: doc.version });
243
284
  }
244
- self.publishAll(uri).await;
285
+ self.schedulePublish(doc.uri, DEBOUNCE).await;
245
286
  }
246
287
 
247
288
  async fn did_save(&self, params: DidSaveTextDocumentParams) {
248
- self.publishAll(params.text_document.uri).await;
289
+ self.schedulePublish(params.text_document.uri, Duration::ZERO).await;
249
290
  }
250
291
 
251
292
  async fn did_close(&self, params: DidCloseTextDocumentParams) {
293
+ let uri = params.text_document.uri;
252
- self.docs.lock().await.remove(&params.text_document.uri);
294
+ self.docs.lock().await.remove(&uri);
295
+ self.client.publish_diagnostics(uri, Vec::new(), None).await;
296
+ }
297
+
298
+ async fn goto_definition(&self, params: GotoDefinitionParams) -> RpcResult<Option<GotoDefinitionResponse>> {
299
+ let p = params.text_document_position_params;
300
+ let Some(text) = self.docs.lock().await.get(&p.text_document.uri).map(|d| d.text.clone()) else {
301
+ return Ok(None);
302
+ };
303
+ let Ok(path) = p.text_document.uri.to_file_path() else {
304
+ return Ok(None);
305
+ };
306
+ let libPath = self.libPath.clone();
307
+ let found = tokio::task::spawn_blocking(move || {
308
+ std::panic::catch_unwind(|| definition::definitionAt(&path, &libPath, &text, p.position)).ok().flatten()
309
+ })
310
+ .await
311
+ .ok()
312
+ .flatten();
313
+ Ok(found.map(GotoDefinitionResponse::Scalar))
253
314
  }
254
315
 
255
316
  async fn hover(&self, params: HoverParams) -> RpcResult<Option<Hover>> {
256
317
  let p = params.text_document_position_params;
257
- let Some(text) = self.docs.lock().await.get(&p.text_document.uri).cloned() else {
318
+ let Some(text) = self.docs.lock().await.get(&p.text_document.uri).map(|d| d.text.clone()) else {
258
319
  return Ok(None);
259
320
  };
321
+ let line = position::lineOf(&text, p.position.line as usize);
322
+ let col = position::byteCol(line, p.position.character);
260
- Ok(hoverAt(&text, p.position.line as usize, p.position.character as usize)
323
+ Ok(hoverAt(&text, p.position.line as usize, col)
261
324
  .map(|s| Hover {
262
325
  contents: HoverContents::Scalar(MarkedString::String(s)),
263
326
  range: None,
@@ -273,46 +336,60 @@ impl LanguageServer for Backend {
273
336
  }
274
337
  }
275
338
 
276
- /// `Backend::typeDiagnostics` without the `Backend` (so it is unit-testable):
339
+ /// The load and type errors of the document `text` at `path`: loads it with
277
- /// loads `path` with `text` overriding what's on disk, then runs the checker.
340
+ /// `text` overriding what's on disk, then runs the checker. An error in another
341
+ /// file (a bad import, say) is shown on the document's first line, naming it.
278
- fn typeDiagnosticsFor(path: &Path, libPath: &Path, text: &str) -> Option<Vec<Diagnostic>> {
342
+ fn typeDiagnosticsFor(path: &Path, libPath: &Path, text: &str) -> Vec<Diagnostic> {
279
343
  let canon = std::fs::canonicalize(path).unwrap_or(path.to_path_buf());
280
344
  let mut overrides = HashMap::new();
281
- overrides.insert(canon, text.to_string());
345
+ overrides.insert(canon.clone(), text.to_string());
282
- let ast = plum_core::loadAndMergeWithOverridesDiag(path, libPath, &overrides).ok()?;
346
+ let diags = match plum_core::loadAndMergeWithOverridesDiag(path, libPath, &overrides) {
283
- let lastLine = text.lines().count().max(1) as u32 - 1;
347
+ Ok(ast) => {
284
- let opts = plum_driver::PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
348
+ let opts = plum_driver::PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
285
- match plum_driver::check(&ast, &opts) {
349
+ match plum_driver::check(&ast, &opts) {
286
- Ok(_) => Some(Vec::new()),
350
+ Ok(_) => return Vec::new(),
287
- Err(diags) => Some(
351
+ Err(diags) => diags,
352
+ }
353
+ }
288
- diags
354
+ Err(diags) => diags,
355
+ };
356
+ diags.into_iter().map(|d| lspDiagnostic(d, &canon, text)).collect()
357
+ }
358
+
359
+ /// A compiler diagnostic as an LSP one on the document `text` (at `canon`).
360
+ fn lspDiagnostic(d: plum_core::diag::Diagnostic, canon: &Path, text: &str) -> Diagnostic {
361
+ let lastLine = text.lines().count().max(1) - 1;
362
+ let lineEnd = |line: usize| Position::new(line as u32, position::utf16Col(position::lineOf(text, line), usize::MAX));
363
+ let elsewhere = !d.file.is_empty() && std::fs::canonicalize(&d.file).map_or(true, |f| f != canon);
364
+ let source = Some(if d.kind == plum_core::diag::DiagKind::Load { "plum-load" } else { "plum-check" }.into());
289
- .into_iter()
365
+ if elsewhere {
366
+ let at = if d.line > 0 { format!("{}:{}:{}", d.file, d.line, d.column) } else { d.file.clone() };
290
- .map(|d| {
367
+ return Diagnostic {
368
+ range: Range { start: Position::new(0, 0), end: lineEnd(0) },
369
+ severity: Some(DiagnosticSeverity::ERROR),
370
+ source,
371
+ message: format!("{at}: {}", d.message),
372
+ ..Default::default()
373
+ };
374
+ }
291
- // `plum_core::Diagnostic` positions are 1-based (0 = unknown); LSP's
375
+ // `plum_core::Diagnostic` positions are 1-based byte columns (0 = unknown); LSP's
292
- // are 0-based. The range runs from the reported start to the recorded end
376
+ // are 0-based UTF-16. The range runs from the reported start to the recorded end
293
- // (`end_line`/`end_column`), or to the end of the start line when the end
377
+ // (`end_line`/`end_column`), or to the end of the start line when the end is
294
- // is unknown; clamped to the document.
378
+ // unknown; clamped to the document.
295
- let line = d.line.saturating_sub(1).min(lastLine as usize) as u32;
379
+ let line = d.line.saturating_sub(1).min(lastLine);
296
- let col = d.column.saturating_sub(1) as u32;
380
+ let start = position::fromByte(text, line, d.column.saturating_sub(1));
297
- // Underline the failing node's span when the checker recorded one.
298
- let end = if d.line != 0 && d.end_line != 0 {
381
+ let end = if d.line != 0 && d.end_line != 0 {
382
+ let endLine = d.end_line.saturating_sub(1).min(lastLine);
299
- Position::new(d.end_line.saturating_sub(1).min(lastLine as usize) as u32, d.end_column.saturating_sub(1) as u32)
383
+ position::fromByte(text, endLine, d.end_column.saturating_sub(1))
300
- } else {
384
+ } else {
301
- Position::new(line, u32::MAX)
385
+ lineEnd(line)
302
- };
386
+ };
303
- Diagnostic {
387
+ Diagnostic {
304
- range: Range {
388
+ range: Range { start, end },
305
- start: Position::new(line, col),
306
- end,
307
- },
308
- severity: Some(DiagnosticSeverity::ERROR),
389
+ severity: Some(DiagnosticSeverity::ERROR),
309
- source: Some("plum-check".into()),
390
+ source,
310
- message: d.message,
391
+ message: d.message,
311
- ..Default::default()
392
+ ..Default::default()
312
- }
313
- })
314
- .collect(),
315
- ),
316
393
  }
317
394
  }
318
395
 
@@ -446,19 +523,16 @@ async fn main() {
446
523
  // CONTAINING `std/` (an `import std/Bool` resolves to
447
524
  // `<lib_path>/std/Bool.plum` — see `plum_core::loader::loadImport`),
448
525
  // not `std` itself; the repo root is `.` when run from a checkout.
449
- let libPath = std::env::args()
526
+ let libPath = plum_core::loader::libPathOrDefault(
450
- .collect::<Vec<_>>()
451
- .windows(2)
452
- .find(|w| w[0] == "--lib-path")
527
+ std::env::args().collect::<Vec<_>>().windows(2).find(|w| w[0] == "--lib-path").map(|w| PathBuf::from(&w[1])),
453
- .map(|w| PathBuf::from(&w[1]))
528
+ );
454
- .unwrap_or_else(|| PathBuf::from("."));
455
529
 
456
530
  let stdin = tokio::io::stdin();
457
531
  let stdout = tokio::io::stdout();
458
532
 
459
533
  let (service, socket) = LspService::new(|client| Backend {
460
534
  client,
461
- docs: Mutex::new(HashMap::new()),
535
+ docs: Arc::new(Mutex::new(HashMap::new())),
462
536
  libPath,
463
537
  stdIndex: OnceLock::new(),
464
538
  });
@@ -499,7 +573,7 @@ mod tests {
499
573
  let text = std::fs::read_to_string(&path).unwrap();
500
574
  let tree = Backend::parseTree(&text);
501
575
  assert!(Backend::syntaxDiagnostics(&tree, &text).is_empty());
502
- let diags = typeDiagnosticsFor(&path, &repoRoot(), &text).expect("sequences.plum loads");
576
+ let diags = typeDiagnosticsFor(&path, &repoRoot(), &text);
503
577
  assert!(
504
578
  diags.is_empty(),
505
579
  "unexpected diagnostics: {:?}",
@@ -524,7 +598,7 @@ mod tests {
524
598
  Backend::syntaxDiagnostics(&tree, &text).is_empty(),
525
599
  "{f}: syntax"
526
600
  );
527
- let diags = typeDiagnosticsFor(&path, &repoRoot(), &text).expect("loads");
601
+ let diags = typeDiagnosticsFor(&path, &repoRoot(), &text);
528
602
  assert!(
529
603
  diags.is_empty(),
530
604
  "{f}: {:?}",
@@ -770,7 +844,7 @@ mod tests {
770
844
  Backend::syntaxDiagnostics(&tree, &text).is_empty(),
771
845
  "{path:?}: syntax"
772
846
  );
773
- let diags = typeDiagnosticsFor(&path, &repoRoot(), &text).expect("loads");
847
+ let diags = typeDiagnosticsFor(&path, &repoRoot(), &text);
774
848
  assert!(
775
849
  diags.is_empty(),
776
850
  "{path:?}: {:?}",
@@ -873,7 +947,7 @@ mod tests {
873
947
  let path = dir.join("main.plum");
874
948
  let text = "import std/Int\n\nfun main() -> Int =\n nope\n";
875
949
  std::fs::write(&path, text).unwrap();
876
- let diags = typeDiagnosticsFor(&path, &repoRoot(), text).expect("loads");
950
+ let diags = typeDiagnosticsFor(&path, &repoRoot(), text);
877
951
  let _ = std::fs::remove_dir_all(&dir);
878
952
  assert_eq!(diags.len(), 1, "{diags:?}");
879
953
  assert_eq!(diags[0].range.start, Position::new(3, 2), "{:?}", diags[0].range);
@@ -888,7 +962,7 @@ mod tests {
888
962
  let path = dir.join("main.plum");
889
963
  let text = "import std/Int\nimport std/Str\n\nfun f() -> Int = 1 + \"a\"\n";
890
964
  std::fs::write(&path, text).unwrap();
891
- let diags = typeDiagnosticsFor(&path, &repoRoot(), text).expect("loads");
965
+ let diags = typeDiagnosticsFor(&path, &repoRoot(), text);
892
966
  let _ = std::fs::remove_dir_all(&dir);
893
967
  assert_eq!(diags.len(), 1, "{diags:?}");
894
968
  assert_eq!(diags[0].range.start, Position::new(3, 21), "{:?}", diags[0].range);
@@ -903,13 +977,67 @@ mod tests {
903
977
  let path = dir.join("main.plum");
904
978
  let text = "import std/Int\nimport std/Bool\n\nfun f() -> Bool = 1 && true\n";
905
979
  std::fs::write(&path, text).unwrap();
906
- let diags = typeDiagnosticsFor(&path, &repoRoot(), text).expect("loads");
980
+ let diags = typeDiagnosticsFor(&path, &repoRoot(), text);
907
981
  let _ = std::fs::remove_dir_all(&dir);
908
982
  assert_eq!(diags.len(), 1, "{diags:?}");
909
983
  assert_eq!(diags[0].range.start, Position::new(3, 18), "{:?}", diags[0].range);
910
984
  assert_eq!(diags[0].range.end, Position::new(3, 19), "{:?}", diags[0].range);
911
985
  }
912
986
 
987
+ /// Columns after non-ASCII text are UTF-16 units: "é😀" is 6 bytes but 3 units.
988
+ #[test]
989
+ fn diagnosticColumnsAreUtf16() {
990
+ let src = "fun f() =\n _ := \"é😀\" ()\n";
991
+ let d = Backend::syntaxDiagnostics(&Backend::parseTree(src), src);
992
+ assert_eq!(d.len(), 1, "{d:?}");
993
+ let byte = src.lines().nth(1).unwrap().find("()").unwrap();
994
+ assert_eq!(d[0].range.start, Position::new(1, byte as u32 - 3), "{d:?}");
995
+
996
+ let dir = std::env::temp_dir().join(format!("plum_lsp_utf16_{}", std::process::id()));
997
+ std::fs::create_dir_all(&dir).unwrap();
998
+ let path = dir.join("main.plum");
999
+ let text = "import std/Int\nimport std/Str\n\nfun f() -> Int =\n _ := \"é😀\"\n nope\n";
1000
+ std::fs::write(&path, text).unwrap();
1001
+ let line = " _ := \"é😀\" + nope";
1002
+ let text2 = text.replace(" _ := \"é😀\"\n nope\n", &format!("{line}\n 0\n"));
1003
+ let diags = typeDiagnosticsFor(&path, &repoRoot(), &text2);
1004
+ let _ = std::fs::remove_dir_all(&dir);
1005
+ assert!(!diags.is_empty(), "{diags:?}");
1006
+ let nope = diags.iter().find(|d| d.message.contains("nope")).unwrap_or(&diags[0]);
1007
+ let unit = position::utf16Col(line, line.find("nope").unwrap());
1008
+ assert_eq!(nope.range.start, Position::new(4, unit), "{nope:?}");
1009
+ assert!(nope.range.end.character <= line.encode_utf16().count() as u32, "{nope:?}");
1010
+ }
1011
+
1012
+ /// A bad import is a diagnostic naming it, not silence.
1013
+ #[test]
1014
+ fn aLoadErrorIsADiagnostic() {
1015
+ let dir = std::env::temp_dir().join(format!("plum_lsp_load_{}", std::process::id()));
1016
+ std::fs::create_dir_all(&dir).unwrap();
1017
+ let path = dir.join("main.plum");
1018
+ let text = "import std/Int\nimport std/NoSuchModule\n\nfun f() -> Int = 1\n";
1019
+ std::fs::write(&path, text).unwrap();
1020
+ let diags = diagnosticsFor(Some(&path), &repoRoot(), text);
1021
+ let _ = std::fs::remove_dir_all(&dir);
1022
+ assert_eq!(diags.len(), 1, "{diags:?}");
1023
+ assert!(diags[0].message.contains("NoSuchModule"), "{}", diags[0].message);
1024
+ // No file: syntax only.
1025
+ assert!(diagnosticsFor(None, &repoRoot(), text).is_empty());
1026
+ }
1027
+
1028
+ /// Completion scanners get a char index: after "é😀" the client's column 6 is char 5.
1029
+ #[test]
1030
+ fn completionColumnsAreConvertedFromUtf16() {
1031
+ let line = " s := \"é😀\".le";
1032
+ let units = line.encode_utf16().count() as u32;
1033
+ let ch = position::charCol(line, units);
1034
+ assert_eq!(ch, line.chars().count());
1035
+ assert_eq!(completion::receiverBeforeDot(line, ch), None, "a string literal is no receiver");
1036
+ let line = " é := s.le";
1037
+ let ch = position::charCol(line, line.encode_utf16().count() as u32);
1038
+ assert_eq!(completion::receiverBeforeDot(line, ch).as_deref(), Some("s"));
1039
+ }
1040
+
913
1041
  #[test]
914
1042
  fn syntaxDiagnosticUnderlinesTheTokenNotTheFunction() {
915
1043
  let src = "import std/Float\n\nexport fun update(w: Float, dt: Float) =\n ()\n\nfun ok() =\n _ := 1.0\n";
compiler/lsp/src/position.rs ADDED
@@ -0,0 +1,77 @@
1
+ //! LSP positions count UTF-16 code units in a line; the parser and the compiler's
2
+ //! diagnostics count bytes. Every conversion between the two goes through here.
3
+
4
+ /// Line `line` (0-based) of `text`, without its line ending ("" past the end).
5
+ pub fn lineOf(text: &str, line: usize) -> &str {
6
+ let l = text.split('\n').nth(line).unwrap_or("");
7
+ l.strip_suffix('\r').unwrap_or(l)
8
+ }
9
+
10
+ /// The UTF-16 column of byte offset `byte` in `line` (clamped to the line; a
11
+ /// byte inside a character counts from that character's start).
12
+ pub fn utf16Col(line: &str, byte: usize) -> u32 {
13
+ let mut units = 0u32;
14
+ for (i, c) in line.char_indices() {
15
+ if i >= byte {
16
+ break;
17
+ }
18
+ units += c.len_utf16() as u32;
19
+ }
20
+ units
21
+ }
22
+
23
+ /// The byte offset in `line` of UTF-16 column `col` (clamped to the line's end;
24
+ /// a column inside a surrogate pair gives the start of that character).
25
+ pub fn byteCol(line: &str, col: u32) -> usize {
26
+ let mut units = 0u32;
27
+ for (i, c) in line.char_indices() {
28
+ if units >= col {
29
+ return i;
30
+ }
31
+ units += c.len_utf16() as u32;
32
+ if units > col {
33
+ return i;
34
+ }
35
+ }
36
+ line.len()
37
+ }
38
+
39
+ /// The char index in `line` of UTF-16 column `col` (for the char-based scanners).
40
+ pub fn charCol(line: &str, col: u32) -> usize {
41
+ line[..byteCol(line, col)].chars().count()
42
+ }
43
+
44
+ /// An LSP position from a 0-based line and a byte column in `text`.
45
+ pub fn fromByte(text: &str, line: usize, byte: usize) -> tower_lsp::lsp_types::Position {
46
+ tower_lsp::lsp_types::Position::new(line as u32, utf16Col(lineOf(text, line), byte))
47
+ }
48
+
49
+ #[cfg(test)]
50
+ mod tests {
51
+ use super::*;
52
+
53
+ #[test]
54
+ fn asciiIsTheSameEitherWay() {
55
+ assert_eq!(utf16Col("abc", 2), 2);
56
+ assert_eq!(byteCol("abc", 2), 2);
57
+ assert_eq!(byteCol("abc", 9), 3);
58
+ }
59
+
60
+ #[test]
61
+ fn nonAsciiCountsUtf16Units() {
62
+ // "é" is 2 bytes and 1 unit; "😀" is 4 bytes and 2 units.
63
+ let l = "é😀x";
64
+ assert_eq!(utf16Col(l, 2), 1);
65
+ assert_eq!(utf16Col(l, 6), 3);
66
+ assert_eq!(byteCol(l, 1), 2);
67
+ assert_eq!(byteCol(l, 3), 6);
68
+ assert_eq!(byteCol(l, 2), 2, "inside the pair: the character's start");
69
+ assert_eq!(charCol(l, 3), 2);
70
+ }
71
+
72
+ #[test]
73
+ fn linesDropTheirEnding() {
74
+ assert_eq!(lineOf("a\r\nbé\n", 1), "bé");
75
+ assert_eq!(lineOf("a", 5), "");
76
+ }
77
+ }
compiler/lsp/tests/protocol.rs ADDED
@@ -0,0 +1,142 @@
1
+ //! plum-lsp over stdio: diagnostics carry the document version, quick edits are
2
+ //! checked once, and a definition request finds the declaration.
3
+ #![allow(non_snake_case)]
4
+
5
+ use std::io::{BufRead, BufReader, Read, Write};
6
+ use std::process::{Child, ChildStdin, Command, Stdio};
7
+ use std::sync::mpsc::{channel, Receiver};
8
+ use std::time::{Duration, Instant};
9
+
10
+ /// The server, killed when dropped.
11
+ struct Server {
12
+ child: Child,
13
+ stdin: ChildStdin,
14
+ messages: Receiver<String>,
15
+ }
16
+
17
+ impl Drop for Server {
18
+ fn drop(&mut self) {
19
+ let _ = self.child.kill();
20
+ let _ = self.child.wait();
21
+ }
22
+ }
23
+
24
+ impl Server {
25
+ fn start() -> Server {
26
+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
27
+ let mut child = Command::new(env!("CARGO_BIN_EXE_plum-lsp"))
28
+ .arg("--lib-path")
29
+ .arg(&root)
30
+ .stdin(Stdio::piped())
31
+ .stdout(Stdio::piped())
32
+ .stderr(Stdio::null())
33
+ .spawn()
34
+ .expect("start plum-lsp");
35
+ let stdin = child.stdin.take().unwrap();
36
+ let mut out = BufReader::new(child.stdout.take().unwrap());
37
+ let (tx, messages) = channel();
38
+ std::thread::spawn(move || loop {
39
+ let mut len = 0usize;
40
+ loop {
41
+ let mut line = String::new();
42
+ if out.read_line(&mut line).unwrap_or(0) == 0 {
43
+ return;
44
+ }
45
+ let line = line.trim_end();
46
+ if line.is_empty() {
47
+ break;
48
+ }
49
+ if let Some(n) = line.strip_prefix("Content-Length: ") {
50
+ len = n.parse().unwrap();
51
+ }
52
+ }
53
+ let mut body = vec![0u8; len];
54
+ if out.read_exact(&mut body).is_err() || tx.send(String::from_utf8(body).unwrap()).is_err() {
55
+ return;
56
+ }
57
+ });
58
+ Server { child, stdin, messages }
59
+ }
60
+
61
+ fn send(&mut self, json: &str) {
62
+ write!(self.stdin, "Content-Length: {}\r\n\r\n{json}", json.len()).unwrap();
63
+ self.stdin.flush().unwrap();
64
+ }
65
+
66
+ /// Every message that arrives within `wait`.
67
+ fn collect(&self, wait: Duration) -> Vec<String> {
68
+ let end = Instant::now() + wait;
69
+ let mut got = Vec::new();
70
+ while let Some(left) = end.checked_duration_since(Instant::now()) {
71
+ match self.messages.recv_timeout(left) {
72
+ Ok(m) => got.push(m),
73
+ Err(_) => break,
74
+ }
75
+ }
76
+ got
77
+ }
78
+
79
+ /// The first message containing `needle`, within 30 seconds.
80
+ fn waitFor(&self, needle: &str) -> String {
81
+ let end = Instant::now() + Duration::from_secs(30);
82
+ while let Some(left) = end.checked_duration_since(Instant::now()) {
83
+ match self.messages.recv_timeout(left) {
84
+ Ok(m) if m.contains(needle) => return m,
85
+ Ok(_) => {}
86
+ Err(_) => break,
87
+ }
88
+ }
89
+ panic!("no message with {needle}");
90
+ }
91
+ }
92
+
93
+ fn escape(s: &str) -> String {
94
+ s.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n")
95
+ }
96
+
97
+ #[test]
98
+ fn diagnosticsAreVersionedDebouncedAndDefinitionsFound() {
99
+ let dir = std::env::temp_dir().join(format!("plum_lsp_protocol_{}", std::process::id()));
100
+ std::fs::create_dir_all(&dir).unwrap();
101
+ let path = dir.join("main.plum");
102
+ let good = "import std/Int\n\nfun helper() -> Int = 1\n\nfun main() -> Int =\n helper()\n";
103
+ std::fs::write(&path, good).unwrap();
104
+ let uri = format!("file://{}", path.display());
105
+
106
+ let mut s = Server::start();
107
+ s.send(r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{}}}"#);
108
+ let init = s.waitFor(r#""id":1"#);
109
+ assert!(init.contains(r#""definitionProvider":true"#), "{init}");
110
+ s.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
111
+
112
+ s.send(&format!(
113
+ r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"plum","version":1,"text":"{}"}}}}}}"#,
114
+ escape(good)
115
+ ));
116
+ let opened = s.waitFor("publishDiagnostics");
117
+ assert!(opened.contains(r#""version":1"#) && opened.contains(r#""diagnostics":[]"#), "{opened}");
118
+
119
+ // Two quick edits: only the last version is checked and published.
120
+ for (version, text) in [(2, good.replace("helper()\n", "nope\n")), (3, good.replace("helper()\n", "nada\n"))] {
121
+ s.send(&format!(
122
+ r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":{version}}},"contentChanges":[{{"text":"{}"}}]}}}}"#,
123
+ escape(&text)
124
+ ));
125
+ }
126
+ let published: Vec<String> = s.collect(Duration::from_secs(5)).into_iter().filter(|m| m.contains("publishDiagnostics")).collect();
127
+ assert_eq!(published.len(), 1, "{published:?}");
128
+ assert!(published[0].contains(r#""version":3"#) && published[0].contains("nada"), "{published:?}");
129
+
130
+ // Back to the good text, then go to `helper`'s definition from its call.
131
+ s.send(&format!(
132
+ r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":4}},"contentChanges":[{{"text":"{}"}}]}}}}"#,
133
+ escape(good)
134
+ ));
135
+ s.send(&format!(
136
+ r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":5,"character":4}}}}}}"#
137
+ ));
138
+ let def = s.waitFor(r#""id":2"#);
139
+ assert!(def.contains(r#""start":{"character":0,"line":2}"#), "{def}");
140
+ drop(s);
141
+ let _ = std::fs::remove_dir_all(&dir);
142
+ }