diff --git a/.github/workflows/reusable-build.yml b/.github/workflows/reusable-build.yml index bab0146b..071db8fa 100644 --- a/.github/workflows/reusable-build.yml +++ b/.github/workflows/reusable-build.yml @@ -154,6 +154,7 @@ jobs: run: | New-Item -ItemType Directory -Force -Path artifact-infc Copy-Item target\x86_64-pc-windows-gnu\release\infc.exe artifact-infc\ + Copy-Item target\x86_64-pc-windows-gnu\release\inference-lsp.exe artifact-infc\ - name: Prepare infs Artifact Package (Windows) if: runner.os == 'Windows' && inputs.package-artifacts && inputs.release-build @@ -166,6 +167,7 @@ jobs: run: | mkdir -p artifact-infc cp target/release/infc artifact-infc/ + cp target/release/inference-lsp artifact-infc/ - name: Prepare infs Artifact Package (Linux) if: runner.os == 'Linux' && inputs.package-artifacts && inputs.release-build @@ -204,6 +206,7 @@ jobs: run: | mkdir -p artifact-infc cp target/release/infc artifact-infc/ + cp target/release/inference-lsp artifact-infc/ - name: Prepare infs Artifact Package (macOS) if: runner.os == 'macOS' && inputs.package-artifacts && inputs.release-build diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c1608a3..b4ea8c89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -728,6 +728,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fix Drop instruction emission for nested non-det blocks — `parent_blocks_stack.last()` (innermost block) is now used instead of `.first()` (outermost block) - Fix `lower_literal` to emit type-correct WASM const instructions — number literals now consult `TypedContext` and emit `i32.const` or `i64.const` based on inferred type instead of always emitting `i32.const` - Fix `wasm_to_v` public API signature — parameter changed from `&Vec` to idiomatic `&[u8]` +- ide: the resilient project walk (`inference::load_project_resilient`) no longer runs the unreachable-file warning scan at all — `ResilientProjectParse::warnings` is documented always-empty. The scan recursively walked and canonicalized every `.inf` under the source root on every keystroke (and, for a document at a volume root like `/main.inf`, the entire disk) to compute warnings the IDE discards. The fail-fast compiler path (`parse_project`) keeps the scan — it runs once per build, not once per keystroke — so compiler behavior is unchanged ([#33]) +- Extern-import diagnostics (`use { … } from ;` binding errors such as an undeclared extern import or an ambiguous extern module) reported from an *imported* file now carry that file's module-path label instead of rendering as if they were in the entry file. Locations are per-file-local, so the missing label made these errors point at wrong positions in the entry file — visible in both the aggregated compiler message and the structured diagnostics the LSP consumes ([#33]) ### Project Manifest @@ -783,6 +785,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Runs `infs component add ` with a progress notification; refreshes `infs doctor` on success; offers Show Output / Retry actions on failure - `infs doctor` notifications (error and warning toasts alike) gain an "Install wasm-opt" action button whenever a `wasm-opt` check reports a warning or failure, invoking the install command directly +### IDE / LSP + +- Add `inference-lsp`, a Language Server Protocol server for Inference (`apps/lsp`) ([#33]) + - A synchronous, single-threaded `lsp-server` 0.8 stdio binary; single-threaded by design because `TypedContext` is `!Send` + - Diagnostics: merged syntax, import, type-check, and analysis-rule findings (rule codes `A001`–`A041`), published on `didOpen`/`didChange`/`didClose` + - Hover: type of the identifier/expression under the cursor, plus dedicated explanations of the non-deterministic keywords (`forall`, `exists`, `unique`, `assume`) and the uzumaki `@` operator, including their Rocq lowering (`BI_forall`/`BI_exists`/`BI_assume`/`BI_uzumaki_num`) + - Goto-definition, including cross-file resolution into an imported module + - Document symbols (hierarchical or flattened, negotiated from client capabilities), completions (context-aware: struct members only after `.`), and inlay hints annotating every non-det block and `@` binding + - Full-text document sync (`TextDocumentSyncKind::Full`); UTF-16 position encoding only (the LSP default; no `positionEncoding` negotiation) + - `file://` URI handling with percent-encoding and Windows drive-letter support + - End-to-end test suite (`apps/lsp/tests/e2e.rs`) spawning the real binary over stdio and asserting on raw JSON-RPC across 18 scenarios (handshake, diagnostics lifecycle, hover, goto, cross-file import, document symbols, completion, inlay hints, UTF-16 positions, robustness, shutdown/exit, stdout framing hygiene) +- Add the `ide/` crate stack backing the LSP server ([#33]) + - `ide/vfs`: `FileId` path interning plus an open-document content overlay; no file I/O, no path canonicalization + - `ide/base-db`: `LineIndex` (byte offset ⇄ 0-based line / UTF-16 column) and the `TextRange`/`LineCol`/`FilePosition`/`FileRange` position PODs + - `ide/ide-db`: `RootDatabase` with closure-aware analysis invalidation, analyzing every open file as its own project entry; `FileAnalysis` merges parse errors, structured type diagnostics, and analysis findings behind an overlay-then-disk `FileLoader` driving `core/inference`'s shared import-closure walk + - `ide/ide`: the `AnalysisHost`/`Analysis` feature API — diagnostics, hover, goto-definition, document symbols, completions, and inlay hints, all returned as editor-terminology PODs with no compiler type crossing the boundary +- Add structured type-check diagnostics: `inference_type_checker::check_with_diagnostics` (re-exported as `inference::type_check_with_diagnostics`) ([#33]) + - Returns a `TypeCheckOutcome { typed_context, errors: Vec }` instead of aggregating errors into one `anyhow::Error` string + - Lossless: the returned `TypedContext` is fully indexed (symbol table assigned, canonical-key indexes built) even when errors are present, so tooling can still query `lookup_struct`/`lookup_enum`/`call_target`/`get_node_typeinfo` for the parts of the program that did check + - `TypeCheckerBuilder::build_typed_context` is re-expressed on top of this function, so the compiler and the IDE share exactly one checking implementation +- Add a `FileLoader` seam to `core/inference` (`exists`/`read`) so the import-closure walk can be driven by either a `DiskLoader` (the compiler) or an IDE-supplied overlay-then-disk loader, plus a resilient walk variant, `load_project_resilient`, that collects every problem (broken imports, per-file syntax errors) instead of failing fast on the first one ([#33]) + - `parse_project` is re-expressed on top of the same closure-walk logic and remains byte-identical for a clean project +- Ship `inference-lsp` with the managed toolchain ([#33]) + - Release packaging bundles the `inference-lsp` binary inside the existing `infc-` archives (no new archive names, no manifest-format change), so `infs install` places it in `toolchains//` automatically + - `infs` symlinks `inference-lsp` into `$INFERENCE_HOME/bin` next to `infc` when the default toolchain contains it, cleans the stale symlink when switching to a toolchain that predates bundling, marks it executable on Unix, and includes it in PATH-shadowing conflict detection + - `infs doctor` gains an appended `inference-lsp` check: `[OK]` with the resolved path when the default toolchain bundles it, `[WARN]` with an upgrade hint when the toolchain predates bundling (never `[FAIL]` — the language server is optional) +- VS Code extension 0.0.5: built-in LSP client — installing the extension now brings up the language server out of the box ([#33]) + - Starts `inference-lsp` over stdio on activation (new `onLanguage:inference` activation event), resolving the binary via `inference.lsp.path` setting → `$INFERENCE_HOME/bin` → PATH, mirroring the `infs` detection order; silent (log-only) when the binary is absent + - Auto-starts the server after a toolchain install/update completes, so the first-run flow (install extension → accept toolchain install) needs no reload + - New settings `inference.lsp.enabled` / `inference.lsp.path` and command `Inference: Restart Language Server`; server traces go to a dedicated `Inference Language Server` output channel + --- ## [0.0.1-alpha] - 2026-01-03 @@ -890,3 +923,4 @@ Initial tagged release. [#225]: https://github.com/Inferara/inference/issues/225 [#227]: https://github.com/Inferara/inference/issues/227 [#217]: https://github.com/Inferara/inference/issues/217 +[#33]: https://github.com/Inferara/inference/issues/33 diff --git a/apps/infs/src/toolchain/archive.rs b/apps/infs/src/toolchain/archive.rs index cf65ab1d..87486d62 100644 --- a/apps/infs/src/toolchain/archive.rs +++ b/apps/infs/src/toolchain/archive.rs @@ -369,14 +369,20 @@ fn find_common_root_folder( } } -/// Sets executable permissions on the `infc` binary within a toolchain directory (Unix only). +/// Sets executable permissions on the managed binaries within a toolchain +/// directory (Unix only). +/// +/// Always targets the `infc` binary at the toolchain root, plus each optional +/// managed binary (e.g. the bundled `inference-lsp` server) when present. +/// Toolchains that predate the bundling lack the optional binaries, so their +/// absence is silently skipped. /// /// On Windows, this function does nothing since executable permissions are not /// managed the same way. /// /// # Arguments /// -/// * `dir` - The toolchain directory containing the `infc` binary at root. +/// * `dir` - The toolchain directory containing the managed binaries at root. /// /// # Errors /// @@ -395,6 +401,13 @@ pub fn set_executable_permissions(dir: &Path) -> Result<()> { .with_context(|| format!("Failed to set permissions: {}", infc_path.display()))?; } + for optional in crate::toolchain::ToolchainPaths::OPTIONAL_MANAGED_BINARIES { + let path = dir.join(optional); + if path.is_file() { + set_executable_file(&path)?; + } + } + Ok(()) } @@ -1017,6 +1030,47 @@ mod tests { let _ = std::fs::remove_dir_all(&temp_dir); } + #[test] + fn set_executable_permissions_sets_755_on_bundled_inference_lsp() { + let temp_dir = temp_test_dir("exec_perm_lsp"); + let infc_path = temp_dir.join("infc"); + let lsp_path = temp_dir.join("inference-lsp"); + std::fs::write(&infc_path, b"infc binary").expect("Should write infc"); + std::fs::write(&lsp_path, b"lsp binary").expect("Should write inference-lsp"); + + for path in [&infc_path, &lsp_path] { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o644)) + .expect("Should set initial perms"); + } + + set_executable_permissions(&temp_dir).expect("Should set permissions"); + + let lsp_mode = std::fs::metadata(&lsp_path) + .expect("Should get metadata") + .permissions() + .mode(); + assert_eq!(lsp_mode & 0o777, 0o755, "inference-lsp should have 0o755 mode"); + + let _ = std::fs::remove_dir_all(&temp_dir); + } + + #[test] + fn set_executable_permissions_skips_absent_inference_lsp() { + let temp_dir = temp_test_dir("exec_perm_lsp_absent"); + let infc_path = temp_dir.join("infc"); + std::fs::write(&infc_path, b"infc binary").expect("Should write infc"); + + // A toolchain that predates the bundling has no inference-lsp; the + // call must still succeed and leave the directory unchanged. + set_executable_permissions(&temp_dir).expect("Should succeed without inference-lsp"); + assert!( + !temp_dir.join("inference-lsp").exists(), + "no inference-lsp file should be created" + ); + + let _ = std::fs::remove_dir_all(&temp_dir); + } + #[test] fn set_executable_file_sets_755_on_named_file() { let temp_dir = temp_test_dir("exec_file_755"); diff --git a/apps/infs/src/toolchain/conflict.rs b/apps/infs/src/toolchain/conflict.rs index 9b40697d..1bb9acd4 100644 --- a/apps/infs/src/toolchain/conflict.rs +++ b/apps/infs/src/toolchain/conflict.rs @@ -48,6 +48,10 @@ pub struct PathConflict { /// 2. The found path differs from the expected managed path /// 3. The expected managed binary actually exists /// +/// Only `infc` participates in this shared conflict block. PATH visibility of +/// the optional `inference-lsp` server is reported exclusively by the dedicated +/// `inference-lsp` doctor check, which appends its own "; also on PATH" note. +/// /// # Arguments /// /// * `bin_dir` - The managed toolchain bin directory (e.g., `~/.inference/bin`) @@ -528,4 +532,55 @@ mod tests { let lines = format_duplicate_path_warning(&[]); assert!(lines.is_empty()); } + + /// Writes an executable stub named `name` into `dir` so `which::which` + /// counts it as a match. + fn write_executable_stub(dir: &Path, name: &str) -> PathBuf { + let stub = dir.join(name); + std::fs::write(&stub, b"#!/bin/sh\nexit 0\n").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mut perms = std::fs::metadata(&stub).unwrap().permissions(); + perms.set_mode(0o755); + std::fs::set_permissions(&stub, perms).unwrap(); + } + stub + } + + #[test] + #[serial_test::serial] + fn detect_conflicts_excludes_shadowed_inference_lsp() { + let platform = Platform::detect().unwrap(); + let lsp_name = format!("inference-lsp{}", platform.executable_extension()); + + // The managed bin directory holds the expected inference-lsp... + let bin_dir = assert_fs::TempDir::new().unwrap(); + write_executable_stub(bin_dir.path(), &lsp_name); + + // ...and PATH resolves inference-lsp to a different directory, so the + // managed copy is shadowed. The shared PATH-conflict block must still + // ignore it: LSP PATH visibility is reported solely by the dedicated + // `inference-lsp` doctor check, not here. + let stub_dir = assert_fs::TempDir::new().unwrap(); + write_executable_stub(stub_dir.path(), &lsp_name); + + let original_path = env::var("PATH").unwrap_or_default(); + // SAFETY: serialized; PATH restored below before assertions. + unsafe { + env::set_var("PATH", stub_dir.path()); + } + + let conflicts = detect_path_conflicts(bin_dir.path()); + + // SAFETY: restore PATH before assertions so a panic doesn't leak state. + unsafe { + env::set_var("PATH", original_path); + } + + assert!( + conflicts.iter().all(|c| c.binary != lsp_name), + "inference-lsp must not appear in the shared PATH-conflict block: {conflicts:?}" + ); + } } diff --git a/apps/infs/src/toolchain/doctor.rs b/apps/infs/src/toolchain/doctor.rs index ef35de7c..c1d1fefa 100644 --- a/apps/infs/src/toolchain/doctor.rs +++ b/apps/infs/src/toolchain/doctor.rs @@ -10,6 +10,10 @@ //! - Toolchain directory existence //! - Default toolchain configuration //! - `infc` compiler binary presence +//! - Bundled `inference-lsp` language server presence + +use std::fmt::Write as _; +use std::path::Path; use super::conflict::enumerate_infc_on_path; use super::resolver::{self, find_infc_with_source}; @@ -117,6 +121,7 @@ pub fn run_all_checks() -> Vec { checks.push(ambiguity); } checks.push(crate::commands::wasm_opt::doctor_check()); + checks.push(check_inference_lsp()); checks } @@ -309,6 +314,72 @@ pub fn check_resolution_ambiguity() -> Option { )) } +/// Checks whether the managed `inference-lsp` language server is available. +/// +/// Newer toolchain archives bundle the LSP server alongside `infc`, so the +/// managed copy lands in the default toolchain directory (and is symlinked +/// into `bin/`). The VS Code extension resolves the server through a PATH tier +/// as well, so any `inference-lsp` also visible on `PATH` is noted on the same +/// line. +/// +/// Statuses, chosen so `infs doctor` still exits zero when the optional server +/// is simply absent: +/// - **OK** — the default toolchain bundles the server; the resolved path is +/// reported, with a PATH hit appended when one exists. +/// - **OK** — no default toolchain is set at all (deferring to +/// [`check_default_toolchain`], which owns that diagnosis). +/// - **Warning** — a default toolchain is set but predates the bundling; the +/// message hints at upgrading and notes any PATH fallback. +#[must_use] +pub fn check_inference_lsp() -> DoctorCheck { + let Ok(platform) = Platform::detect() else { + return DoctorCheck::error("inference-lsp", "Cannot detect platform"); + }; + let binary_with_ext = format!("inference-lsp{}", platform.executable_extension()); + let path_hit = which::which(&binary_with_ext).ok(); + + let Ok(paths) = ToolchainPaths::new() else { + return DoctorCheck::error("inference-lsp", "Cannot determine toolchain paths"); + }; + + inference_lsp_check(&paths, &binary_with_ext, path_hit.as_deref()) +} + +/// Pure decision logic for [`check_inference_lsp`], separated from the +/// environment reads (platform, PATH, toolchain root) so every branch is +/// unit-testable with a `ToolchainPaths` rooted at a temp directory. +fn inference_lsp_check( + paths: &ToolchainPaths, + binary_with_ext: &str, + path_hit: Option<&Path>, +) -> DoctorCheck { + let default_version = match paths.get_default_version() { + Ok(Some(v)) => v, + Ok(None) => return DoctorCheck::ok("inference-lsp", "No toolchain installed"), + Err(e) => { + return DoctorCheck::error("inference-lsp", format!("Cannot read default version: {e}")); + } + }; + + let binary_path = paths.binary_path(&default_version, binary_with_ext); + if binary_path.exists() { + let mut message = format!("Found at {}", binary_path.display()); + if let Some(hit) = path_hit { + let _ = write!(message, "; also on PATH at {}", hit.display()); + } + DoctorCheck::ok("inference-lsp", message) + } else { + let mut message = format!( + "toolchain {default_version} does not include inference-lsp; \ + install a newer toolchain to add the language server" + ); + if let Some(hit) = path_hit { + let _ = write!(message, "; a copy is available on PATH at {}", hit.display()); + } + DoctorCheck::warning("inference-lsp", message) + } +} + #[cfg(test)] mod tests { use super::*; @@ -341,9 +412,10 @@ mod tests { fn run_all_checks_returns_expected_count() { let checks = run_all_checks(); // Base checks: infs, platform, toolchain dir, default toolchain, - // infc, resolved infc, wasm-opt. Ambiguity check is conditional (0 or 1). + // infc, resolved infc, wasm-opt, inference-lsp. Ambiguity check is + // conditional (0 or 1). assert!( - checks.len() == 7 || checks.len() == 8, + checks.len() == 8 || checks.len() == 9, "unexpected check count: {}", checks.len() ); @@ -443,4 +515,110 @@ mod tests { std::fs::remove_dir_all(&temp_dir).ok(); } + + /// The bundled `inference-lsp` binary name for the running platform. + fn lsp_binary_name() -> String { + let ext = Platform::detect().unwrap().executable_extension(); + format!("inference-lsp{ext}") + } + + #[test] + fn check_inference_lsp_returns_valid_doctor_check() { + let check = check_inference_lsp(); + assert_eq!(check.name, "inference-lsp"); + assert!(!check.message.is_empty()); + assert!( + check.status == DoctorCheckStatus::Ok + || check.status == DoctorCheckStatus::Warning + || check.status == DoctorCheckStatus::Error + ); + } + + #[test] + fn inference_lsp_check_ok_when_no_default_toolchain() { + let temp_dir = std::env::temp_dir().join("infs_test_lsp_no_default"); + let _ = std::fs::remove_dir_all(&temp_dir); + std::fs::create_dir_all(&temp_dir).unwrap(); + let paths = ToolchainPaths::with_root(temp_dir.clone()); + + let check = inference_lsp_check(&paths, &lsp_binary_name(), None); + assert_eq!(check.status, DoctorCheckStatus::Ok); + assert_eq!(check.message, "No toolchain installed"); + + std::fs::remove_dir_all(&temp_dir).ok(); + } + + #[test] + fn inference_lsp_check_ok_when_toolchain_bundles_server() { + let temp_dir = std::env::temp_dir().join("infs_test_lsp_present"); + let _ = std::fs::remove_dir_all(&temp_dir); + let paths = ToolchainPaths::with_root(temp_dir.clone()); + let binary = lsp_binary_name(); + + std::fs::create_dir_all(paths.toolchain_dir("0.2.0")).unwrap(); + std::fs::write(paths.binary_path("0.2.0", &binary), b"lsp").unwrap(); + paths.set_default_version("0.2.0").unwrap(); + + let check = inference_lsp_check(&paths, &binary, None); + assert_eq!(check.status, DoctorCheckStatus::Ok); + assert!(check.message.starts_with("Found at")); + assert!(!check.message.contains("also on PATH")); + + std::fs::remove_dir_all(&temp_dir).ok(); + } + + #[test] + fn inference_lsp_check_notes_path_hit_when_present() { + let temp_dir = std::env::temp_dir().join("infs_test_lsp_present_path"); + let _ = std::fs::remove_dir_all(&temp_dir); + let paths = ToolchainPaths::with_root(temp_dir.clone()); + let binary = lsp_binary_name(); + + std::fs::create_dir_all(paths.toolchain_dir("0.2.0")).unwrap(); + std::fs::write(paths.binary_path("0.2.0", &binary), b"lsp").unwrap(); + paths.set_default_version("0.2.0").unwrap(); + + let hit = Path::new("/usr/local/bin/inference-lsp"); + let check = inference_lsp_check(&paths, &binary, Some(hit)); + assert_eq!(check.status, DoctorCheckStatus::Ok); + assert!(check.message.contains("also on PATH at /usr/local/bin/inference-lsp")); + + std::fs::remove_dir_all(&temp_dir).ok(); + } + + #[test] + fn inference_lsp_check_warns_when_toolchain_predates_bundling() { + let temp_dir = std::env::temp_dir().join("infs_test_lsp_absent"); + let _ = std::fs::remove_dir_all(&temp_dir); + let paths = ToolchainPaths::with_root(temp_dir.clone()); + + // Default toolchain exists but does not bundle inference-lsp. + std::fs::create_dir_all(paths.toolchain_dir("0.1.0")).unwrap(); + paths.set_default_version("0.1.0").unwrap(); + + let check = inference_lsp_check(&paths, &lsp_binary_name(), None); + assert_eq!(check.status, DoctorCheckStatus::Warning); + assert!(check.message.contains("does not include inference-lsp")); + assert!(check.message.contains("0.1.0")); + + std::fs::remove_dir_all(&temp_dir).ok(); + } + + #[test] + fn inference_lsp_check_warns_but_notes_path_fallback() { + let temp_dir = std::env::temp_dir().join("infs_test_lsp_absent_path"); + let _ = std::fs::remove_dir_all(&temp_dir); + let paths = ToolchainPaths::with_root(temp_dir.clone()); + + std::fs::create_dir_all(paths.toolchain_dir("0.1.0")).unwrap(); + paths.set_default_version("0.1.0").unwrap(); + + let hit = Path::new("/opt/tools/inference-lsp"); + let check = inference_lsp_check(&paths, &lsp_binary_name(), Some(hit)); + assert_eq!(check.status, DoctorCheckStatus::Warning); + assert!(check.message.contains("does not include inference-lsp")); + assert!(check.message.contains("a copy is available on PATH at /opt/tools/inference-lsp")); + + std::fs::remove_dir_all(&temp_dir).ok(); + } } diff --git a/apps/infs/src/toolchain/paths.rs b/apps/infs/src/toolchain/paths.rs index dd37e51f..1d8530ca 100644 --- a/apps/infs/src/toolchain/paths.rs +++ b/apps/infs/src/toolchain/paths.rs @@ -272,9 +272,16 @@ pub struct ToolchainPaths { } impl ToolchainPaths { - /// Name of the binary managed by the toolchain. + /// Name of the primary binary managed by the toolchain. Every toolchain + /// archive contains it, so a missing copy is always an error. pub const MANAGED_BINARY: &str = "infc"; + /// Additional binaries newer toolchains bundle alongside [`Self::MANAGED_BINARY`] + /// and symlink into `bin/` when present. Toolchains released before the + /// bundling lack these, so a missing optional binary is silently skipped + /// rather than treated as an error. + pub const OPTIONAL_MANAGED_BINARIES: &[&str] = &["inference-lsp"]; + /// Creates a new `ToolchainPaths` instance. /// /// The root directory is determined by: @@ -610,7 +617,11 @@ impl ToolchainPaths { /// Updates symlinks in the bin directory to point to the specified version. /// - /// Creates a symlink for the `infc` binary. + /// Creates a symlink for the `infc` binary, and for each optional managed + /// binary that the selected toolchain bundles. Optional binaries absent + /// from the toolchain (e.g. an older version predating the bundling) are + /// skipped, and any stale symlink left over from a version that did + /// include them is removed so `bin/` reflects the selected toolchain. /// /// # Errors /// @@ -625,29 +636,43 @@ impl ToolchainPaths { let binary = format!("{}{ext}", Self::MANAGED_BINARY); self.create_symlink(version, &binary)?; + for optional in Self::OPTIONAL_MANAGED_BINARIES { + let binary = format!("{optional}{ext}"); + if self.binary_path(version, &binary).exists() { + self.create_symlink(version, &binary)?; + } else { + self.remove_symlink(&binary)?; + } + } + Ok(()) } - /// Removes the symlink from the bin directory. + /// Removes the symlinks from the bin directory. /// - /// Removes the symlink for the `infc` binary. + /// Removes the symlink for the `infc` binary and for every optional + /// managed binary. Removing a symlink that does not exist is a no-op. /// /// # Errors /// - /// Returns an error if the symlink cannot be removed. + /// Returns an error if a symlink cannot be removed. pub fn remove_symlinks(&self) -> Result<()> { let platform = crate::toolchain::Platform::detect()?; let ext = platform.executable_extension(); - let binary = format!("{}{ext}", Self::MANAGED_BINARY); - self.remove_symlink(&binary)?; + for name in Self::managed_binary_names() { + let binary = format!("{name}{ext}"); + self.remove_symlink(&binary)?; + } Ok(()) } /// Checks if symlinks in the bin directory are valid (point to existing binaries). /// - /// Returns a list of binary names that have broken symlinks. + /// Returns a list of binary names that have broken symlinks. A managed + /// binary with no symlink at all is not reported: optional binaries are + /// legitimately absent when the default toolchain predates their bundling. #[must_use = "returns list of broken symlinks without side effects"] pub fn validate_symlinks(&self) -> Vec { let Ok(platform) = crate::toolchain::Platform::detect() else { @@ -656,15 +681,23 @@ impl ToolchainPaths { let ext = platform.executable_extension(); let mut broken = Vec::new(); - let binary = format!("{}{ext}", Self::MANAGED_BINARY); - let symlink_path = self.symlink_path(&binary); - - if symlink_path.symlink_metadata().is_ok() && !symlink_path.exists() { - broken.push(binary); + for name in Self::managed_binary_names() { + let binary = format!("{name}{ext}"); + let symlink_path = self.symlink_path(&binary); + if symlink_path.symlink_metadata().is_ok() && !symlink_path.exists() { + broken.push(binary); + } } broken } + /// Iterates over every managed binary name, primary first, then the + /// optional binaries in declaration order. + fn managed_binary_names() -> impl Iterator { + std::iter::once(Self::MANAGED_BINARY) + .chain(Self::OPTIONAL_MANAGED_BINARIES.iter().copied()) + } + /// Repairs broken symlinks by updating them to point to the default version, /// or removing them if no valid default exists. /// @@ -943,6 +976,14 @@ mod tests { assert_eq!(ToolchainPaths::MANAGED_BINARY, "infc"); } + #[test] + fn optional_managed_binaries_contains_inference_lsp() { + assert!( + ToolchainPaths::OPTIONAL_MANAGED_BINARIES.contains(&"inference-lsp"), + "inference-lsp must be a managed optional binary" + ); + } + #[test] fn binary_path_returns_toolchain_root_path() { let temp_dir = env::temp_dir().join("infs_test_binary_path"); @@ -984,6 +1025,122 @@ mod tests { std::fs::remove_dir_all(&temp_dir).ok(); } + /// Writes a fake executable binary at `path`, marking it executable on Unix + /// so symlink resolution treats it as a real target. + fn write_stub_binary(path: &Path) { + std::fs::write(path, b"fake binary").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + } + + /// Returns the primary and optional managed binary file names for the + /// running platform (with any executable extension applied). + fn managed_binary_file_names() -> (String, String) { + let ext = crate::toolchain::Platform::detect() + .unwrap() + .executable_extension(); + ( + format!("{}{ext}", ToolchainPaths::MANAGED_BINARY), + format!("inference-lsp{ext}"), + ) + } + + #[test] + fn update_symlinks_links_optional_binary_when_present() { + let temp_dir = env::temp_dir().join("infs_test_update_symlinks_opt_present"); + let _ = std::fs::remove_dir_all(&temp_dir); + let paths = ToolchainPaths::with_root(temp_dir.clone()); + + let toolchain_dir = paths.toolchain_dir("0.2.0"); + std::fs::create_dir_all(&toolchain_dir).unwrap(); + std::fs::create_dir_all(&paths.bin).unwrap(); + + let (infc, lsp) = managed_binary_file_names(); + write_stub_binary(&toolchain_dir.join(&infc)); + write_stub_binary(&toolchain_dir.join(&lsp)); + + paths.update_symlinks("0.2.0").unwrap(); + + assert!(paths.symlink_path(&infc).exists(), "infc symlink should exist"); + assert!( + paths.symlink_path(&lsp).exists(), + "inference-lsp symlink should exist when the toolchain bundles it" + ); + assert!( + paths.validate_symlinks().is_empty(), + "both symlinks should resolve to real binaries" + ); + + std::fs::remove_dir_all(&temp_dir).ok(); + } + + #[test] + fn update_symlinks_skips_optional_binary_when_absent() { + let temp_dir = env::temp_dir().join("infs_test_update_symlinks_opt_absent"); + let _ = std::fs::remove_dir_all(&temp_dir); + let paths = ToolchainPaths::with_root(temp_dir.clone()); + + let toolchain_dir = paths.toolchain_dir("0.1.0"); + std::fs::create_dir_all(&toolchain_dir).unwrap(); + std::fs::create_dir_all(&paths.bin).unwrap(); + + let (infc, lsp) = managed_binary_file_names(); + // Only the primary binary is present (older toolchain, no bundled LSP). + write_stub_binary(&toolchain_dir.join(&infc)); + + // A missing optional binary must not turn update_symlinks into an error. + paths.update_symlinks("0.1.0").unwrap(); + + assert!(paths.symlink_path(&infc).exists(), "infc symlink should exist"); + assert!( + paths.symlink_path(&lsp).symlink_metadata().is_err(), + "no inference-lsp symlink should be created when the toolchain lacks it" + ); + + std::fs::remove_dir_all(&temp_dir).ok(); + } + + #[test] + fn update_symlinks_removes_stale_optional_symlink_on_switch() { + let temp_dir = env::temp_dir().join("infs_test_update_symlinks_switch"); + let _ = std::fs::remove_dir_all(&temp_dir); + let paths = ToolchainPaths::with_root(temp_dir.clone()); + std::fs::create_dir_all(&paths.bin).unwrap(); + + let (infc, lsp) = managed_binary_file_names(); + + // Version that bundles the LSP server. + let with_lsp = paths.toolchain_dir("0.2.0"); + std::fs::create_dir_all(&with_lsp).unwrap(); + write_stub_binary(&with_lsp.join(&infc)); + write_stub_binary(&with_lsp.join(&lsp)); + paths.update_symlinks("0.2.0").unwrap(); + assert!( + paths.symlink_path(&lsp).exists(), + "inference-lsp symlink should exist for the bundling version" + ); + + // Version that predates the bundling. + let without_lsp = paths.toolchain_dir("0.1.0"); + std::fs::create_dir_all(&without_lsp).unwrap(); + write_stub_binary(&without_lsp.join(&infc)); + paths.update_symlinks("0.1.0").unwrap(); + + assert!( + paths.symlink_path(&infc).exists(), + "infc symlink should survive the switch" + ); + assert!( + paths.symlink_path(&lsp).symlink_metadata().is_err(), + "stale inference-lsp symlink must be removed when switching to a version without it" + ); + + std::fs::remove_dir_all(&temp_dir).ok(); + } + #[test] fn remove_symlinks_removes_managed_binary_symlink() { let temp_dir = env::temp_dir().join("infs_test_remove_symlinks"); @@ -1019,6 +1176,35 @@ mod tests { std::fs::remove_dir_all(&temp_dir).ok(); } + #[test] + fn remove_symlinks_removes_optional_binary_symlink() { + let temp_dir = env::temp_dir().join("infs_test_remove_symlinks_optional"); + let _ = std::fs::remove_dir_all(&temp_dir); + let paths = ToolchainPaths::with_root(temp_dir.clone()); + + let toolchain_dir = paths.toolchain_dir("0.2.0"); + std::fs::create_dir_all(&toolchain_dir).unwrap(); + std::fs::create_dir_all(&paths.bin).unwrap(); + + let (infc, lsp) = managed_binary_file_names(); + write_stub_binary(&toolchain_dir.join(&infc)); + write_stub_binary(&toolchain_dir.join(&lsp)); + paths.update_symlinks("0.2.0").unwrap(); + assert!(paths.symlink_path(&lsp).exists()); + + paths.remove_symlinks().unwrap(); + assert!( + paths.symlink_path(&infc).symlink_metadata().is_err(), + "infc symlink should be removed" + ); + assert!( + paths.symlink_path(&lsp).symlink_metadata().is_err(), + "inference-lsp symlink should be removed" + ); + + std::fs::remove_dir_all(&temp_dir).ok(); + } + #[test] fn validate_symlinks_returns_empty_when_no_broken_links() { let temp_dir = env::temp_dir().join("infs_test_validate_no_broken"); diff --git a/apps/infs/tests/cli_integration.rs b/apps/infs/tests/cli_integration.rs index 5e4a1daf..bfdf3c5a 100644 --- a/apps/infs/tests/cli_integration.rs +++ b/apps/infs/tests/cli_integration.rs @@ -1669,7 +1669,8 @@ fn doctor_shows_all_checks() { .stdout(predicate::str::contains("Platform")) .stdout(predicate::str::contains("Toolchain directory")) .stdout(predicate::str::contains("Default toolchain")) - .stdout(predicate::str::contains("infc")); + .stdout(predicate::str::contains("infc")) + .stdout(predicate::str::contains("inference-lsp")); } /// Verifies that `infs doctor` output respects the VS Code extension's line contract. diff --git a/apps/lsp/Cargo.toml b/apps/lsp/Cargo.toml index 1de737ff..e9d914f6 100644 --- a/apps/lsp/Cargo.toml +++ b/apps/lsp/Cargo.toml @@ -10,3 +10,11 @@ description = "Inference Language Server Protocol implementation" [[bin]] name = "inference-lsp" path = "src/main.rs" + +[dependencies] +lsp-server = "=0.8.0" +lsp-types = "=0.97.0" +serde_json = "1.0" +anyhow.workspace = true +rustc-hash.workspace = true +inference-ide.workspace = true diff --git a/apps/lsp/README.md b/apps/lsp/README.md index 140b0f44..680b5479 100644 --- a/apps/lsp/README.md +++ b/apps/lsp/README.md @@ -1,43 +1,283 @@ -# inference-lsp - Inference Language Server +# inference-lsp -Language Server Protocol implementation for the Inference programming language. +The Language Server Protocol server for Inference. A synchronous, +single-threaded stdio binary built on `lsp-server` that answers diagnostics, +hover, goto-definition, completion, document symbols, and inlay hints for +`.inf` source, delegating all analysis to the `ide` stack and confining every +protocol concern (framing, position encoding, URIs) to this crate. -## Status +## Where It Sits -Skeleton implementation. See the LSP plan for the full feature roadmap. +This is the top of the IDE stack — the only crate here that speaks JSON-RPC +and `lsp-types`. Everything below it speaks Rust structs, byte offsets, and +`Path`s: -## Planned Features +``` +apps/lsp (this crate) + | lsp-server 0.8 stdio loop, lsp-types 0.97 protocol values + | URI <-> Path, byte offset <-> LSP Position conversion + v +ide/ide AnalysisHost / Analysis: feature API, editor-terminology PODs + | + v +ide/ide-db RootDatabase: per-open-file FileAnalysis, closure-aware invalidation + | \ + v \-> core/inference, core/analysis, core/type-checker, core/ast, core/parser +ide/base-db LineIndex, TextRange, LineCol, FilePosition, FileRange + | + v +ide/vfs FileId interning + open-document overlay (no file I/O) +``` + +Only `ide-db` depends on the compiler crates; `apps/lsp` and `ide/ide` never +name a compiler type. A change to a compiler internal (a new AST node kind, a +new type-checker error variant) is therefore contained to `ide-db` unless it +also needs a new editor-facing feature. + +## Why Single-Threaded + +`inference_type_checker::typed_context::TypedContext` — which every +`FileAnalysis` holds — is `!Send`. `ide::Analysis` methods take `&mut self` for +exactly this reason: the whole stack is designed around one thread owning one +`AnalysisHost` and answering one LSP message at a time. `server::run` reflects +this directly: it is a plain `for message in &connection.receiver` loop with no +worker pool, no `tokio`, and no interior mutability wider than what +`ServerState` itself needs. This is a deliberate v1 simplicity trade-off, not +an oversight — a request that is slow to answer (a large file's full +re-analysis) blocks the next message, but every analysis here is bounded by one +open file's import closure, not a whole workspace. + +## Capability Surface + +Advertised once, in `capabilities::server_capabilities()`, during the +`initialize` handshake: + +| Capability | Value | +|---|---| +| `textDocumentSync` | `Full` — every `didChange` carries the whole new document text, not incremental edits | +| `hoverProvider` | `true` | +| `definitionProvider` | `true` | +| `completionProvider` | trigger characters `.` and `:`, `resolveProvider: false` | +| `documentSymbolProvider` | `true` (hierarchical or flat, negotiated — see below) | +| `inlayHintProvider` | `true` | +| `positionEncoding` | left unset, so the client falls back to the LSP-default UTF-16 — the only encoding this server converts to or from | + +Full-text sync is the deliberate choice for v1: `AnalysisHost::change_document` +takes the complete new text and re-derives everything from it, so there is no +incremental-edit bookkeeping to keep consistent with the analysis cache — the +closure-aware invalidation in `ide-db` already makes a full reanalysis cheap +enough (it only touches analyses whose import closure includes the changed +path). + +Document symbols are negotiated: `server::hierarchical_symbol_support` reads +`initialize`'s `textDocument.documentSymbol.hierarchicalDocumentSymbolSupport` +capability, and the server replies with a nested `DocumentSymbol` tree when the +client supports it or a flattened `SymbolInformation` list (each carrying its +enclosing symbol's name as `containerName`) when it does not. + +## Message Loop + +`server::ServerState` holds the `AnalysisHost` plus a map of open documents +(`Uri -> Document { path, version }`) and turns one request into one +`Response`, or one notification into the diagnostics to publish — with no I/O +of its own, which is what makes it directly unit-testable (see `server.rs`'s +own tests). `server::run` owns the transport: it reads messages off +`connection.receiver`, handles the `shutdown`/`exit` handshake inline, routes +everything else through `ServerState`, and writes results back. An unknown +request method is `MethodNotFound`; params that fail to deserialize are +`InvalidParams` — neither ever panics or disturbs the loop, so one malformed +request cannot take the server down. + +The shutdown handshake is handled in the loop rather than delegated to +`lsp-server`'s `Connection::handle_shutdown` (which consumes the next message +itself and turns anything but `exit` into a fatal protocol error): a `shutdown` +request is answered and flips a `shutting_down` flag, after which every further +request is answered with `InvalidRequest` (`-32600`, the spec's behaviour for a +request received between `shutdown` and `exit`) and every notification but +`exit` is dropped, until `exit` ends the loop. + +A single document notification republishes **every** open document, not just +the notified one. Editing one file can invalidate another open document whose +import closure includes it (`ide-db` drops exactly those analyses), and the +client would otherwise keep rendering the dependent's stale diagnostics. This +is bounded: an unaffected document's analysis is still memoized, so its +republish recomputes nothing, and an editor keeps only a handful of files open. + +`handlers.rs` holds one function per LSP method. Each resolves the document's +path from its URI, converts the LSP position(s) to a byte offset using the +*correct* file's `LineIndex` (a cross-file goto-definition target is converted +with the target file's own index, fetched via `Analysis::closure_line_index` +without re-analyzing that file as its own entry), asks the `ide` layer, and +converts the answer back with `convert.rs`. A URI this server cannot map to a +file — a non-`file` scheme, an untitled buffer — yields a null result and no +diagnostics, never a panic. + +Nothing in this crate ever writes to stdout except the framed JSON-RPC +messages themselves; all logging goes to stderr (see `main.rs`). This is +required by the stdio transport — anything else on stdout corrupts the +protocol stream — and is asserted directly by an end-to-end test (below). -### Phase 1: Diagnostics -- Parse error reporting -- Type error reporting -- File synchronization (open/change/close) +## Resilience and Known Limitations -### Phase 2: Core IDE Features -- Go to definition -- Hover information -- Document symbols +- **Deep-nesting stack headroom.** The analysis pipeline (type-checker, + analysis passes) recurses with the input's nesting depth, so a pathological + or generated document could overflow the default stack and abort the whole + process — losing every open document's state. `main.rs` runs the server loop + on a dedicated thread with a 64 MiB stack (mirroring rust-analyzer), which + clears realistic deep nesting by a wide margin (a document that overflowed the + default main-thread stack at ~800 levels survives past 5000 with the larger + stack). A stack overflow *aborts* rather than unwinds, so a worker thread + cannot catch it; the mitigation is headroom, not isolation. An input deep + enough to exhaust even 64 MiB would still abort — bounding the recursion in + the shared pipeline (out of scope for this crate) would be the complete fix. -### Phase 3: Advanced Features -- Completions -- Find references -- Rename symbol -- Semantic tokens +- **A malformed transport frame is fatal.** `lsp-server`'s stdio reader treats + any framing or body parse failure — an empty body (`Content-Length: 0`), a + non-JSON body, or an unparsable `Content-Length` — as fatal to the connection. + It owns the stdin reader thread and exposes no seam to answer JSON-RPC + `-32700` and resync, so `io_threads.join()` surfaces the failure and the + process exits rather than skipping the bad frame. Recovering would require + replacing `Connection::stdio()` with a vendored reader; rust-analyzer accepts + the same limitation on `lsp-server`, and a well-behaved client does not emit + malformed frames, so this is documented rather than worked around. -### Custom LSP Extensions -- `inference/viewOutput` - Live WAT/Rocq output -- `inference/viewNondet` - Non-deterministic block visualization +## URI Handling -## Architecture +`uri.rs` is the one place in the server that reasons about `file://` +percent-encoding and Windows drive letters (`lsp-types` models a URI with +`fluent-uri`, which offers no path helpers of its own). It supports local +`file://` URIs with an empty or `localhost` authority only; a non-`file` scheme, +a remote/UNC authority, or a URI carrying a query or fragment maps to `None`, +which every caller treats as "not a document this server can analyze" rather +than an error. A query/fragment is *rejected* rather than stripped: a raw `?` or +`#` cannot be a literal path byte (a literal one arrives percent-encoded), so a +URI carrying one is not a plain document spelling and answering from a +`?`-truncated path would only mint a wrong document identity. -This crate is a thin binary wrapper using `tower-lsp` that orchestrates: -- `ide/ide` - High-level IDE API -- `ide/ide-db` - Semantic database -- `ide/base-db` - Source file handling -- `ide/vfs` - Virtual file system +Drive-letter handling is host-shaped, because the `/X:/…` form is a Windows +drive path *only on Windows* — on POSIX it is a genuine absolute path whose +first component is a directory named `X:`. The string core takes an explicit +`windows` flag (`cfg!(windows)` in the public wrappers, a parameter so both +behaviours stay testable from either host): -## Building +- On **Windows**, `file:///c%3A/…` and `file:///C:/…` both canonicalize to + `C:/…` (leading slash dropped, drive letter upper-cased to the std canonical + spelling), so a mixed-case client spelling names one interned document rather + than two; and a backslash in a path is normalized to `/`. +- On **POSIX**, `/c:/…` maps to itself (still absolute, case preserved) and a + backslash is an ordinary filename byte (percent-encoded `%5C`), so a real file + named `a\b.inf` round-trips exactly. -```bash -cargo build -p inference-lsp +Round-tripped forms include: POSIX absolute paths, paths containing spaces or +non-ASCII characters (percent-encoded as raw UTF-8 bytes, so a multi-byte +character split across several `%XX` escapes still decodes correctly), Windows +drive paths with the URI's required leading slash (`C:/Users/x` ⇄ +`file:///C:/Users/x`), and the percent-encoded drive colon some clients (e.g. +VS Code) send (`file:///c%3A/...`). + +## Wiring an Editor + +Any LSP client that can spawn a child process and speak stdio JSON-RPC can +drive this server. The essential configuration, in client-agnostic form: + +```jsonc +{ + "command": "inference-lsp", + "args": [], + // No CLI flags: the server takes no arguments and speaks LSP purely over + // stdio, logging only to stderr. + "filetypes": ["inference"], + "rootUri": null, // no workspace-wide indexing: each opened file is + // analyzed as its own project entry (see ide-db) + "initializationOptions": {}, + "settings": {} +} ``` + +Practical notes for wiring a real client: + +- Register the server for `*.inf` files with language id `"inference"` — this + is the id the server's own e2e test suite and unit tests use for `didOpen`. +- The server advertises `TextDocumentSyncKind::Full`, so a client configured + for incremental sync must still be told to send full-document + `contentChanges` for this server (most LSP client libraries expose a sync + kind negotiated automatically from server capabilities; this is rarely a + manual setting). +- No `rootUri` / workspace-folder behavior is required or used: since every + file is analyzed as its own entry, the server works identically whether the + client provides a workspace root or opens a single loose file. +- Declaring + `textDocument.documentSymbol.hierarchicalDocumentSymbolSupport: true` in the + client's `initialize` capabilities gets the nested `DocumentSymbol` tree + instead of the flattened list. + +## End-to-End Test Suite + +`tests/e2e.rs` spawns the actual compiled `inference-lsp` binary (via +`env!("CARGO_BIN_EXE_inference-lsp")`) and drives a full protocol session +through a minimal hand-written client (`tests/harness/mod.rs`), asserting on +raw JSON rather than a typed re-encoding of it — so a test failure reflects +what a real client would actually see on the wire. Every read is bounded by a +10-second timeout, so a regression that hangs the server fails the test +instead of stalling the run; fixtures live in per-test unique temp +directories, never at a filesystem root and never inside the repo, so the +suite is parallel-safe. + +The suite is organized into twenty-one scenarios: + +1. **Initialize handshake** — the exact capability set is advertised, no + `positionEncoding` is negotiated, no `serverInfo` is sent +2. **`didOpen` on a clean file** — publishes an empty diagnostics set +3. **`didOpen` with a syntax error** — publishes a `"syntax"` diagnostic +4. **`didChange` fixing the error** — diagnostics clear +5. **`didChange` introducing a type error** — the new diagnostic carries a + location +6. **An analysis-rule finding (A041)** — a duplicate local surfaces with the + rule's code +7. **Hover** — over a local variable's type, and over `forall` (explains the + non-det construct) +8. **Goto-definition, same file** — reaches a same-file function +9. **Cross-file goto-definition** — importing a sibling file *on disk* + resolves into it +10. **Missing import** — reported on the `use` directive +11. **`documentSymbol`** — both the hierarchical tree and the flattened form + for a non-hierarchical client +12. **Completion** — top-level keywords/defs, and member-only completions + after `.` +13. **Inlay hints** — every non-det construct in a file gets annotated +14. **UTF-16 positions** — positions resolve correctly past a multi-byte + string literal +15. **`didClose`** — clears the document's diagnostics +16. **Robustness** — an unknown method, malformed params, and a non-`file` URI + each fail gracefully and leave the server usable for the next request +17. **Shutdown / exit** — both the well-behaved sequence and `exit` without a + prior `shutdown` +18. **Stdout hygiene** — a full session (open, edit, hover, goto, complete, + inlay hints) writes *only* well-framed protocol to stdout — nothing else + ever leaks onto the transport +19. **Cross-file republish** — editing an imported file republishes the open + dependent document, so its diagnostics never go stale +20. **Post-shutdown request** — a request arriving after `shutdown` is answered + `InvalidRequest` (`-32600`), and the server still exits cleanly on `exit` +21. **Query/fragment URI** — a `file://` URI carrying a query is ignored, never + interned as a garbage path, and the server stays responsive + +Unit tests for the protocol-adjacent logic live alongside their modules: +`capabilities.rs` (the advertised JSON shape), `convert.rs` (every PDO ⇄ +`lsp_types` mapping, including UTF-16/surrogate-pair round-trips), `uri.rs` +(the URI ⇄ path table above), and `server.rs` (routing, error codes, and the +did-open/did-close diagnostics-publish contract), plus `handlers.rs`'s own +integration with `ServerState`. + +``` +cargo test -p inference-lsp +``` + +## Related Resources + +- [`ide/ide`](../../ide/ide/README.md) — the feature API this crate's handlers call +- [`ide/ide-db`](../../ide/ide-db/README.md) — per-file analysis and closure-aware invalidation +- [`ide/base-db`](../../ide/base-db/README.md) — `LineIndex`, the byte-offset ⇄ LSP-position bridge +- [`ide/vfs`](../../ide/vfs/README.md) — the open-document overlay `AnalysisHost` wraps +- [Language Server Protocol Specification](https://microsoft.github.io/language-server-protocol/) — the wire protocol this crate implements +- [`lsp-server`](https://docs.rs/lsp-server) / [`lsp-types`](https://docs.rs/lsp-types) — the crates this server is built on diff --git a/apps/lsp/src/capabilities.rs b/apps/lsp/src/capabilities.rs new file mode 100644 index 00000000..0994c242 --- /dev/null +++ b/apps/lsp/src/capabilities.rs @@ -0,0 +1,55 @@ +//! The capability set this server advertises during the initialize handshake. + +use lsp_types::{ + CompletionOptions, HoverProviderCapability, OneOf, ServerCapabilities, + TextDocumentSyncCapability, TextDocumentSyncKind, +}; + +/// The server's advertised capabilities: full-text sync plus hover, definition, +/// completion (triggered on `.` and `:`), document symbols, and inlay hints. +/// +/// `position_encoding` is left unset, so the client uses the LSP default of +/// UTF-16 — the only encoding this server converts to (see the `convert` module). +#[must_use = "capabilities are only useful when sent in the initialize result"] +pub(crate) fn server_capabilities() -> ServerCapabilities { + ServerCapabilities { + text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)), + hover_provider: Some(HoverProviderCapability::Simple(true)), + definition_provider: Some(OneOf::Left(true)), + completion_provider: Some(CompletionOptions { + resolve_provider: Some(false), + trigger_characters: Some(vec![".".to_owned(), ":".to_owned()]), + ..CompletionOptions::default() + }), + document_symbol_provider: Some(OneOf::Left(true)), + inlay_hint_provider: Some(OneOf::Left(true)), + ..ServerCapabilities::default() + } +} + +#[cfg(test)] +mod tests { + use super::server_capabilities; + + #[test] + fn advertises_the_v1_feature_set_as_json() { + let value = serde_json::to_value(server_capabilities()).expect("capabilities serialize"); + + // Full-text sync is advertised as the numeric kind 1. + assert_eq!(value["textDocumentSync"], serde_json::json!(1)); + assert_eq!(value["hoverProvider"], serde_json::json!(true)); + assert_eq!(value["definitionProvider"], serde_json::json!(true)); + assert_eq!(value["documentSymbolProvider"], serde_json::json!(true)); + assert_eq!(value["inlayHintProvider"], serde_json::json!(true)); + + let completion = &value["completionProvider"]; + assert_eq!(completion["resolveProvider"], serde_json::json!(false)); + assert_eq!( + completion["triggerCharacters"], + serde_json::json!([".", ":"]) + ); + + // No position-encoding negotiation: the client falls back to UTF-16. + assert!(value.get("positionEncoding").is_none()); + } +} diff --git a/apps/lsp/src/convert.rs b/apps/lsp/src/convert.rs new file mode 100644 index 00000000..4a23dc03 --- /dev/null +++ b/apps/lsp/src/convert.rs @@ -0,0 +1,507 @@ +//! Conversions from `ide`'s plain-old-data answers to `lsp-types` protocol +//! values. +//! +//! The IDE layer speaks byte offsets; the protocol speaks 0-based UTF-16 +//! line/character. Every position crosses that boundary here, using a +//! [`LineIndex`](inference_ide::LineIndex) built for the *right* file — a +//! cross-file goto-definition target is converted with the target file's index, +//! not the requested document's. The severity and kind mappings match every +//! `ide` variant explicitly, so a new one is a compile error here rather than a +//! silent default on the wire. + +use inference_ide as ide; +use lsp_types::{ + CompletionItem, CompletionItemKind, Diagnostic, DiagnosticSeverity, DocumentSymbol, Hover, + HoverContents, InlayHint, InlayHintKind, InlayHintLabel, Location, MarkupContent, MarkupKind, + NumberOrString, Position, Range, SymbolInformation, SymbolKind, Uri, +}; + +/// The LSP position of a byte `offset` within the file `index` describes. +pub(crate) fn position(index: &ide::LineIndex, offset: u32) -> Position { + let line_col = index.line_col(offset); + Position { + line: line_col.line, + character: line_col.character, + } +} + +/// The LSP range of an `ide` byte range within the file `index` describes. +pub(crate) fn range(index: &ide::LineIndex, range: ide::TextRange) -> Range { + Range { + start: position(index, range.start), + end: position(index, range.end), + } +} + +/// The byte offset of an LSP position, or `None` when the position's line is out +/// of range for the file `index` describes. +pub(crate) fn offset(index: &ide::LineIndex, position: Position) -> Option { + index.offset(ide::LineCol { + line: position.line, + character: position.character, + }) +} + +/// The `ide` byte range of an LSP range, or `None` when either endpoint's line is +/// out of range. +pub(crate) fn text_range(index: &ide::LineIndex, range: Range) -> Option { + Some(ide::TextRange { + start: offset(index, range.start)?, + end: offset(index, range.end)?, + }) +} + +pub(crate) fn severity(severity: ide::Severity) -> DiagnosticSeverity { + match severity { + ide::Severity::Error => DiagnosticSeverity::ERROR, + ide::Severity::Warning => DiagnosticSeverity::WARNING, + ide::Severity::Info => DiagnosticSeverity::INFORMATION, + } +} + +pub(crate) fn diagnostic(index: &ide::LineIndex, diagnostic: ide::Diagnostic) -> Diagnostic { + Diagnostic { + range: range(index, diagnostic.range), + severity: Some(severity(diagnostic.severity)), + code: diagnostic.code.map(NumberOrString::String), + source: Some("inference".to_owned()), + message: diagnostic.message, + ..Diagnostic::default() + } +} + +pub(crate) fn symbol_kind(kind: ide::SymbolKind) -> SymbolKind { + match kind { + ide::SymbolKind::Function => SymbolKind::FUNCTION, + ide::SymbolKind::Struct => SymbolKind::STRUCT, + ide::SymbolKind::Enum => SymbolKind::ENUM, + ide::SymbolKind::EnumVariant => SymbolKind::ENUM_MEMBER, + ide::SymbolKind::Field => SymbolKind::FIELD, + ide::SymbolKind::Method => SymbolKind::METHOD, + // A spec is a set of laws over a type, closest to an interface/trait. + ide::SymbolKind::Spec => SymbolKind::INTERFACE, + ide::SymbolKind::Constant => SymbolKind::CONSTANT, + ide::SymbolKind::TypeAlias => SymbolKind::TYPE_PARAMETER, + } +} + +/// A hierarchical document symbol and its nested children. +pub(crate) fn document_symbol( + index: &ide::LineIndex, + symbol: ide::DocumentSymbol, +) -> DocumentSymbol { + let children = if symbol.children.is_empty() { + None + } else { + Some( + symbol + .children + .into_iter() + .map(|child| document_symbol(index, child)) + .collect(), + ) + }; + #[allow(deprecated)] // `deprecated` is a required field; we always leave it unset. + DocumentSymbol { + name: symbol.name, + detail: None, + kind: symbol_kind(symbol.kind), + tags: None, + deprecated: None, + range: range(index, symbol.range), + selection_range: range(index, symbol.selection_range), + children, + } +} + +/// A flat symbol record for a client that does not support the hierarchical +/// document-symbol response. `container` names the enclosing symbol, if any. +pub(crate) fn symbol_information( + index: &ide::LineIndex, + uri: &Uri, + container: Option<&str>, + symbol: &ide::DocumentSymbol, +) -> SymbolInformation { + #[allow(deprecated)] // `deprecated` is a required field; we always leave it unset. + SymbolInformation { + name: symbol.name.clone(), + kind: symbol_kind(symbol.kind), + tags: None, + deprecated: None, + location: Location { + uri: uri.clone(), + range: range(index, symbol.range), + }, + container_name: container.map(ToOwned::to_owned), + } +} + +pub(crate) fn hover(index: &ide::LineIndex, hover: ide::Hover) -> Hover { + Hover { + contents: HoverContents::Markup(MarkupContent { + kind: MarkupKind::Markdown, + value: hover.contents_markdown, + }), + range: Some(range(index, hover.range)), + } +} + +pub(crate) fn completion_item_kind(kind: ide::CompletionItemKind) -> CompletionItemKind { + match kind { + ide::CompletionItemKind::Keyword => CompletionItemKind::KEYWORD, + ide::CompletionItemKind::Function => CompletionItemKind::FUNCTION, + ide::CompletionItemKind::Struct => CompletionItemKind::STRUCT, + ide::CompletionItemKind::Enum => CompletionItemKind::ENUM, + ide::CompletionItemKind::Variable => CompletionItemKind::VARIABLE, + ide::CompletionItemKind::Field => CompletionItemKind::FIELD, + ide::CompletionItemKind::Method => CompletionItemKind::METHOD, + ide::CompletionItemKind::Constant => CompletionItemKind::CONSTANT, + ide::CompletionItemKind::Module => CompletionItemKind::MODULE, + ide::CompletionItemKind::Snippet => CompletionItemKind::SNIPPET, + } +} + +pub(crate) fn completion_item(item: ide::CompletionItem) -> CompletionItem { + CompletionItem { + label: item.label, + kind: Some(completion_item_kind(item.kind)), + detail: item.detail, + ..CompletionItem::default() + } +} + +pub(crate) fn inlay_hint_kind(kind: ide::InlayHintKind) -> InlayHintKind { + match kind { + // Both non-det annotations describe the meaning of a construct; the LSP + // vocabulary offers only Type and Parameter, and Type is the closer fit. + ide::InlayHintKind::NonDetBlock | ide::InlayHintKind::Uzumaki => InlayHintKind::TYPE, + } +} + +pub(crate) fn inlay_hint(index: &ide::LineIndex, hint: ide::InlayHint) -> InlayHint { + InlayHint { + position: position(index, hint.offset), + label: InlayHintLabel::String(hint.label), + kind: Some(inlay_hint_kind(hint.kind)), + text_edits: None, + tooltip: None, + padding_left: Some(true), + padding_right: None, + data: None, + } +} + +#[cfg(test)] +mod tests { + use std::str::FromStr; + + use inference_ide as ide; + use lsp_types::{ + CompletionItemKind, DiagnosticSeverity, HoverContents, InlayHintKind, InlayHintLabel, + MarkupKind, NumberOrString, Position, SymbolKind, Uri, + }; + + use super::{ + completion_item, completion_item_kind, diagnostic, document_symbol, hover, inlay_hint, + inlay_hint_kind, offset, position, range, severity, symbol_information, symbol_kind, + text_range, + }; + + fn index(text: &str) -> ide::LineIndex { + ide::LineIndex::new(text) + } + + #[test] + fn position_and_offset_round_trip_on_a_multibyte_line() { + // "é∀\n😀b": the astral emoji is a surrogate pair (two UTF-16 units). + let index = index("é∀\n😀b"); + // 'b' is byte offset 10, on line 1 after the surrogate pair -> column 2. + assert_eq!( + position(&index, 10), + Position { + line: 1, + character: 2 + } + ); + assert_eq!( + offset( + &index, + Position { + line: 1, + character: 2 + } + ), + Some(10) + ); + } + + #[test] + fn range_maps_both_endpoints() { + let index = index("ab\ncd"); + let converted = range(&index, ide::TextRange { start: 0, end: 4 }); + assert_eq!( + converted.start, + Position { + line: 0, + character: 0 + } + ); + assert_eq!( + converted.end, + Position { + line: 1, + character: 1 + } + ); + } + + #[test] + fn offset_past_end_of_line_clamps_but_out_of_range_line_is_none() { + let index = index("ab\ncd"); + assert_eq!( + offset( + &index, + Position { + line: 0, + character: 99 + } + ), + Some(2) + ); + assert_eq!( + offset( + &index, + Position { + line: 9, + character: 0 + } + ), + None + ); + } + + #[test] + fn text_range_is_none_when_an_endpoint_line_is_out_of_range() { + let index = index("ab\ncd"); + let good = lsp_types::Range { + start: Position { + line: 0, + character: 0, + }, + end: Position { + line: 1, + character: 1, + }, + }; + assert_eq!( + text_range(&index, good), + Some(ide::TextRange { start: 0, end: 4 }) + ); + let bad = lsp_types::Range { + start: Position { + line: 0, + character: 0, + }, + end: Position { + line: 9, + character: 0, + }, + }; + assert_eq!(text_range(&index, bad), None); + } + + #[test] + fn severity_maps_every_variant() { + assert_eq!(severity(ide::Severity::Error), DiagnosticSeverity::ERROR); + assert_eq!( + severity(ide::Severity::Warning), + DiagnosticSeverity::WARNING + ); + assert_eq!( + severity(ide::Severity::Info), + DiagnosticSeverity::INFORMATION + ); + } + + #[test] + fn diagnostic_carries_code_source_and_stripped_message() { + let index = index("fn f() {}"); + let converted = diagnostic( + &index, + ide::Diagnostic { + range: ide::TextRange { start: 3, end: 4 }, + severity: ide::Severity::Error, + code: Some("A041".to_owned()), + message: "already declared".to_owned(), + }, + ); + assert_eq!(converted.severity, Some(DiagnosticSeverity::ERROR)); + assert_eq!( + converted.code, + Some(NumberOrString::String("A041".to_owned())) + ); + assert_eq!(converted.source.as_deref(), Some("inference")); + assert_eq!(converted.message, "already declared"); + } + + #[test] + fn symbol_kind_maps_every_variant() { + assert_eq!(symbol_kind(ide::SymbolKind::Function), SymbolKind::FUNCTION); + assert_eq!(symbol_kind(ide::SymbolKind::Struct), SymbolKind::STRUCT); + assert_eq!(symbol_kind(ide::SymbolKind::Enum), SymbolKind::ENUM); + assert_eq!( + symbol_kind(ide::SymbolKind::EnumVariant), + SymbolKind::ENUM_MEMBER + ); + assert_eq!(symbol_kind(ide::SymbolKind::Field), SymbolKind::FIELD); + assert_eq!(symbol_kind(ide::SymbolKind::Method), SymbolKind::METHOD); + assert_eq!(symbol_kind(ide::SymbolKind::Spec), SymbolKind::INTERFACE); + assert_eq!(symbol_kind(ide::SymbolKind::Constant), SymbolKind::CONSTANT); + assert_eq!( + symbol_kind(ide::SymbolKind::TypeAlias), + SymbolKind::TYPE_PARAMETER + ); + } + + #[test] + fn completion_item_kind_maps_every_variant() { + let cases = [ + ( + ide::CompletionItemKind::Keyword, + CompletionItemKind::KEYWORD, + ), + ( + ide::CompletionItemKind::Function, + CompletionItemKind::FUNCTION, + ), + (ide::CompletionItemKind::Struct, CompletionItemKind::STRUCT), + (ide::CompletionItemKind::Enum, CompletionItemKind::ENUM), + ( + ide::CompletionItemKind::Variable, + CompletionItemKind::VARIABLE, + ), + (ide::CompletionItemKind::Field, CompletionItemKind::FIELD), + (ide::CompletionItemKind::Method, CompletionItemKind::METHOD), + ( + ide::CompletionItemKind::Constant, + CompletionItemKind::CONSTANT, + ), + (ide::CompletionItemKind::Module, CompletionItemKind::MODULE), + ( + ide::CompletionItemKind::Snippet, + CompletionItemKind::SNIPPET, + ), + ]; + for (input, expected) in cases { + assert_eq!(completion_item_kind(input), expected); + } + } + + #[test] + fn inlay_hint_kind_maps_every_variant() { + assert_eq!( + inlay_hint_kind(ide::InlayHintKind::NonDetBlock), + InlayHintKind::TYPE + ); + assert_eq!( + inlay_hint_kind(ide::InlayHintKind::Uzumaki), + InlayHintKind::TYPE + ); + } + + #[test] + fn hover_is_markdown_with_a_range() { + let index = index("fn f() {}"); + let converted = hover( + &index, + ide::Hover { + contents_markdown: "```inference\nfn f()\n```".to_owned(), + range: ide::TextRange { start: 3, end: 4 }, + }, + ); + let HoverContents::Markup(markup) = converted.contents else { + panic!("hover contents are markdown"); + }; + assert_eq!(markup.kind, MarkupKind::Markdown); + assert!(markup.value.contains("fn f()")); + assert!(converted.range.is_some()); + } + + #[test] + fn completion_item_preserves_label_and_detail() { + let converted = completion_item(ide::CompletionItem { + label: "helper".to_owned(), + kind: ide::CompletionItemKind::Function, + detail: Some("fn helper() -> i32".to_owned()), + }); + assert_eq!(converted.label, "helper"); + assert_eq!(converted.kind, Some(CompletionItemKind::FUNCTION)); + assert_eq!(converted.detail.as_deref(), Some("fn helper() -> i32")); + } + + #[test] + fn inlay_hint_carries_label_kind_and_position() { + let index = index("fn f() { forall { assert(true); } }"); + let converted = inlay_hint( + &index, + ide::InlayHint { + offset: 15, + label: "for all values".to_owned(), + kind: ide::InlayHintKind::NonDetBlock, + }, + ); + let InlayHintLabel::String(label) = converted.label else { + panic!("the inlay label is a plain string"); + }; + assert_eq!(label, "for all values"); + assert_eq!(converted.kind, Some(InlayHintKind::TYPE)); + assert_eq!( + converted.position, + Position { + line: 0, + character: 15 + } + ); + } + + #[test] + fn symbol_information_records_container_and_location() { + let index = index("struct P { x: i32; }"); + let uri = Uri::from_str("file:///main.inf").expect("uri"); + let symbol = ide::DocumentSymbol { + name: "x".to_owned(), + kind: ide::SymbolKind::Field, + range: ide::TextRange { start: 11, end: 12 }, + selection_range: ide::TextRange { start: 11, end: 12 }, + children: Vec::new(), + }; + let info = symbol_information(&index, &uri, Some("P"), &symbol); + assert_eq!(info.name, "x"); + assert_eq!(info.kind, SymbolKind::FIELD); + assert_eq!(info.container_name.as_deref(), Some("P")); + assert_eq!(info.location.uri, uri); + } + + #[test] + fn document_symbol_nests_children() { + let index = index("struct P { x: i32; }"); + let symbol = ide::DocumentSymbol { + name: "P".to_owned(), + kind: ide::SymbolKind::Struct, + range: ide::TextRange { start: 0, end: 20 }, + selection_range: ide::TextRange { start: 7, end: 8 }, + children: vec![ide::DocumentSymbol { + name: "x".to_owned(), + kind: ide::SymbolKind::Field, + range: ide::TextRange { start: 11, end: 12 }, + selection_range: ide::TextRange { start: 11, end: 12 }, + children: Vec::new(), + }], + }; + let converted = document_symbol(&index, symbol); + assert_eq!(converted.kind, SymbolKind::STRUCT); + let children = converted.children.expect("a struct has field children"); + assert_eq!(children.len(), 1); + assert_eq!(children[0].kind, SymbolKind::FIELD); + } +} diff --git a/apps/lsp/src/handlers.rs b/apps/lsp/src/handlers.rs new file mode 100644 index 00000000..7f70a1ee --- /dev/null +++ b/apps/lsp/src/handlers.rs @@ -0,0 +1,228 @@ +//! Per-request and per-notification handlers. +//! +//! Each handler resolves the document's path from its URI, converts the LSP +//! position(s) to byte offsets with the correct file's line index, asks the `ide` +//! layer, and converts the answer back. A URI this server cannot map to a file +//! (a non-`file` scheme, an untitled buffer) yields a null result and no +//! diagnostics, never a panic. + +use inference_ide as ide; +use lsp_types::{ + CompletionParams, CompletionResponse, DidChangeTextDocumentParams, DidCloseTextDocumentParams, + DidOpenTextDocumentParams, DocumentSymbolParams, DocumentSymbolResponse, GotoDefinitionParams, + GotoDefinitionResponse, Hover, HoverParams, InlayHint, InlayHintParams, Location, + PublishDiagnosticsParams, SymbolInformation, Uri, +}; + +use crate::server::{Document, ServerState}; +use crate::{convert, uri}; + +pub(crate) fn hover(state: &mut ServerState, params: HoverParams) -> Option { + let position = params.text_document_position_params; + let path = uri::to_path(&position.text_document.uri)?; + let index = state.host.analysis().line_index(&path)?; + let offset = convert::offset(&index, position.position)?; + let hover = state.host.analysis().hover(&path, offset)?; + Some(convert::hover(&index, hover)) +} + +pub(crate) fn goto_definition( + state: &mut ServerState, + params: GotoDefinitionParams, +) -> Option { + let position = params.text_document_position_params; + let path = uri::to_path(&position.text_document.uri)?; + let index = state.host.analysis().line_index(&path)?; + let offset = convert::offset(&index, position.position)?; + let targets = state.host.analysis().goto_definition(&path, offset)?; + + let mut locations = Vec::with_capacity(targets.len()); + for target in targets { + // A cross-file target's range is in that file's own coordinates, so it + // must be converted with the target file's line index — reused from this + // document's already-computed closure, never re-analyzed. + let target_index = if target.path == path { + index.clone() + } else { + match state + .host + .analysis() + .closure_line_index(&path, &target.path) + { + Some(target_index) => target_index, + None => continue, + } + }; + let Some(target_uri) = uri::from_path(&target.path) else { + continue; + }; + locations.push(Location { + uri: target_uri, + range: convert::range(&target_index, target.focus_range), + }); + } + + match locations.len() { + 0 => None, + 1 => Some(GotoDefinitionResponse::Scalar(locations.remove(0))), + _ => Some(GotoDefinitionResponse::Array(locations)), + } +} + +pub(crate) fn completion( + state: &mut ServerState, + params: CompletionParams, +) -> Option { + let position = params.text_document_position; + let path = uri::to_path(&position.text_document.uri)?; + let index = state.host.analysis().line_index(&path)?; + let offset = convert::offset(&index, position.position)?; + let items = state + .host + .analysis() + .completions(&path, offset) + .into_iter() + .map(convert::completion_item) + .collect(); + Some(CompletionResponse::Array(items)) +} + +pub(crate) fn document_symbol( + state: &mut ServerState, + params: DocumentSymbolParams, +) -> Option { + let uri = params.text_document.uri; + let path = uri::to_path(&uri)?; + let index = state.host.analysis().line_index(&path)?; + let symbols = state.host.analysis().document_symbols(&path); + + if state.hierarchical_symbols { + let nested = symbols + .into_iter() + .map(|symbol| convert::document_symbol(&index, symbol)) + .collect(); + return Some(DocumentSymbolResponse::Nested(nested)); + } + + let mut flat = Vec::new(); + for symbol in symbols { + push_flat_symbol(&index, &uri, None, symbol, &mut flat); + } + Some(DocumentSymbolResponse::Flat(flat)) +} + +/// Appends `symbol` and its descendants to `flat`, recording each one's enclosing +/// symbol name as its container (the shape a non-hierarchical client expects). +fn push_flat_symbol( + index: &ide::LineIndex, + uri: &Uri, + container: Option<&str>, + symbol: ide::DocumentSymbol, + flat: &mut Vec, +) { + flat.push(convert::symbol_information(index, uri, container, &symbol)); + for child in symbol.children { + push_flat_symbol(index, uri, Some(&symbol.name), child, flat); + } +} + +pub(crate) fn inlay_hint( + state: &mut ServerState, + params: InlayHintParams, +) -> Option> { + let path = uri::to_path(¶ms.text_document.uri)?; + let index = state.host.analysis().line_index(&path)?; + let clip = convert::text_range(&index, params.range); + let hints = state + .host + .analysis() + .inlay_hints(&path, clip) + .into_iter() + .map(|hint| convert::inlay_hint(&index, hint)) + .collect(); + Some(hints) +} + +pub(crate) fn did_open( + state: &mut ServerState, + params: DidOpenTextDocumentParams, +) -> Option { + let document = params.text_document; + let path = uri::to_path(&document.uri)?; + state.host.open_document(&path, document.text); + state.documents.insert( + document.uri.clone(), + Document { + path, + version: document.version, + }, + ); + Some(publish_diagnostics_params(state, &document.uri)) +} + +pub(crate) fn did_change( + state: &mut ServerState, + params: DidChangeTextDocumentParams, +) -> Option { + let uri = params.text_document.uri; + let version = params.text_document.version; + let path = uri::to_path(&uri)?; + // Full-text sync: the last content change carries the whole new document. + let text = params.content_changes.into_iter().next_back()?.text; + state.host.change_document(&path, text); + state + .documents + .insert(uri.clone(), Document { path, version }); + Some(publish_diagnostics_params(state, &uri)) +} + +pub(crate) fn did_close( + state: &mut ServerState, + params: DidCloseTextDocumentParams, +) -> Option { + let uri = params.text_document.uri; + if let Some(path) = uri::to_path(&uri) { + state.host.close_document(&path); + } + state.documents.remove(&uri); + // Publish an empty set so the editor clears any diagnostics it was showing. + Some(PublishDiagnosticsParams { + uri, + diagnostics: Vec::new(), + version: None, + }) +} + +/// The diagnostics to publish for the tracked document `uri`, converted to LSP +/// coordinates. An untracked or non-analyzable document publishes an empty set. +pub(crate) fn publish_diagnostics_params( + state: &mut ServerState, + uri: &Uri, +) -> PublishDiagnosticsParams { + let Some(document) = state.documents.get(uri) else { + return PublishDiagnosticsParams { + uri: uri.clone(), + diagnostics: Vec::new(), + version: None, + }; + }; + let path = document.path.clone(); + let version = document.version; + + let diagnostics = match state.host.analysis().line_index(&path) { + Some(index) => state + .host + .analysis() + .diagnostics(&path) + .into_iter() + .map(|diagnostic| convert::diagnostic(&index, diagnostic)) + .collect(), + None => Vec::new(), + }; + + PublishDiagnosticsParams { + uri: uri.clone(), + diagnostics, + version: Some(version), + } +} diff --git a/apps/lsp/src/main.rs b/apps/lsp/src/main.rs index 7796669a..0a70a5c6 100644 --- a/apps/lsp/src/main.rs +++ b/apps/lsp/src/main.rs @@ -1,3 +1,59 @@ -pub fn main() { - println!("Hello, Inference LSP!"); +//! `inference-lsp`: the Language Server Protocol server for Inference. +//! +//! A synchronous, single-threaded stdio server built on `lsp-server`. It answers +//! diagnostics, hover, goto-definition, completion, document symbols, and inlay +//! hints for Inference source, delegating all analysis to the `ide` stack and +//! confining every protocol concern (framing, position encoding, URIs) to this +//! crate. Stdout is the JSON-RPC channel; all logging goes to stderr. + +mod capabilities; +mod convert; +mod handlers; +mod server; +mod uri; + +use anyhow::Result; +use lsp_server::Connection; +use lsp_types::InitializeParams; + +/// The stack the server loop runs on. The analysis pipeline (type-checker, +/// analysis passes) recurses with the input's nesting depth, so a pathological or +/// generated document can overflow the default stack and abort the whole process +/// — taking every open document's state with it. A stack overflow aborts rather +/// than unwinds, so a worker thread cannot *catch* it; the mitigation is headroom. +/// 64 MiB (mirroring rust-analyzer's main-loop stack) clears realistic deep +/// nesting by a wide margin. A thread must set this explicitly: a spawned thread's +/// default stack is far smaller than the main thread's. +const SERVER_STACK_SIZE: usize = 64 * 1024 * 1024; + +fn main() -> Result<()> { + eprintln!("inference-lsp: starting on stdio"); + + let server = std::thread::Builder::new() + .name("inference-lsp-main".to_owned()) + .stack_size(SERVER_STACK_SIZE) + .spawn(run_server)?; + server.join().expect("the server thread panicked") +} + +/// Owns the transport for one stdio session: handshake, message loop, teardown. +/// +/// A malformed frame (an empty or non-JSON body, or an unparsable +/// `Content-Length`) is a known limitation: `lsp-server`'s stdio reader treats +/// any framing/body parse failure as fatal to the connection and gives no seam to +/// answer JSON-RPC `-32700` and resync, so `io_threads.join()` surfaces it as an +/// error here and the process exits. Recovering would require replacing +/// `Connection::stdio()` with a vendored reader; rust-analyzer accepts the same +/// limitation on `lsp-server`. See the README's known-limitations note. +fn run_server() -> Result<()> { + let (connection, io_threads) = Connection::stdio(); + let server_capabilities = serde_json::to_value(capabilities::server_capabilities())?; + let init_params = connection.initialize(server_capabilities)?; + let init_params: InitializeParams = serde_json::from_value(init_params)?; + + server::run(connection, &init_params)?; + io_threads.join()?; + + eprintln!("inference-lsp: shut down cleanly"); + Ok(()) } diff --git a/apps/lsp/src/server.rs b/apps/lsp/src/server.rs new file mode 100644 index 00000000..cd5c0e71 --- /dev/null +++ b/apps/lsp/src/server.rs @@ -0,0 +1,421 @@ +//! The server state and the single-threaded message loop. +//! +//! [`ServerState`] holds the analysis host and the set of open documents; it turns +//! one request into one [`Response`] and one notification into the diagnostics to +//! publish, with no I/O of its own — which is what makes it directly testable. +//! [`run`] owns the transport: it reads messages, handles the shutdown/exit +//! handshake inline, routes everything else through the state, and writes the +//! results back. Nothing here prints to stdout; that stream is the protocol +//! channel. + +use std::path::PathBuf; + +use inference_ide::AnalysisHost; +use lsp_server::{Connection, ErrorCode, ExtractError, Message, Notification, Request, Response}; +use lsp_types::notification::{ + DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, Exit, Notification as _, + PublishDiagnostics, +}; +use lsp_types::request::{ + Completion, DocumentSymbolRequest, GotoDefinition, HoverRequest, InlayHintRequest, + Request as _, Shutdown, +}; +use lsp_types::{InitializeParams, PublishDiagnosticsParams, Uri}; +use rustc_hash::FxHashMap; + +use crate::handlers; + +/// A document the editor has opened, with the path the analysis host knows it by +/// and the last version the editor reported (echoed back in published +/// diagnostics so the client can correlate them). +pub(crate) struct Document { + pub(crate) path: PathBuf, + pub(crate) version: i32, +} + +/// The analysis host plus per-document bookkeeping. Feature queries and +/// diagnostics are answered against this; the transport is elsewhere. +pub(crate) struct ServerState { + pub(crate) host: AnalysisHost, + pub(crate) documents: FxHashMap, + /// Whether the client accepts the hierarchical document-symbol response; when + /// it does not, symbols are flattened to `SymbolInformation`. + pub(crate) hierarchical_symbols: bool, +} + +impl ServerState { + pub(crate) fn new(hierarchical_symbols: bool) -> Self { + Self { + host: AnalysisHost::default(), + documents: FxHashMap::default(), + hierarchical_symbols, + } + } + + /// Routes a request to its handler, producing the response to send back. An + /// unknown method is a `MethodNotFound` error; malformed params are + /// `InvalidParams`; neither disturbs the server. + pub(crate) fn handle_request(&mut self, request: Request) -> Response { + if request.method == HoverRequest::METHOD { + self.dispatch::(request, handlers::hover) + } else if request.method == GotoDefinition::METHOD { + self.dispatch::(request, handlers::goto_definition) + } else if request.method == Completion::METHOD { + self.dispatch::(request, handlers::completion) + } else if request.method == DocumentSymbolRequest::METHOD { + self.dispatch::(request, handlers::document_symbol) + } else if request.method == InlayHintRequest::METHOD { + self.dispatch::(request, handlers::inlay_hint) + } else { + Response::new_err( + request.id, + ErrorCode::MethodNotFound as i32, + format!("unsupported request: {}", request.method), + ) + } + } + + /// Deserializes the request's params for `R`, runs `handler`, and wraps the + /// result — turning a params-deserialization failure into `InvalidParams`. + fn dispatch( + &mut self, + request: Request, + handler: fn(&mut ServerState, R::Params) -> R::Result, + ) -> Response + where + R: lsp_types::request::Request, + { + let id = request.id.clone(); + match request.extract::(R::METHOD) { + Ok((id, params)) => Response::new_ok(id, handler(self, params)), + Err(ExtractError::JsonError { error, .. }) => { + Response::new_err(id, ErrorCode::InvalidParams as i32, error.to_string()) + } + Err(ExtractError::MethodMismatch(request)) => Response::new_err( + id, + ErrorCode::InvalidRequest as i32, + format!( + "method mismatch: expected {}, got {}", + R::METHOD, + request.method + ), + ), + } + } + + /// Applies a document notification, returning the diagnostics to publish for + /// the notified document *and* every other open document (see + /// [`publishes_with_dependents`](Self::publishes_with_dependents)). An unknown + /// or unparsable notification publishes nothing. + pub(crate) fn on_notification( + &mut self, + notification: Notification, + ) -> Vec { + let primary = if notification.method == DidOpenTextDocument::METHOD { + match notification.extract(DidOpenTextDocument::METHOD) { + Ok(params) => handlers::did_open(self, params), + Err(_) => return Vec::new(), + } + } else if notification.method == DidChangeTextDocument::METHOD { + match notification.extract(DidChangeTextDocument::METHOD) { + Ok(params) => handlers::did_change(self, params), + Err(_) => return Vec::new(), + } + } else if notification.method == DidCloseTextDocument::METHOD { + match notification.extract(DidCloseTextDocument::METHOD) { + Ok(params) => handlers::did_close(self, params), + Err(_) => return Vec::new(), + } + } else { + return Vec::new(); + }; + self.publishes_with_dependents(primary) + } + + /// Extends a notified document's `primary` publish with a fresh republish for + /// every other open document. + /// + /// A change to one file can invalidate another open document whose import + /// closure includes it — `ide-db` drops exactly those analyses — but the + /// notified document is the only one the client is told about unless we + /// republish the rest. Republishing every open document is the simple correct + /// choice: an unaffected document's analysis is still memoized, so its + /// republish recomputes nothing, and editors keep only a handful of files + /// open, so the cost is bounded by that count, not the project size. + fn publishes_with_dependents( + &mut self, + primary: Option, + ) -> Vec { + let Some(primary) = primary else { + return Vec::new(); + }; + let dependents: Vec = self + .documents + .keys() + .filter(|uri| **uri != primary.uri) + .cloned() + .collect(); + let mut publishes = Vec::with_capacity(dependents.len() + 1); + publishes.push(primary); + for uri in dependents { + publishes.push(handlers::publish_diagnostics_params(self, &uri)); + } + publishes + } +} + +/// Runs the message loop until the client exits or the connection closes. +/// +/// The shutdown handshake is handled inline rather than delegated to +/// `lsp-server`'s `Connection::handle_shutdown`, which consumes the next message +/// itself and turns anything but `exit` into a fatal protocol error. Instead, a +/// `shutdown` request is answered and flips a `shutting_down` flag; while it is +/// set, every further request is answered with `InvalidRequest` (the spec's +/// behaviour for requests received between `shutdown` and `exit`) and every +/// notification but `exit` is ignored. The `exit` notification ends the loop. +/// Every other request is routed through [`ServerState`], and document +/// notifications may publish diagnostics. +/// +/// # Errors +/// +/// Returns an error if a message cannot be written to the transport. +pub fn run(connection: Connection, init_params: &InitializeParams) -> anyhow::Result<()> { + let mut state = ServerState::new(hierarchical_symbol_support(init_params)); + let mut shutting_down = false; + + for message in &connection.receiver { + match message { + Message::Request(request) if request.method == Shutdown::METHOD => { + shutting_down = true; + send( + &connection, + Message::Response(Response::new_ok(request.id, ())), + )?; + } + Message::Request(request) if shutting_down => { + send( + &connection, + Message::Response(Response::new_err( + request.id, + ErrorCode::InvalidRequest as i32, + "the server is shutting down".to_owned(), + )), + )?; + } + Message::Request(request) => { + let response = state.handle_request(request); + send(&connection, Message::Response(response))?; + } + Message::Notification(notification) if notification.method == Exit::METHOD => { + return Ok(()); + } + // A stray notification after `shutdown` (other than `exit`) is dropped. + Message::Notification(_) if shutting_down => {} + Message::Notification(notification) => { + for params in state.on_notification(notification) { + let published = + Notification::new(PublishDiagnostics::METHOD.to_owned(), params); + send(&connection, Message::Notification(published))?; + } + } + Message::Response(_) => {} + } + } + Ok(()) +} + +/// Whether the client advertised support for the hierarchical document-symbol +/// response; absent capabilities mean the flat form. +fn hierarchical_symbol_support(init_params: &InitializeParams) -> bool { + init_params + .capabilities + .text_document + .as_ref() + .and_then(|text_document| text_document.document_symbol.as_ref()) + .and_then(|document_symbol| document_symbol.hierarchical_document_symbol_support) + .unwrap_or(false) +} + +fn send(connection: &Connection, message: Message) -> anyhow::Result<()> { + connection + .sender + .send(message) + .map_err(|error| anyhow::anyhow!("failed to send message: {error}")) +} + +#[cfg(test)] +mod tests { + use lsp_server::{Request, RequestId, Response}; + use lsp_types::notification::{ + DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, Notification as _, + }; + use lsp_types::request::{HoverRequest, Request as _}; + + use super::ServerState; + + fn open(state: &mut ServerState, uri: &str, text: &str) { + let params = serde_json::json!({ + "textDocument": { "uri": uri, "languageId": "inference", "version": 1, "text": text } + }); + let notification = + lsp_server::Notification::new(DidOpenTextDocument::METHOD.to_owned(), params); + state.on_notification(notification); + } + + fn error_code(response: &Response) -> i32 { + response.error.as_ref().expect("an error response").code + } + + #[test] + fn unknown_request_is_method_not_found() { + let mut state = ServerState::new(true); + let request = Request::new( + RequestId::from(1), + "textDocument/rename".to_owned(), + serde_json::json!({}), + ); + let response = state.handle_request(request); + assert_eq!( + error_code(&response), + lsp_server::ErrorCode::MethodNotFound as i32 + ); + } + + #[test] + fn malformed_params_are_invalid_params_and_leave_the_server_usable() { + let mut state = ServerState::new(true); + open( + &mut state, + "file:///inf-test/main.inf", + "fn f() -> i32 { return 1; }", + ); + + // A hover request whose params are not a `HoverParams`. + let bad = Request::new( + RequestId::from(2), + HoverRequest::METHOD.to_owned(), + serde_json::json!({ "unexpected": true }), + ); + let response = state.handle_request(bad); + assert_eq!( + error_code(&response), + lsp_server::ErrorCode::InvalidParams as i32 + ); + + // The server still answers a well-formed request afterwards. + let good = Request::new( + RequestId::from(3), + HoverRequest::METHOD.to_owned(), + serde_json::json!({ + "textDocument": { "uri": "file:///inf-test/main.inf" }, + "position": { "line": 0, "character": 3 } + }), + ); + let response = state.handle_request(good); + assert!(response.error.is_none(), "a valid request still succeeds"); + assert!( + response.result.is_some_and(|result| !result.is_null()), + "hover over the function name returns a result" + ); + } + + #[test] + fn did_open_broken_source_publishes_a_diagnostic() { + let mut state = ServerState::new(true); + let params = serde_json::json!({ + "textDocument": { + "uri": "file:///inf-test/broken.inf", + "languageId": "inference", + "version": 7, + "text": "fn f() -> i32 { return x; }" + } + }); + let notification = + lsp_server::Notification::new(DidOpenTextDocument::METHOD.to_owned(), params); + let mut publishes = state.on_notification(notification); + assert_eq!(publishes.len(), 1, "the only open document publishes once"); + let published = publishes.remove(0); + assert_eq!(published.uri.as_str(), "file:///inf-test/broken.inf"); + assert_eq!(published.version, Some(7)); + assert!( + !published.diagnostics.is_empty(), + "an undeclared variable is reported" + ); + } + + #[test] + fn a_notification_republishes_every_open_document() { + let mut state = ServerState::new(true); + open( + &mut state, + "file:///inf-test/a.inf", + "fn a() -> i32 { return 1; }", + ); + open( + &mut state, + "file:///inf-test/b.inf", + "fn b() -> i32 { return 2; }", + ); + + // A change to a.inf publishes for a.inf *and* republishes b.inf, so a + // client can never keep stale diagnostics on a document a cross-file edit + // invalidated. + let params = serde_json::json!({ + "textDocument": { "uri": "file:///inf-test/a.inf", "version": 2 }, + "contentChanges": [ { "text": "fn a() -> i32 { return 11; }" } ] + }); + let notification = + lsp_server::Notification::new(DidChangeTextDocument::METHOD.to_owned(), params); + let publishes = state.on_notification(notification); + let uris: Vec<&str> = publishes.iter().map(|p| p.uri.as_str()).collect(); + assert!( + uris.contains(&"file:///inf-test/a.inf"), + "the changed document" + ); + assert!( + uris.contains(&"file:///inf-test/b.inf"), + "the other open document is republished too, got {uris:?}" + ); + } + + #[test] + fn did_close_publishes_an_empty_set() { + let mut state = ServerState::new(true); + open( + &mut state, + "file:///inf-test/main.inf", + "fn f() -> i32 { return 1; }", + ); + let params = serde_json::json!({ "textDocument": { "uri": "file:///inf-test/main.inf" } }); + let notification = + lsp_server::Notification::new(DidCloseTextDocument::METHOD.to_owned(), params); + let mut publishes = state.on_notification(notification); + assert_eq!( + publishes.len(), + 1, + "closing the only document clears it once" + ); + let published = publishes.remove(0); + assert!(published.diagnostics.is_empty()); + assert_eq!(published.version, None); + } + + #[test] + fn non_file_uri_is_ignored_on_open() { + let mut state = ServerState::new(true); + let params = serde_json::json!({ + "textDocument": { + "uri": "untitled:Untitled-1", + "languageId": "inference", + "version": 1, + "text": "fn f() {}" + } + }); + let notification = + lsp_server::Notification::new(DidOpenTextDocument::METHOD.to_owned(), params); + assert!( + state.on_notification(notification).is_empty(), + "an untitled buffer is not analyzed and publishes nothing" + ); + } +} diff --git a/apps/lsp/src/uri.rs b/apps/lsp/src/uri.rs new file mode 100644 index 00000000..7cbf40cc --- /dev/null +++ b/apps/lsp/src/uri.rs @@ -0,0 +1,341 @@ +//! Conversions between `file://` URIs and filesystem paths. +//! +//! `lsp-types` models a URI with `fluent-uri`, which offers no path helpers, so +//! the mapping is done here as pure string manipulation and kept in one place — +//! it is the only spot in the server that reasons about percent-encoding and +//! Windows drive letters. The two public wrappers ([`to_path`] / [`from_path`]) +//! bridge to `std` path and `lsp_types::Uri` for the host they run on. +//! +//! # Drive letters are host-shaped +//! +//! The `/X:/…` form is a Windows drive path *only on Windows*. On a POSIX host it +//! is a genuine absolute path whose first component happens to be a directory +//! named `X:`. The string core therefore takes an explicit `windows` flag +//! (`cfg!(windows)` in the public wrappers) instead of pattern-matching the shape +//! host-blindly: on Windows the leading slash is dropped and the drive letter is +//! upper-cased so `file:///c%3A/…` and `file:///C:/…` name one document (the std +//! canonical spelling); on POSIX `/c:/…` maps to itself and a backslash is an +//! ordinary filename byte. The flag is a parameter so both behaviours stay +//! testable from either host. +//! +//! Supported inputs are local `file://` URIs with an empty or `localhost` +//! authority. A non-`file` scheme, a remote authority, or a URI carrying a query +//! or fragment yields `None`; the caller treats that as "not a document we can +//! analyze" and answers gracefully. + +use std::path::{Path, PathBuf}; + +use lsp_types::Uri; + +/// The filesystem path a `file://` URI names, or `None` when it is not a local +/// file URI this server can serve. +#[must_use = "a URI that cannot be mapped to a path must be handled, not ignored"] +pub(crate) fn to_path(uri: &Uri) -> Option { + file_uri_to_path(uri.as_str(), cfg!(windows)).map(PathBuf::from) +} + +/// The `file://` URI naming `path`, or `None` when `path` is not absolute or is +/// not valid UTF-8. +#[must_use = "a path that cannot be mapped to a URI must be handled, not ignored"] +pub(crate) fn from_path(path: &Path) -> Option { + let uri = path_to_file_uri(path.to_str()?, cfg!(windows))?; + uri.parse().ok() +} + +/// Decodes a `file://` URI string into its filesystem path string. +/// +/// The path is percent-decoded; on a Windows host the `file:///C:/…` drive form +/// is canonicalized (leading slash dropped, drive letter upper-cased). A URI that +/// carries a query or fragment is rejected — see [`has_query_or_fragment`]. +fn file_uri_to_path(uri: &str, windows: bool) -> Option { + let rest = uri.strip_prefix("file://")?; + // The authority ends at the first slash, which also begins the absolute path. + let path_start = rest.find('/')?; + let authority = &rest[..path_start]; + if !authority.is_empty() && !authority.eq_ignore_ascii_case("localhost") { + return None; // A remote/UNC authority is out of scope for v1. + } + let path = &rest[path_start..]; + if has_query_or_fragment(path) { + return None; // Not a plain document URI; the caller handles it gracefully. + } + let decoded = percent_decode(path)?; + Some(canonicalize_drive(decoded, windows)) +} + +/// Encodes a filesystem path string as a `file://` URI string. +/// +/// On Windows, backslashes are normalized to forward slashes and a drive-letter +/// path gains the leading slash the URI form requires with an upper-cased drive +/// letter (`c:\x` → `file:///C:/x`). On POSIX only an absolute path has a URI, and +/// a backslash is percent-encoded like any other non-path byte. +fn path_to_file_uri(path: &str, windows: bool) -> Option { + if path.is_empty() { + return None; + } + let absolute = if windows { + let mut normalized = path.replace('\\', "/"); + if starts_with_drive(&normalized) { + normalized[..1].make_ascii_uppercase(); + format!("/{normalized}") + } else if normalized.starts_with('/') { + normalized + } else { + return None; // Only absolute paths have a well-defined file URI. + } + } else if path.starts_with('/') { + path.to_owned() + } else { + return None; // On POSIX a drive-shaped path is relative, so it has no URI. + }; + Some(format!("file://{}", percent_encode(&absolute))) +} + +/// Whether the URI path component begins a query (`?`) or fragment (`#`). +/// +/// These delimiters cannot be literal path bytes in a valid URI — a literal `?` +/// or `#` in a filename arrives percent-encoded (`%3F` / `%23`) and never reaches +/// this raw scan. A file URI carrying either is not a document this server can +/// serve, so it is rejected rather than decoded into a path with the query or +/// fragment fused onto the filename. +fn has_query_or_fragment(path: &str) -> bool { + path.bytes().any(|byte| byte == b'?' || byte == b'#') +} + +/// Whether `path` begins with a `X:` drive prefix. +fn starts_with_drive(path: &str) -> bool { + let bytes = path.as_bytes(); + bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' +} + +/// On Windows, canonicalizes a decoded `/X:/…` drive path to `X:/…` with an +/// upper-cased drive letter. On POSIX the same shape is a genuine absolute path +/// and is returned unchanged. +fn canonicalize_drive(path: String, windows: bool) -> String { + if !windows { + return path; + } + let bytes = path.as_bytes(); + if bytes.len() >= 3 && bytes[0] == b'/' && bytes[1].is_ascii_alphabetic() && bytes[2] == b':' { + let mut stripped = path[1..].to_owned(); + stripped[..1].make_ascii_uppercase(); + stripped + } else { + path + } +} + +const HEX_DIGITS: &[u8; 16] = b"0123456789ABCDEF"; + +/// Percent-encodes every byte outside the unreserved set (plus the path +/// characters `/` and `:`), so the result is a valid URI path that round-trips. +fn percent_encode(input: &str) -> String { + let mut encoded = String::with_capacity(input.len()); + for &byte in input.as_bytes() { + if is_unreserved_path_byte(byte) { + encoded.push(byte as char); + } else { + encoded.push('%'); + encoded.push(HEX_DIGITS[(byte >> 4) as usize] as char); + encoded.push(HEX_DIGITS[(byte & 0x0f) as usize] as char); + } + } + encoded +} + +/// Percent-decodes a URI component, returning `None` on a truncated or non-UTF-8 +/// escape sequence. Bytes are accumulated first, then decoded as UTF-8, so a +/// multi-byte character split across several `%XX` escapes decodes correctly. +fn percent_decode(input: &str) -> Option { + let bytes = input.as_bytes(); + let mut decoded = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + if bytes[index] == b'%' { + let high = hex_value(*bytes.get(index + 1)?)?; + let low = hex_value(*bytes.get(index + 2)?)?; + decoded.push((high << 4) | low); + index += 3; + } else { + decoded.push(bytes[index]); + index += 1; + } + } + String::from_utf8(decoded).ok() +} + +fn is_unreserved_path_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/' | b':') +} + +fn hex_value(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + use std::str::FromStr; + + use lsp_types::Uri; + + use super::{file_uri_to_path, from_path, path_to_file_uri, to_path}; + + // The string core is exercised for both hosts explicitly, so a POSIX build + // still covers the Windows drive-letter behaviour and vice versa. + const POSIX: bool = false; + const WINDOWS: bool = true; + + #[test] + fn posix_absolute_path_round_trips() { + let path = "/home/user/main.inf"; + let uri = path_to_file_uri(path, POSIX).expect("an absolute posix path has a uri"); + assert_eq!(uri, "file:///home/user/main.inf"); + assert_eq!(file_uri_to_path(&uri, POSIX).as_deref(), Some(path)); + } + + #[test] + fn spaces_are_percent_encoded_and_decoded() { + let path = "/home/user/a b.inf"; + let uri = path_to_file_uri(path, POSIX).expect("uri"); + assert_eq!(uri, "file:///home/user/a%20b.inf"); + assert_eq!(file_uri_to_path(&uri, POSIX).as_deref(), Some(path)); + } + + #[test] + fn non_ascii_is_encoded_as_utf8_bytes() { + // `naïve` — the `ï` is two UTF-8 bytes 0xC3 0xAF, each escaped. + let path = "/home/na\u{ef}ve.inf"; + let uri = path_to_file_uri(path, POSIX).expect("uri"); + assert_eq!(uri, "file:///home/na%C3%AFve.inf"); + assert_eq!(file_uri_to_path(&uri, POSIX).as_deref(), Some(path)); + } + + #[test] + fn windows_drive_forward_slash_round_trips() { + let path = "C:/Users/x/main.inf"; + let uri = path_to_file_uri(path, WINDOWS).expect("uri"); + assert_eq!(uri, "file:///C:/Users/x/main.inf"); + assert_eq!(file_uri_to_path(&uri, WINDOWS).as_deref(), Some(path)); + } + + #[test] + fn windows_backslashes_normalize_to_forward_slashes() { + let uri = path_to_file_uri("C:\\Users\\x\\main.inf", WINDOWS).expect("uri"); + assert_eq!(uri, "file:///C:/Users/x/main.inf"); + } + + #[test] + fn windows_drive_case_is_canonicalized_to_uppercase() { + // [15]: VS Code sends the drive colon percent-encoded and lowercased; on + // Windows both spellings must decode to the one std-canonical (uppercase) + // path, so the overlay and the analysis memo key them as one document. + let lower = file_uri_to_path("file:///c%3A/Users/x/main.inf", WINDOWS); + let upper = file_uri_to_path("file:///C:/Users/x/main.inf", WINDOWS); + assert_eq!(lower.as_deref(), Some("C:/Users/x/main.inf")); + assert_eq!(lower, upper, "the two drive spellings name one document"); + } + + #[test] + fn posix_drive_shape_stays_absolute() { + // [18]: on POSIX `/c:/…` is a genuine absolute path (a directory literally + // named `c:`), never a Windows drive — it must not lose its leading slash + // nor have its case folded, and it must round-trip. + let path = file_uri_to_path("file:///c%3A/proj/main.inf", POSIX); + assert_eq!(path.as_deref(), Some("/c:/proj/main.inf")); + assert!(path.as_deref().unwrap().starts_with('/'), "still absolute"); + let uri = path_to_file_uri("/c:/proj/main.inf", POSIX).expect("uri"); + assert_eq!( + file_uri_to_path(&uri, POSIX).as_deref(), + Some("/c:/proj/main.inf") + ); + // A drive-shaped path is relative on POSIX, so it has no file URI. + assert_eq!(path_to_file_uri("c:/x", POSIX), None); + } + + #[test] + fn query_and_fragment_uris_are_rejected() { + // [16]: a document URI carries neither a query nor a fragment; both are + // rejected rather than fused onto the filename. + assert_eq!(file_uri_to_path("file:///a.inf?x=1#f", POSIX), None); + assert_eq!(file_uri_to_path("file:///a.inf?ver=1", POSIX), None); + assert_eq!(file_uri_to_path("file:///a.inf#L5", POSIX), None); + // A percent-encoded `?` (%3F) is a literal filename byte, not a query. + assert_eq!( + file_uri_to_path("file:///a%3Fb.inf", POSIX).as_deref(), + Some("/a?b.inf") + ); + } + + #[test] + fn posix_backslash_is_a_literal_filename_byte() { + // [17]: on POSIX a backslash is an ordinary byte; from_path percent-encodes + // it (%5C) rather than rewriting it to a slash, so the round trip is exact. + let path = "/home/a\\b.inf"; + let uri = path_to_file_uri(path, POSIX).expect("uri"); + assert_eq!(uri, "file:///home/a%5Cb.inf"); + assert_eq!(file_uri_to_path(&uri, POSIX).as_deref(), Some(path)); + } + + #[test] + fn localhost_authority_is_accepted() { + assert_eq!( + file_uri_to_path("file://localhost/home/user/main.inf", POSIX).as_deref(), + Some("/home/user/main.inf") + ); + } + + #[test] + fn non_file_schemes_are_rejected() { + assert_eq!(file_uri_to_path("http://example.com/x.inf", POSIX), None); + assert_eq!(file_uri_to_path("untitled:Untitled-1", POSIX), None); + assert_eq!(file_uri_to_path("inmemory://model/1", POSIX), None); + } + + #[test] + fn remote_authority_is_rejected() { + assert_eq!( + file_uri_to_path("file://server/share/main.inf", POSIX), + None + ); + } + + #[test] + fn relative_path_has_no_file_uri() { + assert_eq!(path_to_file_uri("relative/main.inf", POSIX), None); + assert_eq!(path_to_file_uri("", POSIX), None); + } + + #[test] + fn truncated_escape_is_rejected() { + assert_eq!(file_uri_to_path("file:///home/a%2", POSIX), None); + assert_eq!(file_uri_to_path("file:///home/a%zz", POSIX), None); + } + + #[test] + fn literal_percent_round_trips() { + let path = "/home/100%done/main.inf"; + let uri = path_to_file_uri(path, POSIX).expect("uri"); + assert_eq!(uri, "file:///home/100%25done/main.inf"); + assert_eq!(file_uri_to_path(&uri, POSIX).as_deref(), Some(path)); + } + + #[test] + fn uri_wrappers_round_trip_through_lsp_type() { + let path = PathBuf::from("/home/user/main.inf"); + let uri = from_path(&path).expect("a uri for an absolute path"); + assert_eq!(uri.as_str(), "file:///home/user/main.inf"); + assert_eq!(to_path(&uri), Some(path)); + } + + #[test] + fn to_path_rejects_a_non_file_uri() { + let uri = Uri::from_str("untitled:Untitled-1").expect("a syntactically valid uri"); + assert_eq!(to_path(&uri), None); + } +} diff --git a/apps/lsp/tests/e2e.rs b/apps/lsp/tests/e2e.rs new file mode 100644 index 00000000..835c0232 --- /dev/null +++ b/apps/lsp/tests/e2e.rs @@ -0,0 +1,952 @@ +//! Protocol-level end-to-end tests for the `inference-lsp` binary. +//! +//! Each test spawns the real server over stdio and drives a full LSP session — +//! initialize, feature exchanges, shutdown, exit — asserting on the raw JSON that +//! crosses the wire. The [`harness`] client bounds every read with a timeout, so a +//! regression that hangs the server fails the test instead of stalling the run. +//! All fixtures live in per-test unique temp directories, never at a filesystem +//! root and never in the repo, so the tests are parallel-safe. + +mod harness; + +use std::time::Duration; + +use harness::{LspClient, TempDir, path_to_uri, pos_after, pos_at, pos_at_nth, pos_end}; +use serde_json::{Value, json}; + +// LSP `SymbolKind` numeric values (LSP spec, DocumentSymbol section). +const KIND_METHOD: i64 = 6; +const KIND_FIELD: i64 = 8; +const KIND_INTERFACE: i64 = 11; // A spec maps to Interface. +const KIND_FUNCTION: i64 = 12; +const KIND_STRUCT: i64 = 23; + +// LSP `InlayHintKind::Type`. +const INLAY_KIND_TYPE: i64 = 1; + +// JSON-RPC error codes. +const METHOD_NOT_FOUND: i64 = -32601; +const INVALID_PARAMS: i64 = -32602; + +/// A single-file fixture: an isolated temp dir with `main.inf` written to disk, +/// plus its `file://` URI. The returned [`TempDir`] must be kept alive for the +/// session (it removes the directory on drop). The document is not opened yet, so +/// a test can assert on the diagnostics its own `did_open` returns. +fn fixture(tag: &str, source: &str) -> (TempDir, String) { + let dir = TempDir::new(tag); + let path = dir.write("main.inf", source); + let uri = path_to_uri(&path); + (dir, uri) +} + +fn hover_request(client: &mut LspClient, uri: &str, position: Value) -> Value { + client.request( + "textDocument/hover", + json!({ "textDocument": { "uri": uri }, "position": position }), + ) +} + +fn definition_request(client: &mut LspClient, uri: &str, position: Value) -> Value { + client.request( + "textDocument/definition", + json!({ "textDocument": { "uri": uri }, "position": position }), + ) +} + +fn completion_request(client: &mut LspClient, uri: &str, position: Value) -> Value { + client.request( + "textDocument/completion", + json!({ "textDocument": { "uri": uri }, "position": position }), + ) +} + +/// The labels of a `CompletionResponse::Array`. +fn completion_labels(response: &Value) -> Vec { + response["result"] + .as_array() + .expect("completion result is an array") + .iter() + .map(|item| { + item["label"] + .as_str() + .expect("label is a string") + .to_owned() + }) + .collect() +} + +/// The symbol in `symbols` named `name`, panicking if absent. +fn symbol<'a>(symbols: &'a [Value], name: &str) -> &'a Value { + symbols + .iter() + .find(|symbol| symbol["name"] == json!(name)) + .unwrap_or_else(|| panic!("no symbol named {name:?} in {symbols:?}")) +} + +// --- 1. initialize handshake ------------------------------------------------ + +#[test] +fn initialize_advertises_the_v1_capabilities() { + let mut client = LspClient::spawn(); + let result = client.initialize_default(true); + let capabilities = &result["capabilities"]; + + assert_eq!(capabilities["textDocumentSync"], json!(1), "full-text sync"); + assert_eq!(capabilities["hoverProvider"], json!(true)); + assert_eq!(capabilities["definitionProvider"], json!(true)); + assert_eq!(capabilities["documentSymbolProvider"], json!(true)); + assert_eq!(capabilities["inlayHintProvider"], json!(true)); + + let completion = &capabilities["completionProvider"]; + assert_eq!(completion["resolveProvider"], json!(false)); + let triggers = completion["triggerCharacters"] + .as_array() + .expect("trigger characters"); + assert!(triggers.contains(&json!(".")), "`.` is a trigger"); + assert!(triggers.contains(&json!(":")), "`:` is a trigger"); + + // No position encoding is negotiated, so the client keeps the UTF-16 default; + // lsp-server 0.8 attaches no serverInfo. + assert!(capabilities.get("positionEncoding").is_none()); + assert!(result.get("serverInfo").is_none(), "no serverInfo declared"); + + client.shutdown_exit_ok(); +} + +// --- 2. didOpen clean -> empty diagnostics ---------------------------------- + +#[test] +fn did_open_clean_file_publishes_empty_diagnostics() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let (_dir, uri) = fixture("clean", "fn add(a: i32, b: i32) -> i32 { return a + b; }"); + let published = client.did_open(&uri, "fn add(a: i32, b: i32) -> i32 { return a + b; }", 1); + + assert!( + published.diagnostics.is_empty(), + "a clean file has no diagnostics, got {:?}", + published.diagnostics + ); + assert_eq!(published.version, json!(1), "the echoed document version"); + + client.shutdown_exit_ok(); +} + +// --- 3. syntax error diagnostic --------------------------------------------- + +#[test] +fn did_open_with_syntax_error_publishes_a_syntax_diagnostic() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + // A multi-line fixture: the missing expression is on line 1, so a range that + // regressed to line 0 (or to `0..0`) would fail the exact anchor below rather + // than pass because `line == 0` happened to hold on a one-line file. + let source = "fn f() {\n let x: i32 = ;\n}"; + let (_dir, uri) = fixture("syntax", source); + let published = client.did_open(&uri, source, 1); + + let diagnostic = published + .by_code("syntax") + .expect("a syntax-coded diagnostic"); + assert_eq!(diagnostic["severity"], json!(1), "Error severity"); + assert!( + diagnostic["message"] + .as_str() + .is_some_and(|m| !m.is_empty()), + "the message is non-empty" + ); + // The diagnostic is anchored on the semicolon where an expression was expected. + assert_eq!( + diagnostic["range"]["start"], + pos_at(source, ";"), + "anchored where the expression is missing" + ); + assert_eq!(diagnostic["range"]["end"], pos_after(source, ";")); + + client.shutdown_exit_ok(); +} + +// --- 4. didChange fixes the error ------------------------------------------- + +#[test] +fn did_change_fixing_the_error_clears_diagnostics() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let (_dir, uri) = fixture("fix", "fn f() -> i32 { return x; }"); + let broken = client.did_open(&uri, "fn f() -> i32 { return x; }", 1); + assert!( + !broken.diagnostics.is_empty(), + "the undeclared `x` is reported" + ); + + let fixed = client.did_change(&uri, "fn f() -> i32 { return 1; }", 2); + assert!(fixed.diagnostics.is_empty(), "the fix clears diagnostics"); + assert_eq!(fixed.version, json!(2), "the new document version"); + + client.shutdown_exit_ok(); +} + +// --- 5. didChange introduces a type error ----------------------------------- + +#[test] +fn did_change_introducing_a_type_error_surfaces_it_with_location() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let (_dir, uri) = fixture("type", "fn add(a: i32, b: i32) -> i32 { return a + b; }"); + let clean = client.did_open(&uri, "fn add(a: i32, b: i32) -> i32 { return a + b; }", 1); + assert!(clean.diagnostics.is_empty()); + + // Returning a `bool` where `i32` is declared is a genuine type mismatch. The + // return sits on line 1 of a multi-line fixture, so the exact anchor below is + // not satisfiable by a degenerate `0..0` range. + let broken_source = "fn f() -> i32 {\n return true;\n}"; + let broken = client.did_change(&uri, broken_source, 2); + let diagnostic = broken.by_code("type").expect("a type-coded diagnostic"); + assert_eq!(diagnostic["severity"], json!(1)); + let message = diagnostic["message"].as_str().expect("a message"); + assert!( + message.contains("mismatch") && message.contains("i32"), + "the message names the type mismatch, got {message:?}" + ); + // The diagnostic spans the offending `return true;` statement exactly. + assert_eq!( + diagnostic["range"]["start"], + pos_at(broken_source, "return"), + "anchored at the return keyword on line 1" + ); + assert_eq!( + diagnostic["range"]["end"], + pos_after(broken_source, "return true;"), + "range covers the whole return statement" + ); + + client.shutdown_exit_ok(); +} + +// --- 6. analysis rule finding (A041) ---------------------------------------- + +#[test] +fn duplicate_local_surfaces_as_an_a041_finding() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let source = "fn f() { let a: i32 = 1; let a: i32 = 2; }"; + let (_dir, uri) = fixture("a041", source); + let published = client.did_open(&uri, source, 1); + + let finding = published.by_code("A041").expect("an A041 finding"); + assert_eq!(finding["severity"], json!(1), "A041 is an Error"); + assert!( + finding["message"] + .as_str() + .is_some_and(|m| m.contains("already declared")), + "message explains the duplicate, got {}", + finding["message"] + ); + // Anchored on the second declaration. + assert_eq!(finding["range"]["start"], pos_at_nth(source, "let a", 1)); + + client.shutdown_exit_ok(); +} + +// --- 7. hover --------------------------------------------------------------- + +#[test] +fn hover_over_a_local_shows_its_type() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let source = "fn f() -> i32 { let count: i32 = 5; return count; }"; + let (_dir, uri) = fixture("hover-local", source); + client.did_open(&uri, source, 1); + + let response = hover_request(&mut client, &uri, pos_at_nth(source, "count", 1)); + let contents = &response["result"]["contents"]; + assert_eq!(contents["kind"], json!("markdown")); + assert!( + contents["value"] + .as_str() + .is_some_and(|v| v.contains("count: i32")), + "hover renders the local's type, got {}", + contents["value"] + ); + assert!(response["result"]["range"].is_object(), "hover has a range"); + + client.shutdown_exit_ok(); +} + +#[test] +fn hover_over_forall_explains_the_nondet_construct() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let source = "fn f() { forall { assert(true); } }"; + let (_dir, uri) = fixture("hover-forall", source); + client.did_open(&uri, source, 1); + + let response = hover_request(&mut client, &uri, pos_at(source, "forall")); + let value = response["result"]["contents"]["value"] + .as_str() + .expect("markdown hover value"); + assert!(value.contains("forall"), "names the keyword: {value}"); + assert!( + value.contains("every path must succeed"), + "carries the non-det explanation: {value}" + ); + + client.shutdown_exit_ok(); +} + +// --- 8. goto-definition, same file ------------------------------------------ + +#[test] +fn goto_definition_reaches_a_same_file_function() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let source = "fn helper() -> i32 { return 7; }\nfn use_it() -> i32 { return helper(); }"; + let (_dir, uri) = fixture("goto-local", source); + client.did_open(&uri, source, 1); + + let response = definition_request(&mut client, &uri, pos_at_nth(source, "helper", 1)); + let location = &response["result"]; + assert_eq!(location["uri"], json!(uri), "same-file target"); + // The focus range points at the definition's name. + assert_eq!(location["range"]["start"], pos_at(source, "helper")); + + client.shutdown_exit_ok(); +} + +// --- 9. cross-file: import a sibling on disk --------------------------------- + +#[test] +fn cross_file_entry_is_clean_and_goto_reaches_the_imported_file() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let dir = TempDir::new("cross"); + let entry_source = "use lib;\nfn main() -> i32 { return lib::helper(); }"; + let lib_source = "pub fn helper() -> i32 { return 7; }"; + let entry_path = dir.write("main.inf", entry_source); + let lib_path = dir.write("lib.inf", lib_source); + let entry_uri = path_to_uri(&entry_path); + let lib_uri = path_to_uri(&lib_path); + + // Only the entry is opened; the lib is resolved from disk by the project walk. + let published = client.did_open(&entry_uri, entry_source, 1); + assert!( + published.diagnostics.is_empty(), + "a resolvable on-disk import raises no spurious diagnostics, got {:?}", + published.diagnostics + ); + + let response = definition_request(&mut client, &entry_uri, pos_at(entry_source, "helper")); + let location = &response["result"]; + assert_eq!(location["uri"], json!(lib_uri), "target is the lib file"); + assert_eq!( + location["range"]["start"], + pos_at(lib_source, "helper"), + "range is the name in the lib file" + ); + + client.shutdown_exit_ok(); +} + +// --- 10. missing import ----------------------------------------------------- + +#[test] +fn missing_import_is_reported_on_the_use_directive() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + // The `use` directive starts off byte 0 (a header line precedes it) and off + // line 0, so a degenerate `0..0` or whole-file range would fail the exact + // anchor assertion below instead of passing vacuously. + let source = "// entry\nuse libx;\nfn main() -> i32 { return 0; }"; + let (_dir, uri) = fixture("missing-import", source); + let published = client.did_open(&uri, source, 1); + + let diagnostic = published.by_code("import").expect("an import diagnostic"); + assert!( + diagnostic["message"] + .as_str() + .is_some_and(|m| m.contains("cannot find imported module `libx`")), + "names the missing module, got {}", + diagnostic["message"] + ); + // The range is exactly the `use libx;` directive span, both ends pinned. + assert_eq!( + diagnostic["range"]["start"], + pos_at(source, "use libx;"), + "range starts at the directive" + ); + assert_eq!( + diagnostic["range"]["end"], + pos_after(source, "use libx;"), + "range ends at the directive's semicolon" + ); + + client.shutdown_exit_ok(); +} + +// --- 11. documentSymbol, hierarchical and flat ------------------------------ + +const SYMBOL_SOURCE: &str = "struct Point { px: i32; fn getx(self) -> i32 { return self.px; } }\n\ +spec Laws { fn commutes() {} }\n\ +fn entry() { return; }"; + +#[test] +fn document_symbol_returns_a_hierarchical_tree() { + let mut client = LspClient::spawn(); + client.initialize_default(true); // hierarchical support declared + + let (_dir, uri) = fixture("symbols-tree", SYMBOL_SOURCE); + client.did_open(&uri, SYMBOL_SOURCE, 1); + + let response = client.request( + "textDocument/documentSymbol", + json!({ "textDocument": { "uri": uri } }), + ); + let symbols = response["result"].as_array().expect("a symbol array"); + assert_eq!(symbols.len(), 3, "three top-level symbols"); + + let point = symbol(symbols, "Point"); + assert_eq!(point["kind"], json!(KIND_STRUCT)); + assert_eq!( + point["selectionRange"]["start"], + pos_at(SYMBOL_SOURCE, "Point"), + "selection range is the struct name" + ); + let point_children = point["children"].as_array().expect("struct children"); + assert_eq!(symbol(point_children, "px")["kind"], json!(KIND_FIELD)); + assert_eq!(symbol(point_children, "getx")["kind"], json!(KIND_METHOD)); + + let laws = symbol(symbols, "Laws"); + assert_eq!( + laws["kind"], + json!(KIND_INTERFACE), + "a spec is an interface" + ); + let laws_children = laws["children"].as_array().expect("spec children"); + assert_eq!( + symbol(laws_children, "commutes")["kind"], + json!(KIND_FUNCTION) + ); + + assert_eq!(symbol(symbols, "entry")["kind"], json!(KIND_FUNCTION)); + + client.shutdown_exit_ok(); +} + +#[test] +fn document_symbol_flattens_for_a_non_hierarchical_client() { + let mut client = LspClient::spawn(); + client.initialize_default(false); // no hierarchical support + + let (_dir, uri) = fixture("symbols-flat", SYMBOL_SOURCE); + client.did_open(&uri, SYMBOL_SOURCE, 1); + + let response = client.request( + "textDocument/documentSymbol", + json!({ "textDocument": { "uri": uri } }), + ); + let symbols = response["result"] + .as_array() + .expect("a flat SymbolInformation array"); + + // Every symbol, including nested members, appears at the top level. + for name in ["Point", "px", "getx", "Laws", "commutes", "entry"] { + let info = symbol(symbols, name); + assert_eq!(info["location"]["uri"], json!(uri), "{name} location uri"); + assert!(info.get("children").is_none(), "flat symbols do not nest"); + } + // A member records its enclosing symbol as the container. + assert_eq!(symbol(symbols, "px")["containerName"], json!("Point")); + assert_eq!(symbol(symbols, "getx")["containerName"], json!("Point")); + assert_eq!(symbol(symbols, "commutes")["containerName"], json!("Laws")); + + client.shutdown_exit_ok(); +} + +// --- 12. completion --------------------------------------------------------- + +#[test] +fn completion_at_top_level_offers_keywords_and_defs() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let source = "struct Widget { w: i32; }\nfn compute() -> i32 { return 1; }"; + let (_dir, uri) = fixture("complete-top", source); + client.did_open(&uri, source, 1); + + let response = completion_request(&mut client, &uri, json!({ "line": 0, "character": 0 })); + let labels = completion_labels(&response); + assert!( + labels.iter().any(|l| l == "fn"), + "a keyword item: {labels:?}" + ); + assert!( + labels.iter().any(|l| l == "forall"), + "a non-det keyword item" + ); + assert!(labels.iter().any(|l| l == "Widget"), "the struct"); + assert!(labels.iter().any(|l| l == "compute"), "the function"); + + client.shutdown_exit_ok(); +} + +#[test] +fn completion_after_dot_offers_members_only() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let source = "struct P { x: i32; fn get(self) -> i32 { return self.x; } }\n\ +fn m(p: P) -> i32 { return p.; }"; + let (_dir, uri) = fixture("complete-dot", source); + // The incomplete `p.` produces a syntax diagnostic; consume it. + client.did_open(&uri, source, 1); + + let response = completion_request(&mut client, &uri, pos_after(source, "p.")); + let labels = completion_labels(&response); + assert!(labels.iter().any(|l| l == "x"), "the field: {labels:?}"); + assert!(labels.iter().any(|l| l == "get"), "the method: {labels:?}"); + assert!( + !labels.iter().any(|l| l == "m"), + "an unrelated top-level fn is excluded: {labels:?}" + ); + assert!( + !labels.iter().any(|l| l == "fn"), + "keywords are excluded after a dot: {labels:?}" + ); + + client.shutdown_exit_ok(); +} + +// --- 13. inlay hints on a non-det file -------------------------------------- + +const NONDET_SOURCE: &str = "fn f() {\n\ + forall { let a: i32 = @; assert(a == a); }\n\ + exists { let b: i32 = @; assert(b == b); }\n\ + unique { assert(true); }\n\ + assume { assert(true); }\n\ +}"; + +#[test] +fn inlay_hints_annotate_every_nondet_construct() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let (_dir, uri) = fixture("inlay", NONDET_SOURCE); + client.did_open(&uri, NONDET_SOURCE, 1); + + let response = client.request( + "textDocument/inlayHint", + json!({ + "textDocument": { "uri": uri }, + "range": { "start": { "line": 0, "character": 0 }, "end": pos_end(NONDET_SOURCE) }, + }), + ); + let hints = response["result"].as_array().expect("an inlay-hint array"); + assert_eq!(hints.len(), 6, "four blocks plus two uzumaki: {hints:?}"); + assert!( + hints.iter().all(|h| h["kind"] == json!(INLAY_KIND_TYPE)), + "both kinds map to the Type inlay kind" + ); + + // The four block hints, each at the end of its header keyword. + for (keyword, label) in [ + ("forall", "\u{25B8} every path must succeed"), + ("exists", "\u{25B8} at least one path must succeed"), + ("unique", "\u{25B8} exactly one path must succeed"), + ("assume", "\u{25B8} keeps only paths where this holds"), + ] { + let hint = hints + .iter() + .find(|h| h["label"] == json!(label)) + .unwrap_or_else(|| panic!("a hint labelled {label:?}")); + assert_eq!( + hint["position"], + pos_after(NONDET_SOURCE, keyword), + "{keyword} hint sits at the header end" + ); + } + + // Both `@` bindings, typed `i32`. + let uzumaki = hints + .iter() + .filter(|h| h["label"] == json!("\u{25B8} ranges over every value of its type (i32)")) + .count(); + assert_eq!(uzumaki, 2, "one uzumaki hint per `@`"); + + client.shutdown_exit_ok(); +} + +// --- 14. UTF-16 positions ---------------------------------------------------- + +#[test] +fn utf16_positions_resolve_past_a_multibyte_string_literal() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + // The emoji is two astral characters (four UTF-16 units, eight UTF-8 bytes) + // before `count` on the same line, so a byte-vs-UTF-16 confusion would land + // the position on the wrong token. + let source = + "fn f() -> i32 { let s: i32 = \"\u{1F600}\u{1F680}\"; let count: i32 = 5; return count; }"; + let (_dir, uri) = fixture("utf16", source); + client.did_open(&uri, source, 1); + + // Hover at the *use* of `count` resolves to its type. + let hover = hover_request(&mut client, &uri, pos_at_nth(source, "count", 1)); + assert!( + hover["result"]["contents"]["value"] + .as_str() + .is_some_and(|v| v.contains("count: i32")), + "hover resolved across the emoji, got {}", + hover["result"]["contents"]["value"] + ); + + // Definition at the same position reaches the `let count` binding name. + let definition = definition_request(&mut client, &uri, pos_at_nth(source, "count", 1)); + assert_eq!(definition["result"]["uri"], json!(uri)); + assert_eq!( + definition["result"]["range"]["start"], + pos_at(source, "count"), + "definition reaches the binding name" + ); + + client.shutdown_exit_ok(); +} + +// --- 15. didClose clears diagnostics ---------------------------------------- + +#[test] +fn did_close_clears_the_documents_diagnostics() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let (_dir, uri) = fixture("close", "fn f() -> i32 { return x; }"); + let opened = client.did_open(&uri, "fn f() -> i32 { return x; }", 1); + assert!( + !opened.diagnostics.is_empty(), + "the broken doc reports errors" + ); + + let closed = client.did_close(&uri); + assert!(closed.diagnostics.is_empty(), "close clears diagnostics"); + assert_eq!( + closed.version, + Value::Null, + "a cleared publish carries no version" + ); + + client.shutdown_exit_ok(); +} + +// --- 16. robustness --------------------------------------------------------- + +#[test] +fn unknown_method_errors_and_the_server_stays_alive() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + let source = "fn f() -> i32 { return 1; }"; + let (_dir, uri) = fixture("robust-unknown", source); + client.did_open(&uri, source, 1); + + let response = client.request("textDocument/rename", json!({ "unsupported": true })); + assert_eq!( + response["error"]["code"], + json!(METHOD_NOT_FOUND), + "an unknown method is MethodNotFound" + ); + + // The server still answers a well-formed request afterwards. + let hover = hover_request(&mut client, &uri, pos_at(source, "f(")); + assert!( + hover.get("error").is_none(), + "the server is still responsive" + ); + + client.shutdown_exit_ok(); +} + +#[test] +fn malformed_params_error_and_the_server_stays_alive() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + let source = "fn f() -> i32 { return 1; }"; + let (_dir, uri) = fixture("robust-malformed", source); + client.did_open(&uri, source, 1); + + // A hover request whose params are not a `HoverParams` (no position). + let bad = client.request( + "textDocument/hover", + json!({ "textDocument": { "uri": uri } }), + ); + assert_eq!( + bad["error"]["code"], + json!(INVALID_PARAMS), + "missing position is InvalidParams" + ); + + // A well-formed hover still succeeds. + let good = hover_request(&mut client, &uri, pos_at(source, "f(")); + assert!(good.get("error").is_none(), "the server recovered"); + + client.shutdown_exit_ok(); +} + +#[test] +fn non_file_uri_is_ignored_without_crashing() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + let source = "fn f() -> i32 { return 1; }"; + let (_dir, uri) = fixture("robust-untitled", source); + client.did_open(&uri, source, 1); + + // An untitled buffer is not a file the server can analyze; it publishes + // nothing and must not crash. Send it raw (there is no publish to wait for). + client.send_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": "untitled:Untitled-1", + "languageId": "inference", + "version": 1, + "text": "fn g() {}" + } + }), + ); + + // A subsequent request against the real document still works. + let hover = hover_request(&mut client, &uri, pos_at(source, "f(")); + assert!( + hover.get("error").is_none(), + "the server survived the untitled open" + ); + + client.shutdown_exit_ok(); +} + +// --- 17. shutdown / exit ---------------------------------------------------- + +#[test] +fn shutdown_then_exit_exits_cleanly() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + // Open nothing; just run the shutdown/exit handshake. + client.shutdown_exit_ok(); +} + +#[test] +fn exit_without_shutdown_exits_zero_on_this_server() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + // The LSP spec asks a server to exit with code 1 when `exit` arrives with no + // preceding `shutdown`. This server does not track that: lsp-server's reader + // stops after forwarding `exit`, the message loop then ends, and `main` + // returns `Ok`, so the process exits 0 in both cases. Asserting the actual + // behavior documents the deviation rather than hiding it. + client.exit(); + let status = client.wait_for_exit(); + assert_eq!( + status.code(), + Some(0), + "this server exits 0 even without a prior shutdown (spec would be 1)" + ); +} + +// --- 18. stdout carries only framed protocol -------------------------------- + +#[test] +fn a_full_session_writes_only_framed_protocol_to_stdout() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + // Exercise every request and notification kind in one session; the harness + // reader parses the whole stdout stream as framed messages and records any + // byte that is not, so a stray `println!` or half-written frame would make + // `wait_for_exit` fail. This asserts the property by construction. + let source = "struct P { x: i32; fn get(self) -> i32 { return self.x; } }\n\ +fn use_it(p: P) -> i32 { forall { let n: i32 = @; assert(n == n); } return p.get(); }"; + let (_dir, uri) = fixture("framing", source); + client.did_open(&uri, source, 1); + + hover_request(&mut client, &uri, pos_at(source, "get")); + definition_request(&mut client, &uri, pos_at_nth(source, "get", 1)); + completion_request(&mut client, &uri, json!({ "line": 0, "character": 0 })); + client.request( + "textDocument/documentSymbol", + json!({ "textDocument": { "uri": uri } }), + ); + client.request( + "textDocument/inlayHint", + json!({ + "textDocument": { "uri": uri }, + "range": { "start": { "line": 0, "character": 0 }, "end": pos_end(source) }, + }), + ); + client.did_change(&uri, "fn f() -> i32 { return 1; }", 2); + client.did_close(&uri); + + // `shutdown_exit_ok` calls `wait_for_exit`, which asserts no framing violation + // and a clean end of stream — i.e. every stdout byte was a valid framed message. + client.shutdown_exit_ok(); +} + +// --- 19. editing an imported file republishes dependent documents ----------- + +#[test] +fn editing_an_imported_file_republishes_open_dependents() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + let dir = TempDir::new("stale-cross-file"); + let main_source = "use lib;\nfn main() -> i32 { return lib::helper(); }"; + let lib_ok = "pub fn helper() -> i32 { return 7; }"; + let lib_broken = "pub fn other() -> i32 { return 8; }"; + let main_path = dir.write("main.inf", main_source); + let lib_path = dir.write("lib.inf", lib_ok); + let main_uri = path_to_uri(&main_path); + let lib_uri = path_to_uri(&lib_path); + + // Both documents open clean. + let opened_main = client.did_open(&main_uri, main_source, 1); + assert!( + opened_main.diagnostics.is_empty(), + "main opens clean, got {:?}", + opened_main.diagnostics + ); + let opened_lib = client.did_open(&lib_uri, lib_ok, 1); + assert!(opened_lib.diagnostics.is_empty(), "lib opens clean"); + // Drain the republish that opening lib triggered for the still-clean main. + client.drain_publishes(Duration::from_millis(500)); + + // Break lib: main now calls a function that no longer exists. The change to + // lib must produce a fresh publish for the dependent main, without touching + // main itself — otherwise the editor keeps rendering main as clean. + client.send_notification( + "textDocument/didChange", + json!({ + "textDocument": { "uri": lib_uri, "version": 2 }, + "contentChanges": [ { "text": lib_broken } ], + }), + ); + let after_break = client.drain_publishes(Duration::from_secs(5)); + let main_broken = after_break + .iter() + .find(|(uri, _)| uri == &main_uri) + .unwrap_or_else(|| { + panic!("main.inf was not republished after lib changed: {after_break:?}") + }); + assert!( + !main_broken.1.is_empty(), + "the dependent main.inf is republished with errors" + ); + + // Fix lib: main's now-stale errors must clear via another fresh republish. + client.send_notification( + "textDocument/didChange", + json!({ + "textDocument": { "uri": lib_uri, "version": 3 }, + "contentChanges": [ { "text": lib_ok } ], + }), + ); + let after_fix = client.drain_publishes(Duration::from_secs(5)); + let main_fixed = after_fix + .iter() + .find(|(uri, _)| uri == &main_uri) + .unwrap_or_else(|| { + panic!("main.inf was not republished after lib was fixed: {after_fix:?}") + }); + assert!( + main_fixed.1.is_empty(), + "fixing lib clears main's stale errors, got {:?}", + main_fixed.1 + ); + + client.shutdown_exit_ok(); +} + +// --- 20. a request after shutdown is answered InvalidRequest ------------------ + +#[test] +fn request_after_shutdown_is_answered_invalid_request() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + + client.shutdown(); + + // Per the LSP spec, a request received between `shutdown` and `exit` is + // answered with InvalidRequest (-32600) while the server keeps waiting for + // `exit` — it must not tear the connection down with no response. + let response = client.request( + "textDocument/hover", + json!({ + "textDocument": { "uri": "file:///inf-test/x.inf" }, + "position": { "line": 0, "character": 0 } + }), + ); + assert_eq!( + response["error"]["code"], + json!(-32600), + "a post-shutdown request is InvalidRequest, got {response}" + ); + + // The server is still alive and exits cleanly on the exit notification. + client.exit(); + let status = client.wait_for_exit(); + assert_eq!( + status.code(), + Some(0), + "the server still exits cleanly after answering the post-shutdown request" + ); +} + +// --- 21. a URI carrying a query or fragment is ignored, not analyzed --------- + +#[test] +fn query_or_fragment_uri_is_ignored_without_crashing() { + let mut client = LspClient::spawn(); + client.initialize_default(true); + let source = "fn f() -> i32 { return 1; }"; + let (_dir, uri) = fixture("uri-query", source); + client.did_open(&uri, source, 1); + + // A `file://` URI carrying a query is not a document this server can serve. It + // must be ignored — never interned as the garbage path `main.inf?ver=1` and + // published under it. Send it raw, then confirm no publish names it. + let query_uri = format!("{uri}?ver=1"); + client.send_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": query_uri, + "languageId": "inference", + "version": 1, + "text": "fn g() {}" + } + }), + ); + let published = client.drain_publishes(Duration::from_secs(1)); + assert!( + !published + .iter() + .any(|(published_uri, _)| published_uri.contains("?ver=1")), + "a query-bearing URI is not analyzed or published, got {published:?}" + ); + + // A subsequent request against the real document still works. + let hover = hover_request(&mut client, &uri, pos_at(source, "f(")); + assert!( + hover.get("error").is_none(), + "the server survived the query-bearing open" + ); + + client.shutdown_exit_ok(); +} diff --git a/apps/lsp/tests/harness/mod.rs b/apps/lsp/tests/harness/mod.rs new file mode 100644 index 00000000..e76cfdf1 --- /dev/null +++ b/apps/lsp/tests/harness/mod.rs @@ -0,0 +1,638 @@ +//! A minimal Language Server Protocol test client. +//! +//! It spawns the built `inference-lsp` binary and speaks the LSP base protocol +//! (framed JSON-RPC) over its stdio. Every read is bounded by a hard timeout, so +//! a server that hangs makes the test *fail* rather than stall the run. Messages +//! are kept as raw [`serde_json::Value`]s and asserted with JSON pointer paths, +//! so the tests exercise the real wire format, not a typed re-encoding of it. +//! +//! A background reader thread parses the child's stdout into framed messages. If +//! any byte of that stream is not valid framing, the reader reports it as a +//! [`Incoming::Framing`] error instead of a message — which is what lets a test +//! assert the server never writes non-protocol bytes to stdout. + +#![allow(dead_code)] // A shared test-support module; not every helper is used by every test. + +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, ExitStatus, Stdio}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +/// How long any single message read waits before the test gives up on the server. +/// Generous because the suite runs its server spawns in parallel and shares the +/// machine with whatever else CI is compiling; a hang still fails, just later. +const RECV_TIMEOUT: Duration = Duration::from_secs(30); + +/// How long to wait for the child process to exit before killing it and failing. +const EXIT_TIMEOUT: Duration = Duration::from_secs(30); + +/// One item the reader thread pulls off the child's stdout. +enum Incoming { + /// A well-framed JSON-RPC message. + Message(Value), + /// The stream ended cleanly between messages. + Eof, + /// A stdout byte sequence that was not valid framed protocol. The server must + /// never produce this; a test treats it as a failure. + Framing(String), +} + +/// A spawned `inference-lsp` process with a framed-JSON-RPC channel to it. +pub struct LspClient { + child: Child, + stdin: ChildStdin, + incoming: Receiver, + reader: Option>, + /// Messages received while waiting for a different, specific one. + pending: Vec, + next_id: i64, + /// Set once a framing violation is observed; asserted absent at shutdown. + framing_error: Option, +} + +impl LspClient { + /// Spawns the compiled server binary with piped stdio and starts the reader. + #[must_use] + pub fn spawn() -> Self { + let mut child = Command::new(env!("CARGO_BIN_EXE_inference-lsp")) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn inference-lsp"); + + let stdin = child.stdin.take().expect("child stdin"); + let stdout = child.stdout.take().expect("child stdout"); + + let (tx, rx) = mpsc::channel(); + let reader = std::thread::spawn(move || read_loop(stdout, &tx)); + + LspClient { + child, + stdin, + incoming: rx, + reader: Some(reader), + pending: Vec::new(), + next_id: 0, + framing_error: None, + } + } + + // --- Low-level protocol ------------------------------------------------ + + /// Sends a request and returns the id it was assigned. + pub fn send_request(&mut self, method: &str, params: Value) -> i64 { + self.next_id += 1; + let id = self.next_id; + self.write_message(&json!({ + "jsonrpc": "2.0", + "id": id, + "method": method, + "params": params, + })); + id + } + + /// Sends a notification (no id, no response expected). + pub fn send_notification(&mut self, method: &str, params: Value) { + self.write_message(&json!({ + "jsonrpc": "2.0", + "method": method, + "params": params, + })); + } + + /// Receives the next message in arrival order, failing on timeout or a + /// prematurely closed / corrupt stream. + pub fn recv_message(&mut self) -> Value { + if !self.pending.is_empty() { + return self.pending.remove(0); + } + match self.incoming.recv_timeout(RECV_TIMEOUT) { + Ok(Incoming::Message(value)) => value, + Ok(Incoming::Eof) => panic!("server closed its stdout while a message was expected"), + Ok(Incoming::Framing(error)) => { + self.framing_error = Some(error.clone()); + panic!("server wrote non-protocol bytes to stdout: {error}"); + } + Err(RecvTimeoutError::Timeout) => { + panic!("timed out waiting for a message from the server") + } + Err(RecvTimeoutError::Disconnected) => panic!("the reader thread ended unexpectedly"), + } + } + + /// Waits for the response to `id`, buffering any notifications that arrive + /// first so a later `wait_for_notification` can still find them. + pub fn wait_for_response(&mut self, id: i64) -> Value { + loop { + if let Some(index) = self + .pending + .iter() + .position(|message| response_id(message) == Some(id)) + { + return self.pending.remove(index); + } + let message = self.recv_message(); + if response_id(&message) == Some(id) { + return message; + } + self.pending.push(message); + } + } + + /// Waits for the next notification with `method`, buffering everything else. + pub fn wait_for_notification(&mut self, method: &str) -> Value { + loop { + if let Some(index) = self + .pending + .iter() + .position(|message| notification_method(message) == Some(method)) + { + return self.pending.remove(index); + } + let message = self.recv_message(); + if notification_method(&message) == Some(method) { + return message; + } + self.pending.push(message); + } + } + + // --- Convenience ------------------------------------------------------- + + /// Sends a request and returns the whole response object (with `result` or + /// `error`). + pub fn request(&mut self, method: &str, params: Value) -> Value { + let id = self.send_request(method, params); + self.wait_for_response(id) + } + + /// Runs the initialize handshake with the given client capabilities and + /// returns the `InitializeResult` value, then sends `initialized`. + pub fn initialize(&mut self, capabilities: Value) -> Value { + let response = self.request( + "initialize", + json!({ + "processId": Value::Null, + "rootUri": Value::Null, + "capabilities": capabilities, + }), + ); + assert!( + response.get("error").is_none(), + "initialize failed: {response}" + ); + let result = response + .get("result") + .cloned() + .expect("initialize returns a result"); + self.send_notification("initialized", json!({})); + result + } + + /// The common case: initialize declaring (or not) hierarchical document-symbol + /// support, returning the `InitializeResult`. + pub fn initialize_default(&mut self, hierarchical_symbols: bool) -> Value { + self.initialize(json!({ + "textDocument": { + "documentSymbol": { + "hierarchicalDocumentSymbolSupport": hierarchical_symbols, + } + } + })) + } + + /// Opens a document and returns the diagnostics that its `publishDiagnostics` + /// carries. + pub fn did_open(&mut self, uri: &str, text: &str, version: i64) -> PublishedDiagnostics { + self.send_notification( + "textDocument/didOpen", + json!({ + "textDocument": { + "uri": uri, + "languageId": "inference", + "version": version, + "text": text, + } + }), + ); + self.wait_for_publish(uri) + } + + /// Replaces a document's whole text (full-sync) and returns the new + /// diagnostics. + pub fn did_change(&mut self, uri: &str, text: &str, version: i64) -> PublishedDiagnostics { + self.send_notification( + "textDocument/didChange", + json!({ + "textDocument": { "uri": uri, "version": version }, + "contentChanges": [ { "text": text } ], + }), + ); + self.wait_for_publish(uri) + } + + /// Closes a document and returns the (expected empty) cleared diagnostics. + pub fn did_close(&mut self, uri: &str) -> PublishedDiagnostics { + self.send_notification( + "textDocument/didClose", + json!({ "textDocument": { "uri": uri } }), + ); + self.wait_for_publish(uri) + } + + /// Collects every `publishDiagnostics` that arrives within `window`, as + /// `(uri, diagnostics)` pairs in arrival order. + /// + /// One document notification legitimately triggers several publishes (the + /// notified document plus every other open one), so a test that observes the + /// cross-document republish drains the whole burst rather than waiting on a + /// single URI. Already-buffered publishes are taken first; non-publish + /// messages stay buffered for later `wait_for_*` calls. + pub fn drain_publishes(&mut self, window: Duration) -> Vec<(String, Vec)> { + let mut collected = Vec::new(); + let mut index = 0; + while index < self.pending.len() { + if notification_method(&self.pending[index]) == Some("textDocument/publishDiagnostics") + { + collected.push(publish_pair(&self.pending.remove(index))); + } else { + index += 1; + } + } + + let deadline = Instant::now() + window; + loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return collected; + } + match self.incoming.recv_timeout(remaining) { + Ok(Incoming::Message(value)) => { + if notification_method(&value) == Some("textDocument/publishDiagnostics") { + collected.push(publish_pair(&value)); + } else { + self.pending.push(value); + } + } + Ok(Incoming::Eof) => return collected, + Ok(Incoming::Framing(error)) => { + self.framing_error = Some(error); + return collected; + } + Err(RecvTimeoutError::Timeout) => return collected, + Err(RecvTimeoutError::Disconnected) => return collected, + } + } + } + + /// Waits for a `publishDiagnostics` notification for `uri`. + pub fn wait_for_publish(&mut self, uri: &str) -> PublishedDiagnostics { + loop { + let message = self.wait_for_notification("textDocument/publishDiagnostics"); + let params = &message["params"]; + if params["uri"] == json!(uri) { + return PublishedDiagnostics { + version: params.get("version").cloned().unwrap_or(Value::Null), + diagnostics: params["diagnostics"] + .as_array() + .cloned() + .unwrap_or_default(), + }; + } + } + } + + // --- Lifecycle --------------------------------------------------------- + + /// Sends the shutdown request and asserts its result is JSON `null`. + pub fn shutdown(&mut self) { + let response = self.request("shutdown", Value::Null); + assert!( + response.get("error").is_none(), + "shutdown returned an error: {response}" + ); + assert_eq!( + response.get("result"), + Some(&Value::Null), + "shutdown result must be null, got {response}" + ); + } + + /// Sends the exit notification. + pub fn exit(&mut self) { + self.send_notification("exit", Value::Null); + } + + /// Drains any trailing messages, asserts the stream ended cleanly with no + /// framing violation, and returns the process exit status (killing and + /// failing if it does not exit in time). + pub fn wait_for_exit(&mut self) -> ExitStatus { + self.drain_until_eof(); + assert!( + self.framing_error.is_none(), + "server wrote non-protocol bytes to stdout: {:?}", + self.framing_error + ); + + let deadline = Instant::now() + EXIT_TIMEOUT; + loop { + match self.child.try_wait().expect("poll child") { + Some(status) => return status, + None if Instant::now() >= deadline => { + let _ = self.child.kill(); + panic!("server did not exit within {EXIT_TIMEOUT:?}"); + } + None => std::thread::sleep(Duration::from_millis(10)), + } + } + } + + /// The full happy-path lifecycle tail: shutdown, exit, and assert exit code 0. + pub fn shutdown_exit_ok(&mut self) { + self.shutdown(); + self.exit(); + let status = self.wait_for_exit(); + assert!( + status.success(), + "clean shutdown must exit 0, got {status:?}" + ); + } + + /// Reads until the stream ends, keeping notifications in `pending` and + /// recording any framing violation. Used before waiting on process exit. + fn drain_until_eof(&mut self) { + loop { + match self.incoming.recv_timeout(RECV_TIMEOUT) { + Ok(Incoming::Message(value)) => self.pending.push(value), + Ok(Incoming::Eof) => return, + Ok(Incoming::Framing(error)) => { + self.framing_error = Some(error); + return; + } + Err(RecvTimeoutError::Timeout) => { + panic!("server did not close its stdout within {RECV_TIMEOUT:?}") + } + Err(RecvTimeoutError::Disconnected) => return, + } + } + } + + fn write_message(&mut self, message: &Value) { + let body = serde_json::to_vec(message).expect("serialize message"); + let header = format!("Content-Length: {}\r\n\r\n", body.len()); + self.stdin + .write_all(header.as_bytes()) + .expect("write header"); + self.stdin.write_all(&body).expect("write body"); + self.stdin.flush().expect("flush"); + } +} + +impl Drop for LspClient { + fn drop(&mut self) { + // A panicking test must never leak a live server process. + let _ = self.child.kill(); + let _ = self.child.wait(); + if let Some(reader) = self.reader.take() { + let _ = reader.join(); + } + } +} + +/// The payload of a `textDocument/publishDiagnostics` notification. +pub struct PublishedDiagnostics { + pub version: Value, + pub diagnostics: Vec, +} + +impl PublishedDiagnostics { + /// The first diagnostic whose `code` equals `code`, if any. + #[must_use] + pub fn by_code(&self, code: &str) -> Option<&Value> { + self.diagnostics.iter().find(|d| d["code"] == json!(code)) + } +} + +/// The reader thread: parse framed messages off `stdout` until EOF or a violation. +fn read_loop(stdout: std::process::ChildStdout, tx: &Sender) { + let mut reader = BufReader::new(stdout); + loop { + match read_one(&mut reader) { + Ok(Some(value)) => { + if tx.send(Incoming::Message(value)).is_err() { + return; + } + } + Ok(None) => { + let _ = tx.send(Incoming::Eof); + return; + } + Err(error) => { + let _ = tx.send(Incoming::Framing(error)); + return; + } + } + } +} + +/// Reads one framed message: `Content-Length` headers, a blank line, then exactly +/// that many body bytes. `Ok(None)` is a clean end of stream between messages. +fn read_one(reader: &mut impl BufRead) -> Result, String> { + let mut content_length: Option = None; + let mut saw_header = false; + loop { + let mut line = String::new(); + let read = reader.read_line(&mut line).map_err(|e| e.to_string())?; + if read == 0 { + return if saw_header { + Err("stream ended in the middle of a message header".to_owned()) + } else { + Ok(None) + }; + } + if line == "\r\n" || line == "\n" { + break; + } + saw_header = true; + let (key, value) = line + .split_once(':') + .ok_or_else(|| format!("malformed header line: {line:?}"))?; + if key.trim().eq_ignore_ascii_case("content-length") { + let parsed = value + .trim() + .parse() + .map_err(|_| format!("invalid content-length: {value:?}"))?; + content_length = Some(parsed); + } + } + + let length = content_length.ok_or("message had no content-length header")?; + let mut body = vec![0u8; length]; + reader.read_exact(&mut body).map_err(|e| e.to_string())?; + serde_json::from_slice(&body) + .map(Some) + .map_err(|e| format!("message body was not valid JSON: {e}")) +} + +/// The request id a response message answers, if it is a response. +fn response_id(message: &Value) -> Option { + if message.get("method").is_some() { + return None; // A request/notification, not a response. + } + message.get("id").and_then(Value::as_i64) +} + +/// The method of a notification (a message with a method but no id). +fn notification_method(message: &Value) -> Option<&str> { + if message.get("id").is_some() { + return None; + } + message.get("method").and_then(Value::as_str) +} + +/// The `(uri, diagnostics)` a `publishDiagnostics` notification carries. +fn publish_pair(message: &Value) -> (String, Vec) { + let params = &message["params"]; + let uri = params["uri"].as_str().unwrap_or_default().to_owned(); + let diagnostics = params["diagnostics"] + .as_array() + .cloned() + .unwrap_or_default(); + (uri, diagnostics) +} + +// --- Position and URI helpers ---------------------------------------------- + +/// The 0-based line / UTF-16 character LSP position of `byte_offset` in `source`. +fn lsp_position(source: &str, byte_offset: usize) -> Value { + let mut line = 0u32; + let mut character = 0u32; + for (index, ch) in source.char_indices() { + if index >= byte_offset { + break; + } + if ch == '\n' { + line += 1; + character = 0; + } else { + character += ch.len_utf16() as u32; + } + } + json!({ "line": line, "character": character }) +} + +/// The LSP position at the start of the first occurrence of `needle`. +#[must_use] +pub fn pos_at(source: &str, needle: &str) -> Value { + let offset = source + .find(needle) + .unwrap_or_else(|| panic!("{needle:?} not found in source")); + lsp_position(source, offset) +} + +/// The LSP position at the start of the `n`-th (0-based) occurrence of `needle`. +#[must_use] +pub fn pos_at_nth(source: &str, needle: &str, n: usize) -> Value { + let mut start = 0; + for _ in 0..n { + let found = source[start..] + .find(needle) + .unwrap_or_else(|| panic!("fewer than {} occurrences of {needle:?}", n + 1)); + start += found + needle.len(); + } + let found = source[start..] + .find(needle) + .unwrap_or_else(|| panic!("fewer than {} occurrences of {needle:?}", n + 1)); + lsp_position(source, start + found) +} + +/// The LSP position just past the end of the first occurrence of `needle`. +#[must_use] +pub fn pos_after(source: &str, needle: &str) -> Value { + let offset = source + .find(needle) + .unwrap_or_else(|| panic!("{needle:?} not found in source")); + lsp_position(source, offset + needle.len()) +} + +/// The LSP position at the very end of `source` (one past its last byte). +#[must_use] +pub fn pos_end(source: &str) -> Value { + lsp_position(source, source.len()) +} + +/// A throwaway directory under the system temp dir, removed on drop. Fixtures for +/// the e2e tests live here — never at a filesystem root, never in the repo. +pub struct TempDir { + pub path: PathBuf, +} + +impl TempDir { + #[must_use] + pub fn new(tag: &str) -> Self { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock after epoch") + .as_nanos(); + let path = std::env::temp_dir().join(format!( + "inference-lsp-e2e-{tag}-{}-{nanos}", + std::process::id() + )); + std::fs::create_dir_all(&path).expect("create temp dir"); + TempDir { path } + } + + /// Writes `contents` to `/`, creating parents, and returns the + /// absolute path. + pub fn write(&self, relative: &str, contents: &str) -> PathBuf { + let dest = self.path.join(relative); + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent).expect("create fixture parent dir"); + } + std::fs::write(&dest, contents).expect("write fixture"); + dest + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +/// The `file://` URI naming `path`, mirroring the server's own URI encoding +/// (forward slashes, a leading slash before a drive letter, percent-encoded +/// non-path bytes) so a POSIX and a Windows host each round-trip through the same +/// spelling the server expects. +#[must_use] +pub fn path_to_uri(path: &Path) -> String { + let text = path.to_str().expect("fixture path is valid UTF-8"); + let normalized = text.replace('\\', "/"); + let absolute = if normalized.starts_with('/') { + normalized + } else { + format!("/{normalized}") + }; + format!("file://{}", percent_encode(&absolute)) +} + +fn percent_encode(input: &str) -> String { + const HEX: &[u8; 16] = b"0123456789ABCDEF"; + let mut out = String::with_capacity(input.len()); + for &byte in input.as_bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/' | b':') { + out.push(byte as char); + } else { + out.push('%'); + out.push(HEX[(byte >> 4) as usize] as char); + out.push(HEX[(byte & 0x0f) as usize] as char); + } + } + out +} diff --git a/core/analysis/src/call_graph.rs b/core/analysis/src/call_graph.rs index e5ea62f9..c8f52be7 100644 --- a/core/analysis/src/call_graph.rs +++ b/core/analysis/src/call_graph.rs @@ -348,26 +348,24 @@ fn type_name_of(arena: &AstArena, expr: ExprId) -> Option { /// (`Free`) target distinct nodes. If no candidate names an existing node the /// edge is dropped, so callers can never manufacture a false edge. pub(crate) fn resolve_adjacency(nodes: &[FnNode]) -> Vec> { - // Build the key → index map with an explicit insert so a duplicate key is a - // loud failure rather than a silent last-wins overwrite. Two nodes sharing a - // key would mean a recursive function's self-edge could resolve to a - // different node, masking the cycle from the recursion check (A035). - // `FnKey` is injective by construction and the type checker rejects genuine - // duplicate definitions first, so a collision here is an upstream invariant - // break; surface it in debug builds and keep the first node in release so the - // graph stays usable. + // Build the key → index map, keeping the first node on a duplicate key. + // + // On the fail-fast compiler path `FnKey` is injective: the type checker + // rejects genuine duplicate definitions before analysis runs, so no two nodes + // share a key and this map is a plain bijection — the branch that discards a + // later duplicate is never taken, and A035/A036 outputs on valid programs are + // unchanged. The IDE resilient path has no such guarantee: error recovery + // lowers every unparseable top-level construct to an `` placeholder + // function (a single stray `forall { }` lowers to two), and a program caught + // mid-edit can momentarily name the same function twice, so distinct nodes can + // carry the same key. Keeping the first node is a deterministic, total + // degradation — an already-broken program may have a self-edge resolve to the + // wrong same-keyed node, at worst making A035/A036 miss a diagnostic on code + // that does not yet compile. That is never a false positive, and never a panic + // that would abort the analysis (or, in debug builds, the whole LSP process). let mut index: HashMap<&FnKey, usize> = HashMap::with_capacity(nodes.len()); for (i, n) in nodes.iter().enumerate() { - if let Some(&existing) = index.get(&n.key) { - debug_assert!( - false, - "duplicate call-graph key `{}` at node {i} (already node {existing}); \ - FnKey must be injective or A035/A036 may miss a self-edge", - n.key - ); - continue; - } - index.insert(&n.key, i); + index.entry(&n.key).or_insert(i); } nodes @@ -564,6 +562,32 @@ mod tests { ); } + /// The IDE resilient path can present two nodes under the same `FnKey`: a + /// single stray `forall { }` lowers to two `` placeholder functions, + /// and a program mid-edit can name the same function twice. Building the + /// adjacency must not panic; it keeps the first same-keyed node + /// deterministically, so an edge naming that key resolves to it and every + /// other node still yields a row. + #[test] + fn adjacency_keeps_first_node_on_duplicate_key() { + let dup_key = || FnKey::free_in(Vec::new(), ""); + let nodes = vec![ + node(dup_key(), vec![]), + node(dup_key(), vec![]), + node( + FnKey::free_in(Vec::new(), "caller"), + vec![free_edge("", Vec::new())], + ), + ]; + let adj = resolve_adjacency(&nodes); + assert_eq!(adj.len(), 3, "every node yields an adjacency row"); + assert_eq!( + adj[2], + vec![(0, loc())], + "an edge naming the duplicated key resolves to the first same-keyed node" + ); + } + /// The FAMILY 2 regression witness at the graph level: a struct associated /// function (`mid::make` in file `a`, a `Method` key) and a same-named free /// function in the sibling file (`make` in `a/mid`, a `Free` key) are diff --git a/core/inference/src/lib.rs b/core/inference/src/lib.rs index 6aff4895..b972d13f 100644 --- a/core/inference/src/lib.rs +++ b/core/inference/src/lib.rs @@ -264,6 +264,23 @@ pub use inference_analysis::errors::{AnalysisErrors, AnalysisResult}; use inference_ast::arena::AstArena; pub use inference_type_checker::typed_context::TypedContext; +/// Re-export of the lossless type-check entry point and its result types so +/// downstream consumers (IDE/LSP) get the structured diagnostics and the +/// partially-populated [`TypedContext`] without a direct dependency on +/// `inference-type-checker`. Mirrors the [`type_check`] wrapper, but keeps the +/// per-error [`TypeCheckError`] and file label instead of joining them into one +/// string. +/// +/// [`TypeCheckError`]: inference_type_checker::errors::TypeCheckError +pub use inference_type_checker::{TypeCheckDiagnostic, TypeCheckOutcome}; + +/// Re-export of the structured type-check error so downstream consumers can +/// match on a [`TypeCheckDiagnostic`]'s variant and read its source location +/// (via [`TypeCheckError::location`]) without a direct dependency on +/// `inference-type-checker`. Mirrors the [`WasmToVError`]/[`LinkError`] re-exports. +/// +/// [`TypeCheckError::location`]: inference_type_checker::errors::TypeCheckError::location +pub use inference_type_checker::errors::TypeCheckError; pub mod errors; pub mod extern_prelude; @@ -271,7 +288,10 @@ mod project; pub mod wasm_link; pub use errors::InferenceError; -pub use project::{parse_project, ProjectParse, ProjectWarning}; +pub use project::{ + load_project_resilient, parse_project, DiskLoader, FileLoader, FileParseErrors, ImportProblem, + LoadedFile, ProjectParse, ProjectWarning, ResilientProjectParse, +}; /// Re-export of `rustc_hash::FxHashMap` so library consumers of `inference` /// can construct the spec-funcs map passed to [`wasm_to_v`] without taking a @@ -506,6 +526,24 @@ pub fn type_check(arena: AstArena) -> anyhow::Result { Ok(type_checker_builder.typed_context()) } +/// Type-checks `arena` losslessly, returning the [`TypedContext`] together with +/// the structured type-check diagnostics instead of one aggregated string. +/// +/// Unlike [`type_check`], which discards the context on any error and joins the +/// errors into a single [`anyhow::Error`], this preserves every error's variant, +/// per-file-local source location, and optional module-path file label, and +/// returns the (possibly partially populated) context alongside them. It is the +/// entry point tooling (IDE/LSP) uses to report diagnostics and still serve +/// features on the parts of the program that type-checked. +/// +/// See [`TypeCheckOutcome`] for the guarantees the returned context provides +/// when errors are present. The runtime compilation pipeline keeps using +/// [`type_check`]; the two share exactly one checking implementation. +#[must_use = "the outcome carries both the typed context and the diagnostics"] +pub fn type_check_with_diagnostics(arena: AstArena) -> TypeCheckOutcome { + inference_type_checker::check_with_diagnostics(arena) +} + /// Performs semantic analysis on the typed AST. /// /// This function runs control flow analysis passes on the typed AST, diff --git a/core/inference/src/project.rs b/core/inference/src/project.rs index 13ad1aa5..ed0c975e 100644 --- a/core/inference/src/project.rs +++ b/core/inference/src/project.rs @@ -25,7 +25,8 @@ use std::path::{Path, PathBuf}; use anyhow::anyhow; use inference_ast::arena::AstArena; -use inference_ast::nodes::{Directive, SourceFileData, UseDirective}; +use inference_ast::nodes::{Directive, Location, SourceFileData, UseDirective}; +use inference_parser::ParseError; use rustc_hash::FxHashSet; use crate::errors::InferenceError; @@ -37,6 +38,45 @@ const SOURCE_EXTENSION: &str = "inf"; /// "did you mean" suggestion for a missing import. const SUGGESTION_MAX_DISTANCE: usize = 2; +/// Reads source files for the import-closure walk. +/// +/// The walk itself is pure: it decides which files a program's `use` graph +/// reaches and where each one lives, but never touches the filesystem directly. +/// A `FileLoader` supplies the two capabilities it needs — existence and +/// contents — so the same resolution logic drives both the compiler (a +/// [`DiskLoader`]) and the IDE (an overlay-then-disk loader that lets an open, +/// unsaved buffer shadow its on-disk contents). Keeping one walk behind this +/// seam is what guarantees the compiler and the IDE can never disagree about +/// which files a program imports. +pub trait FileLoader { + /// Whether a source file exists at `path`. + #[must_use = "the existence check is the reason to call this"] + fn exists(&self, path: &Path) -> bool; + + /// Reads the full source text at `path`. + /// + /// # Errors + /// + /// Returns the underlying I/O error if the file cannot be read. + fn read(&self, path: &Path) -> std::io::Result; +} + +/// A [`FileLoader`] backed directly by the filesystem, used by the compiler +/// front end. Existence is a plain `is_file` probe and reads go straight to +/// `std::fs`. +#[derive(Debug, Default)] +pub struct DiskLoader; + +impl FileLoader for DiskLoader { + fn exists(&self, path: &Path) -> bool { + path.is_file() + } + + fn read(&self, path: &Path) -> std::io::Result { + std::fs::read_to_string(path) + } +} + /// Outcome of parsing a project: the unified arena plus any non-fatal warnings. /// /// Warnings are returned rather than printed so library code stays silent; the @@ -70,6 +110,114 @@ impl std::fmt::Display for ProjectWarning { } } +/// A single reachable file discovered by the resilient walk: its canonical +/// module path (empty for the entry file) paired with the absolute path it was +/// read from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LoadedFile { + /// Source-root-relative module path; empty for the entry file. + pub module_path: Vec, + /// The path the file was read from. + pub path: PathBuf, +} + +/// A file's own syntax errors, labeled with the file it belongs to. +/// +/// Source locations in a merged multi-file arena are per-file-local, so the +/// module path is required to attribute each error to the right file. The entry +/// file carries an empty module path. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FileParseErrors { + /// Source-root-relative module path of the file; empty for the entry file. + pub module_path: Vec, + /// The syntax errors the resilient parser collected for this file. + pub errors: Vec, +} + +/// A `use` import that could not be resolved to a file on the loader. +/// +/// Unlike the compiler front end, which fails fast on the first missing import, +/// the resilient walk records each one as structured data anchored at the `use` +/// directive so the IDE can render a diagnostic in place without aborting the +/// rest of the analysis. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ImportProblem { + /// The `::`-joined import path as written (`lib::arith`). + pub referenced_as: String, + /// The absolute path the resolver looked for. + pub expected_path: PathBuf, + /// The nearest sibling `.inf` stem, when one is within the suggestion + /// distance; used to offer a "did you mean" hint. + pub suggestion: Option, + /// Location of the `use` directive within the importing file. Offsets are + /// per-file-local, to be resolved against the importing file's line index. + pub location: Location, + /// Module path of the importing file, naming which file `location` belongs + /// to; empty for the entry file. + pub importing_module_path: Vec, +} + +/// The lossless outcome of the resilient project walk, for IDE use. +/// +/// Where [`parse_project`] fails fast and discards everything on the first +/// problem, this returns the merged arena built from every reachable file that +/// could be read (each parsed resiliently) alongside the problems collected +/// along the way, so an editor can serve features on the healthy parts of a +/// program with broken imports or syntax errors. +#[derive(Debug)] +#[must_use = "the resilient parse carries the arena and every collected problem"] +pub struct ResilientProjectParse { + /// Every reachable file that could be read, lowered into one arena in + /// canonical order (entry first, then imports sorted by module path). + pub arena: AstArena, + /// Per-file syntax errors, each labeled with its file's module path. + pub parse_errors: Vec, + /// `use` imports that did not resolve to a file. + pub import_problems: Vec, + /// Always empty. The resilient walk does not scan the source tree for + /// unreachable files: that scan enumerates and canonicalizes every `.inf` + /// under the source root — work an editor would repeat on every keystroke, + /// growing with the tree — and no IDE consumer reads the result. The field is + /// retained so the resilient outcome mirrors [`ProjectParse`]'s shape; the + /// fail-fast [`parse_project`] still populates its own warnings. + pub warnings: Vec, + /// Every file actually read, in discovery order: its module path and the + /// path it was read from. Serves as both the closure file set and the + /// module-path → path mapping. + pub files: Vec, +} + +/// A problem encountered while walking the import closure. Recorded by the walk +/// in the exact sequence the fail-fast front end would surface them, so +/// [`parse_project`] can translate the first one and stay byte-identical. +enum WalkProblem { + /// A reachable file could not be read. + Io { + path: PathBuf, + source: std::io::Error, + }, + /// A `use` path segment is not a usable file/directory name. + InvalidSegment { + referenced_as: String, + segment: String, + }, + /// A file failed to parse (its own syntax errors). + FileParse { + module_path: Vec, + errors: Vec, + }, + /// A `use` named a file the loader has no contents for. + MissingImport(ImportProblem), +} + +/// The raw result of one closure walk, shared by the fail-fast compiler entry +/// and the resilient IDE entry. +struct WalkOutcome { + arena: AstArena, + files: Vec, + problems: Vec, +} + /// Parses a project starting from `entry`, returning one arena holding every /// import-reachable file plus any unreachable-file warnings. /// @@ -79,6 +227,10 @@ impl std::fmt::Display for ProjectWarning { /// file is read and parsed exactly once, into the shared arena as it is /// discovered. Import cycles are permitted and terminate via a visited set. /// +/// Reads go through a [`DiskLoader`] and the walk fails fast on the first +/// problem, preserving the exact errors and ordering the compiler front end has +/// always produced. +/// /// # Errors /// /// Returns [`InferenceError::NoSourceRoot`] if `entry` has no parent directory, @@ -93,107 +245,362 @@ pub fn parse_project(entry: &Path) -> anyhow::Result { .ok_or_else(|| InferenceError::NoSourceRoot(entry.to_path_buf()))? .to_path_buf(); - let arena = parse_reachable_files(entry, &src_root)?; - let warnings = collect_unreachable_warnings(&arena, &src_root, entry); + let WalkOutcome { + arena, problems, .. + } = resolve_closure(entry, &src_root, &DiskLoader, false); + if let Some(problem) = problems.into_iter().next() { + return Err(fail_fast_error(problem, entry)); + } + + let warnings = collect_unreachable_warnings(&arena, &src_root, entry); Ok(ProjectParse { arena, warnings }) } -/// Breadth-first walk of the import closure, parsing every reachable file exactly -/// once into a shared arena. Each file is keyed by its canonical module path so a -/// file reached twice (including through a cycle) is parsed once. +/// Resiliently loads the import closure of `entry` through `loader`, collecting +/// every problem instead of failing fast. +/// +/// Imports resolve exactly as they do for [`parse_project`] — the same +/// `/.inf` mapping, the reserved `use root;` handle, and +/// entry self-import deduplication — but every file is parsed resiliently and +/// every problem (a file's syntax errors, an unresolved import) is recorded +/// while the walk keeps going. Reads consult `loader`, so an IDE overlay can +/// shadow on-disk contents. The returned arena holds every file that could be +/// read, so editor features still work on the healthy parts of a broken program. +/// +/// The source root is `entry`'s parent directory (or the empty path when it has +/// none, matching how a bare filename resolves relative to the working +/// directory). Unreachable-file warnings and missing-import suggestions are +/// computed against the filesystem, matching [`parse_project`]. +pub fn load_project_resilient(entry: &Path, loader: &dyn FileLoader) -> ResilientProjectParse { + let src_root = entry + .parent() + .unwrap_or_else(|| Path::new("")) + .to_path_buf(); + + let WalkOutcome { + arena, + files, + problems, + } = resolve_closure(entry, &src_root, loader, true); + + let mut parse_errors = Vec::new(); + let mut import_problems = Vec::new(); + for problem in problems { + match problem { + WalkProblem::FileParse { + module_path, + errors, + } => parse_errors.push(FileParseErrors { + module_path, + errors, + }), + WalkProblem::MissingImport(import) => import_problems.push(import), + // A read race (the loader claimed a file exists, then failed to read + // it) or an invalid segment (unreachable from valid lexer output) + // simply drops the affected file/directive from the closure. + WalkProblem::Io { .. } | WalkProblem::InvalidSegment { .. } => {} + } + } + + // The resilient walk never scans the source tree for unreachable files. The + // scan enumerates and canonicalizes every `.inf` file under the source root, + // which for an editor runs on every keystroke and grows with the tree — yet no + // IDE consumer reads these warnings. They are always empty here; the fail-fast + // compiler keeps the scan (see [`ResilientProjectParse::warnings`]). + // The resilient walk never scans the source tree for unreachable files. The + // scan enumerates and canonicalizes every `.inf` file under the source root, + // which for an editor runs on every keystroke and grows with the tree — yet no + // IDE consumer reads these warnings. They are always empty here; the fail-fast + // compiler keeps the scan (see [`ResilientProjectParse::warnings`]). + ResilientProjectParse { + arena, + parse_errors, + import_problems, + warnings: Vec::new(), + files, + } +} + +/// Breadth-first walk of the import closure through `loader`, parsing every +/// reachable file exactly once into a shared arena. Each file is keyed by its +/// canonical module path so a file reached twice (including through a cycle) is +/// parsed once. +/// +/// When `resilient` is false the walk stops at the first problem it records +/// (fail-fast, for the compiler); when true it records every problem and keeps +/// going (for the IDE). Either way, problems are recorded in a fixed order per +/// file — its read error, then its own syntax errors, then its first invalid +/// segment, then its missing imports — so the fail-fast caller surfaces exactly +/// the error it always has. /// /// Files accumulate in discovery (BFS) order; the walk ends by reordering them /// into canonical order (see [`AstArena::canonicalize_source_file_order`]), the /// single source of truth downstream phases consume for ordering. -fn parse_reachable_files(entry: &Path, src_root: &Path) -> anyhow::Result { - let mut arena = AstArena::default(); - let mut visited: FxHashSet> = FxHashSet::default(); - let mut queue: VecDeque<(Vec, PathBuf)> = VecDeque::new(); - - // The entry is the one file with an empty module path. It is keyed by the - // empty segment list, but a `use main;` that resolves to the entry file - // carries the segments `["main"]`, which the visited set would not catch — so - // a path resolving to the entry file is recognized separately, below. - let entry_canonical = std::fs::canonicalize(entry).ok(); - visited.insert(Vec::new()); - queue.push_back((Vec::new(), entry.to_path_buf())); - - while let Some((module_path, file_path)) = queue.pop_front() { - let source = read_source(&file_path)?; - // `module_path` is moved into the arena by `parse_into` but still needed by - // the parse-error arm below, so clone it for the move. - let parsed = inference_parser::parse_into(arena, &source, module_path.clone()); - arena = parsed.arena; +fn resolve_closure( + entry: &Path, + src_root: &Path, + loader: &dyn FileLoader, + resilient: bool, +) -> WalkOutcome { + Walk::new(entry, src_root, loader, resilient).run() +} + +/// The mutable state of one closure walk. Holds the growing arena, the BFS +/// frontier, and the collected problems; its methods carry one file at a time +/// through read → parse → import resolution. +struct Walk<'a> { + src_root: &'a Path, + loader: &'a dyn FileLoader, + resilient: bool, + /// The entry's path exactly as given. A self-import that resolves back to the + /// entry is recognized by plain equality against this, which holds even for an + /// editor overlay that never reached disk (and so cannot be canonicalized). + entry_raw: PathBuf, + /// The entry's canonical path, used to also recognize a self-import that + /// reaches the entry through a different spelling or a symlink. `None` if the + /// entry cannot be canonicalized (e.g. an unsaved overlay buffer). + entry_canonical: Option, + arena: AstArena, + visited: FxHashSet>, + queue: VecDeque<(Vec, PathBuf)>, + files: Vec, + problems: Vec, +} + +impl<'a> Walk<'a> { + fn new(entry: &Path, src_root: &'a Path, loader: &'a dyn FileLoader, resilient: bool) -> Self { + let mut visited = FxHashSet::default(); + let mut queue = VecDeque::new(); + // The entry is the one file with an empty module path. A `use main;` that + // resolves back to the entry carries the segments `["main"]`, which the + // visited set would not catch — so a path resolving to the entry file is + // recognized separately, by comparing canonical paths. + visited.insert(Vec::new()); + queue.push_back((Vec::new(), entry.to_path_buf())); + Walk { + src_root, + loader, + resilient, + entry_raw: entry.to_path_buf(), + entry_canonical: std::fs::canonicalize(entry).ok(), + arena: AstArena::default(), + visited, + queue, + files: Vec::new(), + problems: Vec::new(), + } + } + + fn run(mut self) -> WalkOutcome { + while let Some((module_path, file_path)) = self.queue.pop_front() { + if self.process_file(&module_path, file_path) { + return self.into_outcome(); + } + } + + // Files were parsed in discovery (BFS) order; downstream phases consume + // canonical order as their single source of truth, so reorder now — + // before any `SourceFileId` is handed out. + self.arena.canonicalize_source_file_order(); + + // Discovery deduplicates files by module path (and self-imports of the + // entry), so each file appears exactly once. A duplicate would lower the + // same definitions twice; assert the invariant so a future discovery + // regression is caught here rather than in the output. + debug_assert!( + self.arena + .source_files() + .collect::>() + .windows(2) + .all(|w| w[0].module_path != w[1].module_path), + "discovered files must have unique module paths after deduplication" + ); + + self.into_outcome() + } + + fn into_outcome(self) -> WalkOutcome { + WalkOutcome { + arena: self.arena, + files: self.files, + problems: self.problems, + } + } + + /// Reads, parses, and resolves the imports of one popped file. Returns `true` + /// when a fail-fast walk recorded a problem and should stop. + fn process_file(&mut self, module_path: &[String], file_path: PathBuf) -> bool { + let source = match self.loader.read(&file_path) { + Ok(source) => source, + Err(source) => { + self.problems.push(WalkProblem::Io { + path: file_path, + source, + }); + return !self.resilient; + } + }; + + let parsed = inference_parser::parse_into( + std::mem::take(&mut self.arena), + &source, + module_path.to_vec(), + ); + self.arena = parsed.arena; + self.files.push(LoadedFile { + module_path: module_path.to_vec(), + path: file_path, + }); // Surface a file's own syntax errors before resolving its imports. A // rejected `use a::b::*;` still lowers to the segments `a::b`, so without - // this guard the glob would be probed as the file `a/b.inf`; when that + // this ordering the glob would be probed as the file `a/b.inf`; when that // file is absent, the "file not found" lookup would mask the educational - // glob diagnostic. Reporting the parse error first means the user sees why - // their directive is invalid rather than a misleading missing-file path. + // glob diagnostic. Capture the error spans before the errors move into the + // recorded problem: a `use` directive overlapping one of them is skipped + // below so the resilient walk mirrors the fail-fast ordering instead of + // resolving imports out of a directive that failed to parse. + let error_spans: Vec = parsed.errors.iter().map(|error| error.span).collect(); if !parsed.errors.is_empty() { - return Err(parse_error(&module_path, entry, &parsed.errors)); + self.problems.push(WalkProblem::FileParse { + module_path: module_path.to_vec(), + errors: parsed.errors, + }); + if !self.resilient { + return true; + } } - // `parse_into` lowers the file's `SourceFileData` after all of its defs and - // directives, so the file just parsed is the last one stored (pinned by - // `parse_into_allocates_the_new_file_last` in `core/parser`). - let file = arena - .last_source_file() - .expect("parse_into stores the file it just lowered"); - debug_assert_eq!( - file.module_path, module_path, - "parse_into must store the just-lowered file last" - ); + // `parse_into` lowers the file's `SourceFileData` after all of its defs + // and directives, so the file just parsed is the last one stored (pinned + // by `parse_into_allocates_the_new_file_last` in `core/parser`). + let (imports, invalids) = { + let file = self + .arena + .last_source_file() + .expect("parse_into stores the file it just lowered"); + debug_assert_eq!( + file.module_path.as_slice(), + module_path, + "parse_into must store the just-lowered file last" + ); + path_form_imports(&self.arena, file) + }; + + if let Some(invalid) = invalids.into_iter().next() { + self.problems.push(WalkProblem::InvalidSegment { + referenced_as: invalid.referenced_as, + segment: invalid.segment, + }); + if !self.resilient { + return true; + } + } - for segments in path_form_imports(&arena, file)? { - if visited.contains(&segments) { + // Drop imports whose `use` directive overlaps one of this file's own parse + // errors. In fail-fast mode `error_spans` is empty here (a syntax error + // returned above), so this is a no-op and the compiler is unchanged; the + // resilient walk uses it to avoid probing a syntax-mangled directive (a + // rejected glob) as a file and resurrecting a misleading missing-import. + let imports = imports + .into_iter() + .filter(|import| !location_overlaps_any(import.location, &error_spans)) + .collect(); + + self.enqueue_imports(imports, module_path) + } + + /// Enqueues the file imports of one file, recording a missing-import problem + /// for any the loader cannot find and deduplicating a self-import of the + /// entry. Returns `true` when a fail-fast walk hit a missing import. + fn enqueue_imports( + &mut self, + imports: Vec, + importing_module_path: &[String], + ) -> bool { + for import in imports { + if self.visited.contains(&import.segments) { continue; } - let dep_path = module_file_path(src_root, &segments); - if !dep_path.is_file() { - return Err(missing_import_error(&segments, &dep_path)); + let dep_path = module_file_path(self.src_root, &import.segments); + if !self.loader.exists(&dep_path) { + self.problems.push(WalkProblem::MissingImport(ImportProblem { + referenced_as: import.segments.join("::"), + suggestion: suggest_sibling(&dep_path), + expected_path: dep_path, + location: import.location, + importing_module_path: importing_module_path.to_vec(), + })); + if !self.resilient { + return true; + } + continue; } - // A `use` that names the entry file itself (e.g. `use main;` when the - // entry is `src/main.inf`) is a self-import: the entry is already in - // the closure under the empty module path, so re-discovering it here - // would lower its definitions into the arena twice and emit every - // entry function twice. Skip it, mirroring the reserved `use root;` - // handle. The reserved-handle name is the intended way to reach the - // entry; a literal self-import resolving to it is just deduplicated. - // Canonicalization failures fall through to normal handling so a real - // distinct file is never wrongly dropped. - if let (Some(entry_path), Ok(dep_canonical)) = - (entry_canonical.as_ref(), std::fs::canonicalize(&dep_path)) - && *entry_path == dep_canonical - { + // A `use` naming the entry file itself is a self-import: the entry is + // already in the closure under the empty module path, so skip it + // rather than lower its definitions twice. + if self.is_self_import(&dep_path) { continue; } - visited.insert(segments.clone()); - queue.push_back((segments, dep_path)); + self.visited.insert(import.segments.clone()); + self.queue.push_back((import.segments, dep_path)); } + false } - // Files were parsed in discovery (BFS) order; downstream phases consume - // canonical order as their single source of truth, so reorder now — before any - // `SourceFileId` is handed out. - arena.canonicalize_source_file_order(); - - // Discovery deduplicates files by module path (and self-imports of the entry), - // so each file appears exactly once. A duplicate would lower the same - // definitions twice and emit them twice in codegen; assert the invariant so a - // future discovery regression is caught here rather than in the output. - debug_assert!( - arena - .source_files() - .collect::>() - .windows(2) - .all(|w| w[0].module_path != w[1].module_path), - "discovered files must have unique module paths after deduplication" - ); + /// Whether `dep_path` names the entry file, so a `use` resolving to it is a + /// self-import to deduplicate rather than lower a second time. + /// + /// Plain path equality is the primary check: `dep_path` and the entry path are + /// both built from the same source root with identical spelling, so they match + /// exactly — and, crucially, this still holds when the entry lives only in an + /// editor overlay and so cannot be canonicalized. Canonicalization is a + /// fallback that additionally catches a self-import reaching the entry through + /// a different spelling or a symlink; it applies only when both paths exist on + /// disk, so a genuinely distinct file is never wrongly dropped. + fn is_self_import(&self, dep_path: &Path) -> bool { + if dep_path == self.entry_raw.as_path() { + return true; + } + if let (Some(entry_canonical), Ok(dep_canonical)) = ( + self.entry_canonical.as_deref(), + std::fs::canonicalize(dep_path), + ) { + return entry_canonical == dep_canonical.as_path(); + } + false + } +} - Ok(arena) +/// Translates the first problem a fail-fast walk recorded into the compiler's +/// public error, preserving the exact variants and messages `parse_project` has +/// always produced. +fn fail_fast_error(problem: WalkProblem, entry: &Path) -> anyhow::Error { + match problem { + WalkProblem::Io { path, source } => anyhow!(InferenceError::Io { path, source }), + WalkProblem::InvalidSegment { + referenced_as, + segment, + } => anyhow!(InferenceError::InvalidImportSegment { + referenced_as, + segment, + }), + WalkProblem::FileParse { + module_path, + errors, + } => parse_error(&module_path, entry, &errors), + WalkProblem::MissingImport(ImportProblem { + referenced_as, + expected_path, + suggestion, + .. + }) => anyhow!(InferenceError::ImportFileNotFound { + referenced_as, + expected_path, + suggestion, + }), + } } /// Builds a parse-failure error for `errors`. An imported (non-entry) file is @@ -230,46 +637,75 @@ fn parse_error( } } +/// A path-form `use` import naming a source file to load, with the location of +/// the `use` directive in the importing file. +struct FileImport { + segments: Vec, + location: Location, +} + +/// A `use` path segment that is not a usable file/directory name, carrying the +/// full directive path it appeared in for the diagnostic. +struct InvalidImportSegment { + referenced_as: String, + segment: String, +} + /// Extracts the path-form `use` imports of an already-parsed file as canonical -/// module-path segment lists. A braced item import (`use a::b::{x};`) maps to the -/// file `a::b` — the segments *before* the brace list. The `from`-form is skipped. +/// module-path segment lists paired with each directive's location, plus any +/// directives whose segments are not usable filesystem names. A braced item +/// import (`use a::b::{x};`) maps to the file `a::b` — the segments *before* the +/// brace list. The `from`-form and the reserved `use root;` handle are skipped. +/// +/// Invalid-segment directives are returned separately, in directive order, so a +/// fail-fast caller can report the first one exactly as the previous +/// `use_directive_segments` `?` did, while a resilient caller can skip them (an +/// invalid segment is not reachable from valid lexer output). /// /// The caller passes the just-lowered file explicitly, because the shared arena /// holds every file walked so far; `arena` is still needed to resolve the -/// directives' segment identifiers. The caller parses the file and surfaces any -/// syntax errors first, so only the directive shapes of a cleanly-parsed file -/// reach here. +/// directives' segment identifiers. fn path_form_imports( arena: &AstArena, source_file: &SourceFileData, -) -> anyhow::Result>> { +) -> (Vec, Vec) { let mut imports = Vec::new(); + let mut invalids = Vec::new(); for directive in &source_file.directives { let Directive::Use(use_dir) = directive; if use_dir.from.is_some() { continue; } - let segments = use_directive_segments(arena, use_dir)?; - // `use root;` / `use root::{x};` is the reserved handle for the program - // entry file (Inference's `@import("root")`), not a file to load: the entry - // is already in the closure. A literal `src/root.inf` is shadowed by the - // reserved name and would surface as an unreachable-file warning instead. - if is_root_handle(&segments) { - continue; - } - if !segments.is_empty() { - imports.push(segments); + match use_directive_segments(arena, use_dir) { + Ok(segments) => { + // `use root;` / `use root::{x};` is the reserved handle for the + // program entry file (Inference's `@import("root")`), not a file + // to load: the entry is already in the closure. A literal + // `src/root.inf` is shadowed by the reserved name and surfaces as + // an unreachable-file warning instead. + if is_root_handle(&segments) { + continue; + } + if !segments.is_empty() { + imports.push(FileImport { + segments, + location: use_dir.location, + }); + } + } + Err(invalid) => invalids.push(invalid), } } - Ok(imports) + (imports, invalids) } /// Resolves a path-form `use` directive's segment identifiers to validated owned -/// strings. Rejects a segment that is not a usable file/directory name. +/// strings, or reports the first segment that is not a usable file/directory +/// name. fn use_directive_segments( arena: &AstArena, use_dir: &UseDirective, -) -> anyhow::Result> { +) -> Result, InvalidImportSegment> { let mut segments = Vec::with_capacity(use_dir.segments.len()); for &ident in &use_dir.segments { let segment = arena.ident_name(ident).to_string(); @@ -280,10 +716,10 @@ fn use_directive_segments( .map(|&id| arena.ident_name(id)) .collect::>() .join("::"); - return Err(anyhow!(InferenceError::InvalidImportSegment { + return Err(InvalidImportSegment { referenced_as, segment, - })); + }); } segments.push(segment); } @@ -305,6 +741,19 @@ fn is_valid_segment(segment: &str) -> bool { && !segment.contains('\\') } +/// Whether `location`'s byte range intersects any span in `error_spans`. +/// +/// Used to recognize a `use` directive that failed to parse: a rejected glob +/// `use a::b::*;` still lowers to the segments `a::b`, and its syntax error falls +/// inside the directive's own span, so the overlap drops it from import resolution +/// before it is probed as the file `a/b.inf`. A healthy directive elsewhere in the +/// same file does not overlap the error, so it is still followed. +fn location_overlaps_any(location: Location, error_spans: &[Location]) -> bool { + error_spans.iter().any(|span| { + location.offset_start < span.offset_end && span.offset_start < location.offset_end + }) +} + /// Maps canonical module-path segments to the file they name under `src_root`: /// `["lib", "arith"]` ⇒ `/lib/arith.inf`. fn module_file_path(src_root: &Path, segments: &[String]) -> PathBuf { @@ -316,30 +765,14 @@ fn module_file_path(src_root: &Path, segments: &[String]) -> PathBuf { path } -/// Reads a source file into a string, mapping IO failures to [`InferenceError::Io`]. -fn read_source(path: &Path) -> anyhow::Result { - std::fs::read_to_string(path).map_err(|source| { - anyhow!(InferenceError::Io { - path: path.to_path_buf(), - source, - }) - }) -} - -/// Builds a missing-import error, offering the nearest sibling `.inf` stem as a -/// suggestion when one is within [`SUGGESTION_MAX_DISTANCE`] edits. The -/// suggestion is searched in the directory the missing file would have lived in. -fn missing_import_error(segments: &[String], expected_path: &Path) -> anyhow::Error { - let referenced_as = segments.join("::"); - let suggestion = expected_path +/// Offers the nearest sibling `.inf` stem as a suggestion for a missing import +/// when one is within [`SUGGESTION_MAX_DISTANCE`] edits. The suggestion is +/// searched in the directory the missing file would have lived in. +fn suggest_sibling(expected_path: &Path) -> Option { + expected_path .file_stem() .and_then(|stem| stem.to_str()) - .and_then(|target| nearest_sibling(expected_path, target)); - anyhow!(InferenceError::ImportFileNotFound { - referenced_as, - expected_path: expected_path.to_path_buf(), - suggestion, - }) + .and_then(|target| nearest_sibling(expected_path, target)) } /// Finds the closest-named sibling `.inf` file to `target` (the missing file's @@ -398,6 +831,10 @@ fn edit_distance(a: &str, b: &str) -> usize { /// Enumerates every `.inf` file under `src_root` and warns about those reached by /// no import chain (i.e. not present in the arena's canonical file set). The /// entry file is always reachable and never warned about. +/// +/// Only the fail-fast compiler front end calls this — a single build, not a +/// per-keystroke query. The resilient IDE walk skips it entirely (its warnings are +/// always empty), so the recursive directory scan never runs interactively. fn collect_unreachable_warnings( arena: &AstArena, src_root: &Path, @@ -1617,4 +2054,470 @@ mod tests { "a non-entry file named main is discovered like any other import" ); } + + // Axis: the resilient IDE variant (`load_project_resilient`) + // + // These exercise the collecting walk that ide-db drives: it shares the same + // import resolution as `parse_project` but parses every file resiliently and + // records problems instead of failing fast. + + /// The canonical module paths of a resilient parse's files, in stored order. + fn resilient_module_paths(parse: &ResilientProjectParse) -> Vec> { + parse + .arena + .source_files() + .map(|sf| sf.module_path.clone()) + .collect() + } + + #[test] + fn resilient_and_fail_fast_produce_identical_arenas_for_a_clean_project() { + // The single-source-of-truth invariant: the compiler and the IDE must + // never disagree about which files a program imports or how they are + // lowered. On a clean project, both walks discover files in the same BFS + // order and lower them identically, so the arenas are byte-identical. + let project = TempProject::new("resilient-parity"); + let entry = project.write( + "main.inf", + "use math;\nuse lib::arith;\npub fn main() -> i32 { return 0; }", + ); + project.write("math.inf", "use lib::arith;\npub fn foo() {}"); + project.write( + "lib/arith.inf", + "pub fn add(a: i32, b: i32) -> i32 { return a + b; }", + ); + + let fail_fast = parse_project(&entry).expect("clean project parses"); + let resilient = load_project_resilient(&entry, &DiskLoader); + + assert!(resilient.parse_errors.is_empty()); + assert!(resilient.import_problems.is_empty()); + assert_eq!( + fail_fast.arena, resilient.arena, + "clean-project arenas must be byte-identical across both walks" + ); + assert_eq!(fail_fast.warnings, resilient.warnings); + } + + #[test] + fn resilient_walk_at_a_filesystem_root_returns_without_scanning_the_disk() { + // Regression: an editor that opens a lone file living at a filesystem root + // makes the source root the whole volume (`/main.inf` -> src_root `/`). The + // resilient walk must not scan the source tree for unreachable files — + // otherwise it walks every directory on disk, on every keystroke, and never + // returns. The resilient walk skips that scan unconditionally, so a root + // source tree returns at once. An in-memory loader supplies the entry so + // the test never depends on a real file at the root; a worker thread with a + // timeout turns a regressed hang into a failed assertion rather than a stuck + // test run. + struct RootEntryLoader { + entry: PathBuf, + source: String, + } + + impl FileLoader for RootEntryLoader { + fn exists(&self, path: &Path) -> bool { + path == self.entry + } + + fn read(&self, path: &Path) -> std::io::Result { + if path == self.entry { + Ok(self.source.clone()) + } else { + Err(std::io::Error::from(std::io::ErrorKind::NotFound)) + } + } + } + + // A path directly under the filesystem root, so its parent — the source + // root the walk derives — is the root itself, with no parent of its own. + let fs_root = std::env::temp_dir() + .ancestors() + .last() + .expect("the temp dir has a root ancestor") + .to_path_buf(); + assert!( + fs_root.parent().is_none(), + "the derived filesystem root must have no parent" + ); + let entry = fs_root.join("inference-lsp-root-regression.inf"); + let loader = RootEntryLoader { + entry: entry.clone(), + source: "pub fn main() {}".to_string(), + }; + + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let parse = load_project_resilient(&entry, &loader); + let _ = tx.send(parse.warnings.len()); + }); + + let warning_count = rx + .recv_timeout(std::time::Duration::from_secs(20)) + .expect( + "the resilient walk at a filesystem root did not return: \ + the whole-disk unreachable scan was not skipped", + ); + assert_eq!( + warning_count, 0, + "a lone file at a filesystem root has no unreachable-file warnings" + ); + } + + #[test] + fn resilient_walk_collects_a_broken_imported_files_parse_errors_and_keeps_the_rest() { + // A syntax error in one imported file must not abort the walk: the entry + // and the other imports are still lowered, and the broken file's errors + // are collected, labeled with its module path. + let project = TempProject::new("resilient-broken"); + let entry = project.write( + "main.inf", + "use broken;\nuse good;\npub fn main() -> i32 { return 0; }", + ); + project.write("broken.inf", "pub fn oops( { return 1; }"); + project.write("good.inf", "pub fn good() -> i32 { return 7; }"); + + let parse = load_project_resilient(&entry, &DiskLoader); + + // Every file was still discovered and lowered. + assert_eq!( + resilient_module_paths(&parse), + vec![ + Vec::::new(), + mp(&["broken"]), + mp(&["good"]), + ], + ); + // The broken file's syntax errors are collected and labeled. + assert_eq!(parse.parse_errors.len(), 1, "only the broken file errors"); + assert_eq!(parse.parse_errors[0].module_path, mp(&["broken"])); + assert!(!parse.parse_errors[0].errors.is_empty()); + assert!(parse.import_problems.is_empty()); + // The good file's definition survives in the arena. + let good_defs: Vec<&str> = parse + .arena + .source_files() + .find(|sf| sf.module_path == mp(&["good"])) + .expect("good file present") + .defs + .iter() + .map(|&d| parse.arena.def_name(d)) + .collect(); + assert_eq!(good_defs, vec!["good"]); + } + + #[test] + fn resilient_walk_records_a_missing_import_with_location_and_suggestion() { + // A missing import becomes structured data anchored at the `use` + // directive, not a hard error. The importing file is still analyzable. + let project = TempProject::new("resilient-missing"); + let entry = project.write( + "main.inf", + "use arith;\npub fn main() -> i32 { return 0; }", + ); + // A near-miss sibling one edit away drives the suggestion. + project.write("arithh.inf", "pub fn add() {}"); + + let parse = load_project_resilient(&entry, &DiskLoader); + + assert_eq!(parse.import_problems.len(), 1); + let problem = &parse.import_problems[0]; + assert_eq!(problem.referenced_as, "arith"); + assert!(problem.expected_path.ends_with("arith.inf")); + assert_eq!(problem.suggestion.as_deref(), Some("arithh")); + // The problem is anchored in the entry file at the `use` directive, which + // begins at the first byte of the source. + assert!(problem.importing_module_path.is_empty()); + assert_eq!(problem.location.offset_start, 0); + assert!(parse.parse_errors.is_empty()); + // The entry itself is still lowered. + assert_eq!(resilient_module_paths(&parse), vec![Vec::::new()]); + } + + #[test] + fn resilient_walk_honors_the_reserved_use_root_handle() { + // `use root;` is the reserved entry handle, not a file to load, so it does + // not produce a missing-import problem even though no `root.inf` exists. + let project = TempProject::new("resilient-root"); + let entry = project.write( + "main.inf", + "use root;\npub fn main() -> i32 { return 0; }", + ); + + let parse = load_project_resilient(&entry, &DiskLoader); + + assert!(parse.import_problems.is_empty(), "`use root;` names no file"); + assert!(parse.parse_errors.is_empty()); + assert_eq!(resilient_module_paths(&parse), vec![Vec::::new()]); + } + + #[test] + fn resilient_walk_deduplicates_a_self_import_of_the_entry() { + // A `use main;` from a sub-file resolves back to the entry, already in the + // closure under the empty module path; the resilient walk deduplicates it + // exactly as the compiler does, so the entry is lowered once. + let project = TempProject::new("resilient-self-import"); + let entry = project.write( + "main.inf", + "use lib::helper;\npub fn main() -> i32 { return 0; }", + ); + project.write( + "lib/helper.inf", + "use main;\npub fn doubled() -> i32 { return 14; }", + ); + + let parse = load_project_resilient(&entry, &DiskLoader); + + let entry_count = parse + .arena + .source_files() + .filter(|sf| sf.module_path.is_empty()) + .count(); + assert_eq!(entry_count, 1, "the entry is lowered exactly once"); + assert_eq!( + resilient_module_paths(&parse), + vec![Vec::::new(), mp(&["lib", "helper"])], + ); + assert!(parse.import_problems.is_empty()); + } + + #[test] + fn resilient_walk_terminates_on_a_two_file_import_cycle() { + // Two files importing each other must terminate via the visited set, just + // like the fail-fast walk, and both appear once. + let project = TempProject::new("resilient-cycle"); + let entry = project.write("main.inf", "use a;\npub fn main() {}"); + project.write("a.inf", "use b;\npub fn fa() {}"); + project.write("b.inf", "use a;\npub fn fb() {}"); + + let parse = load_project_resilient(&entry, &DiskLoader); + + assert_eq!( + resilient_module_paths(&parse), + vec![Vec::::new(), mp(&["a"]), mp(&["b"])], + ); + assert!(parse.import_problems.is_empty()); + assert!(parse.parse_errors.is_empty()); + } + + #[test] + fn resilient_walk_reports_every_read_file_with_its_module_path() { + // The `files` list is the closure file set plus the module-path → path + // mapping ide-db consumes: every reachable file that was read, once. + let project = TempProject::new("resilient-files"); + let entry = project.write("main.inf", "use lib::a;\npub fn main() {}"); + let a = project.write("lib/a.inf", "pub fn fa() {}"); + + let parse = load_project_resilient(&entry, &DiskLoader); + + let mut by_module: Vec<(Vec, PathBuf)> = parse + .files + .iter() + .map(|f| (f.module_path.clone(), f.path.clone())) + .collect(); + by_module.sort(); + assert_eq!(by_module.len(), 2); + assert_eq!(by_module[0].0, Vec::::new()); + assert_eq!(by_module[0].1, entry); + assert_eq!(by_module[1].0, mp(&["lib", "a"])); + assert_eq!(by_module[1].1, a); + } + + #[test] + fn resilient_walk_uses_the_loader_overlay_over_disk() { + // A custom loader can shadow on-disk contents (the overlay-then-disk model + // ide-db uses). Here the loader serves a different entry body than the one + // on disk, and reports which paths it was asked to read. + use std::cell::RefCell; + use std::collections::HashMap; + + struct MapLoader { + files: HashMap, + reads: RefCell>, + } + impl FileLoader for MapLoader { + fn exists(&self, path: &Path) -> bool { + self.files.contains_key(path) + } + fn read(&self, path: &Path) -> std::io::Result { + self.reads.borrow_mut().push(path.to_path_buf()); + self.files + .get(path) + .cloned() + .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound)) + } + } + + let entry = PathBuf::from("/proj/main.inf"); + let dep = PathBuf::from("/proj/lib/dep.inf"); + let mut files = HashMap::new(); + files.insert(entry.clone(), "use lib::dep;\npub fn main() {}".to_string()); + files.insert(dep.clone(), "pub fn helper() {}".to_string()); + let loader = MapLoader { + files, + reads: RefCell::new(Vec::new()), + }; + + let parse = load_project_resilient(&entry, &loader); + + assert!(parse.import_problems.is_empty()); + assert!(parse.parse_errors.is_empty()); + assert_eq!( + resilient_module_paths(&parse), + vec![Vec::::new(), mp(&["lib", "dep"])], + ); + // Both files were read through the loader, never `std::fs`. + let reads = loader.reads.borrow(); + assert!(reads.contains(&entry)); + assert!(reads.contains(&dep)); + } + + #[test] + fn resilient_walk_deduplicates_a_self_import_of_an_overlay_only_entry() { + // Regression: an entry that lives only in an editor overlay (never written + // to disk) cannot be canonicalized, so the self-import dedup must fall back + // to plain path equality. A `use main;` in a reachable file resolves back + // to the overlay entry; without the fallback the entry is lowered twice — + // once under the empty module path and once under a phantom `["main"]` + // module mapped to the same file — duplicating every entry symbol for the + // type checker, the analysis rules, and cross-file IDE features. + use std::collections::HashMap; + + struct OverlayLoader { + files: HashMap, + } + impl FileLoader for OverlayLoader { + fn exists(&self, path: &Path) -> bool { + self.files.contains_key(path) + } + fn read(&self, path: &Path) -> std::io::Result { + self.files + .get(path) + .cloned() + .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound)) + } + } + + // Paths under a directory that does not exist on disk, so the entry cannot + // be canonicalized — the overlay-only condition. The loader serves both. + let entry = PathBuf::from("/inference-overlay-only/main.inf"); + let lib = PathBuf::from("/inference-overlay-only/lib.inf"); + let mut files = HashMap::new(); + files.insert( + entry.clone(), + "use lib;\npub fn main() -> i32 { return 0; }".to_string(), + ); + files.insert( + lib.clone(), + "use main;\npub fn helper() -> i32 { return 7; }".to_string(), + ); + let loader = OverlayLoader { files }; + + let parse = load_project_resilient(&entry, &loader); + + // The entry is lowered exactly once (empty path); no phantom `["main"]`. + assert_eq!( + resilient_module_paths(&parse), + vec![Vec::::new(), mp(&["lib"])], + "the overlay-only entry must not be re-lowered as a `[\"main\"]` module", + ); + let entry_count = parse + .arena + .source_files() + .filter(|sf| sf.module_path.is_empty()) + .count(); + assert_eq!( + entry_count, 1, + "the overlay-only entry is lowered exactly once" + ); + } + + #[test] + fn resilient_walk_never_reports_unreachable_warnings() { + // Regression: the resilient/IDE walk must not scan the source tree for + // unreachable files. That scan enumerates and canonicalizes every `.inf` + // under the source root — work an editor repeats on every keystroke — yet + // no IDE consumer reads the warnings. An orphan the fail-fast walk warns + // about must yield no resilient warning at all. + let project = TempProject::new("resilient-no-warn"); + let entry = project.write("main.inf", "pub fn main() -> i32 { return 0; }"); + project.write("orphan.inf", "pub fn orphan() {}"); + + // The fail-fast compiler still warns about the orphan... + let fail_fast = parse_project(&entry).expect("project parses"); + assert_eq!( + fail_fast.warnings.len(), + 1, + "the compiler still scans for and warns about orphans" + ); + + // ...but the resilient walk skips the scan entirely. + let resilient = load_project_resilient(&entry, &DiskLoader); + assert!( + resilient.warnings.is_empty(), + "the resilient walk must not compute unreachable-file warnings, got {:?}", + resilient.warnings, + ); + } + + #[test] + fn resilient_walk_ignores_imports_of_a_parse_rejected_glob_when_target_absent() { + // Regression: a rejected glob `use a::b::*;` still lowers to the segments + // `a::b`, so without care the resilient walk probes it as the file + // `a/b.inf` and manufactures a misleading missing-import problem that + // accompanies the directive's own educational glob diagnostic. The + // fail-fast walk never does this (it stops at the syntax error); the + // resilient walk must mirror that intent by not resolving imports out of a + // directive that failed to parse. Here `a/b.inf` does not exist. + let project = TempProject::new("resilient-glob-absent"); + let entry = project.write( + "main.inf", + "use a::b::*;\npub fn main() -> i32 { return 0; }", + ); + + let parse = load_project_resilient(&entry, &DiskLoader); + + // The glob's own syntax error is still collected on the entry file. + assert_eq!( + parse.parse_errors.len(), + 1, + "the glob syntax error is still reported" + ); + assert_eq!(parse.parse_errors[0].module_path, Vec::::new()); + // ...but no missing-import problem is manufactured from the rejected glob. + assert!( + parse.import_problems.is_empty(), + "a parse-rejected glob directive must not drive import resolution, got {:?}", + parse.import_problems, + ); + // Only the entry is in the closure; `a/b.inf` was never probed. + assert_eq!(resilient_module_paths(&parse), vec![Vec::::new()]); + } + + #[test] + fn resilient_walk_does_not_pull_in_the_file_named_by_a_parse_rejected_glob() { + // Companion to the absent-target case: even when `a/b.inf` exists on disk, + // a rejected glob `use a::b::*;` must not silently pull it into the + // closure. The fail-fast compiler refuses at the glob without touching + // `b.inf`, and the resilient walk must not diverge by analyzing it. + let project = TempProject::new("resilient-glob-present"); + let entry = project.write( + "main.inf", + "use a::b::*;\npub fn main() -> i32 { return 0; }", + ); + project.write("a/b.inf", "pub fn helper() -> i32 { return 1; }"); + + let parse = load_project_resilient(&entry, &DiskLoader); + + // `a/b.inf` was not pulled into the closure by the rejected directive. + assert_eq!( + resilient_module_paths(&parse), + vec![Vec::::new()], + "a file named by a parse-rejected glob must not enter the closure", + ); + assert!(parse.import_problems.is_empty()); + // The glob syntax error is still surfaced on the entry. + assert_eq!(parse.parse_errors.len(), 1); + assert_eq!(parse.parse_errors[0].module_path, Vec::::new()); + } } diff --git a/core/inference/tests/type_check_diagnostics.rs b/core/inference/tests/type_check_diagnostics.rs new file mode 100644 index 00000000..80908448 --- /dev/null +++ b/core/inference/tests/type_check_diagnostics.rs @@ -0,0 +1,533 @@ +//! Integration tests for the lossless structured type-check entry point +//! (`inference::type_check_with_diagnostics` / `inference_type_checker::check_with_diagnostics`, +//! issue #33). +//! +//! The suite pins three properties the LSP layer depends on: +//! +//! 1. **Structured, parse-free diagnostics** — each error keeps its +//! [`TypeCheckError`] variant, its per-file-local source location, and its +//! optional module-path file label, so no string parsing is needed. +//! 2. **Legacy parity** — the existing string-joining path +//! ([`inference::type_check`]) renders byte-identically to rendering the +//! structured errors the same way, guarding against drift between the two. +//! 3. **Partial-context usefulness** — when some definitions fail to check, the +//! returned context still answers whole-program queries (`lookup_struct`, +//! `lookup_enum`, `lookup_method`) and per-node queries +//! (`get_node_typeinfo`, `call_target`) for the definitions that did check. +//! +//! Sources are compact inline `.inf` per the contributing guide; multi-file +//! programs are folded with `inference_parser::parse_into` (no filesystem). + +use inference::{ + TypeCheckDiagnostic, TypeCheckError, TypedContext, type_check, type_check_with_diagnostics, +}; +use inference_ast::arena::AstArena; +use inference_ast::ids::{DefId, ExprId, NodeId}; +use inference_ast::nodes::{Def, Expr, Stmt}; + +/// Parses a single-file source into an arena, asserting it is syntactically +/// valid (these tests exercise type checking, not parsing). +fn parse_arena(source: &str) -> AstArena { + let parsed = inference_parser::parse(source); + assert!( + parsed.errors.is_empty(), + "test source has syntax errors: {:?}", + parsed.errors + ); + parsed.arena +} + +/// Folds `(module_path, source)` pairs into one multi-file arena, entry file +/// (empty module path) first. Mirrors what the project front end builds at +/// runtime, without touching the filesystem. +fn parse_multi_file(files: &[(&[&str], &str)]) -> AstArena { + let mut arena = AstArena::default(); + for (module_path, source) in files { + let segments: Vec = module_path.iter().map(|s| (*s).to_string()).collect(); + let parsed = inference_parser::parse_into(arena, source, segments); + assert!( + parsed.errors.is_empty(), + "multi-file test source {module_path:?} has syntax errors: {:?}", + parsed.errors + ); + arena = parsed.arena; + } + arena +} + +/// Renders structured diagnostics exactly as the legacy aggregated +/// [`inference::type_check`] message does: `label:line:col: message` per error +/// (bare `line:col: message` for the entry file), joined by `"; "`. Kept in +/// lockstep with the render in `TypeCheckerBuilder::build_typed_context`; the +/// parity tests fail if they ever diverge. +fn render_like_legacy(errors: &[TypeCheckDiagnostic]) -> String { + errors + .iter() + .map(|diagnostic| match &diagnostic.file_label { + Some(label) => format!("{label}:{}", diagnostic.error), + None => diagnostic.error.to_string(), + }) + .collect::>() + .join("; ") +} + +/// Finds the top-level function named `name`, panicking if it is absent. +fn function_def_id_by_name(ctx: &TypedContext, name: &str) -> DefId { + for def_id in ctx.function_def_ids() { + if let Def::Function { name: name_id, .. } = &ctx.arena()[def_id].kind + && ctx.arena()[*name_id].name == name + { + return def_id; + } + } + panic!("function `{name}` not found in typed context"); +} + +/// Returns the id of the first `FunctionCall` expression in the body of the +/// given function, panicking if there is none. Used to probe `get_node_typeinfo` +/// (on the call expression, which carries the callee's return type) and +/// `call_target` (on the call's function sub-expression). +fn first_call_expr_in_body(ctx: &TypedContext, func: DefId) -> ExprId { + let Def::Function { body, .. } = &ctx.arena()[func].kind else { + panic!("`{func:?}` is not a function"); + }; + for &stmt_id in &ctx.arena()[*body].stmts { + let candidate = match &ctx.arena()[stmt_id].kind { + Stmt::VarDef { + value: Some(expr), .. + } => Some(*expr), + Stmt::Return { expr } => Some(*expr), + Stmt::Expr(expr) => Some(*expr), + _ => None, + }; + if let Some(expr) = candidate + && matches!(ctx.arena()[expr].kind, Expr::FunctionCall { .. }) + { + return expr; + } + } + panic!("no function call in body of `{func:?}`"); +} + +// --- Single-error structured shape ------------------------------------------ + +#[test] +fn single_type_mismatch_has_structured_variant_and_location() { + let source = r#"fn main() -> i32 { return true; }"#; + let outcome = type_check_with_diagnostics(parse_arena(source)); + + assert_eq!( + outcome.errors.len(), + 1, + "expected exactly one error, got {:?}", + outcome.errors + ); + let diagnostic = &outcome.errors[0]; + assert_eq!( + diagnostic.file_label, None, + "an entry-file error carries no file label" + ); + let TypeCheckError::TypeMismatch { location, .. } = &diagnostic.error else { + panic!("expected TypeMismatch, got {:?}", diagnostic.error); + }; + // The return-type mismatch anchors at the returning statement; assert the + // location is on line 1, in bounds, non-empty, and covers the `true` value. + assert_eq!(location.start_line, 1, "single-line source"); + assert!( + location.offset_end > location.offset_start, + "location spans a non-empty range" + ); + assert!( + (location.offset_end as usize) <= source.len(), + "location stays within the source" + ); + let slice = &source[location.offset_start as usize..location.offset_end as usize]; + assert!( + slice.contains("true"), + "the location `{slice}` should cover the offending `true`" + ); + assert_eq!( + location.start_column, + location.offset_start + 1, + "1-based byte column on a single line equals offset + 1" + ); +} + +#[test] +fn undefined_function_error_carries_name_and_location() { + let source = r#"fn main() -> i32 { return missing(); }"#; + let outcome = type_check_with_diagnostics(parse_arena(source)); + + let undefined = outcome + .errors + .iter() + .find_map(|d| match &d.error { + TypeCheckError::UndefinedFunction { name, location } => Some((name, location)), + _ => None, + }) + .expect("expected an UndefinedFunction error"); + assert_eq!(undefined.0, "missing"); + assert_eq!(undefined.1.start_line, 1); + assert!( + undefined.1.offset_end > undefined.1.offset_start, + "location spans a non-empty range" + ); + assert!( + (undefined.1.offset_end as usize) <= source.len(), + "location stays within the source" + ); +} + +#[test] +fn unknown_type_error_variant_is_preserved() { + let source = r#"fn main(x: Nope) -> i32 { return 0; }"#; + let outcome = type_check_with_diagnostics(parse_arena(source)); + + let has_unknown_type = outcome.errors.iter().any(|d| { + matches!( + &d.error, + TypeCheckError::UnknownType { name, .. } if name == "Nope" + ) + }); + assert!( + has_unknown_type, + "expected UnknownType for `Nope`, got {:?}", + outcome.errors + ); +} + +// --- Multiple errors: order and dedup --------------------------------------- + +#[test] +fn multiple_errors_preserve_order_and_render_like_legacy() { + let source = r#"fn a() -> i32 { return true; } fn b() -> i32 { return missing(); }"#; + let legacy = type_check(parse_arena(source)) + .err() + .expect("program has type errors") + .to_string(); + let outcome = type_check_with_diagnostics(parse_arena(source)); + + assert!( + outcome.errors.len() >= 2, + "expected at least two errors, got {:?}", + outcome.errors + ); + assert_eq!( + render_like_legacy(&outcome.errors), + legacy, + "structured render must reproduce the legacy aggregated string byte-for-byte" + ); +} + +#[test] +fn dedup_behavior_matches_legacy() { + // The same undefined type referenced twice can be emitted by more than one + // pass; the structured path must dedup identically to the legacy path, which + // the render-equality below enforces. + let source = r#"fn f(a: Nope, b: Nope) -> i32 { return 0; }"#; + let legacy = type_check(parse_arena(source)) + .err() + .expect("program has type errors") + .to_string(); + let outcome = type_check_with_diagnostics(parse_arena(source)); + + assert_eq!(render_like_legacy(&outcome.errors), legacy); + assert_eq!( + legacy.matches("; ").count() + 1, + outcome.errors.len(), + "structured error count matches the number of `; `-joined legacy segments" + ); +} + +// --- Multi-file file labels ------------------------------------------------- + +#[test] +fn error_in_imported_module_is_labeled_with_module_path() { + let arena = parse_multi_file(&[ + ( + &[], + "use lib::math; pub fn main() -> i32 { return lib::math::add(1, 2); }", + ), + ( + &["lib", "math"], + "pub fn add(a: i32, b: i32) -> i32 { return wrong; }", + ), + ]); + let outcome = type_check_with_diagnostics(arena); + + let labeled = outcome + .errors + .iter() + .find(|d| matches!(&d.error, TypeCheckError::UnknownIdentifier { name, .. } if name == "wrong")) + .expect("expected the undeclared-variable error from the imported file"); + assert_eq!( + labeled.file_label.as_deref(), + Some("lib::math"), + "an imported-file error names its module path" + ); +} + +#[test] +fn multi_file_render_matches_legacy_with_labels() { + let files: &[(&[&str], &str)] = &[ + ( + &[], + "use lib::math; pub fn main() -> i32 { return lib::math::add(1); }", + ), + ( + &["lib", "math"], + "pub fn add(a: i32, b: i32) -> i32 { return wrong; }", + ), + ]; + let legacy = type_check(parse_multi_file(files)) + .err() + .expect("program has type errors") + .to_string(); + let outcome = type_check_with_diagnostics(parse_multi_file(files)); + + assert!( + !outcome.errors.is_empty(), + "expected cross-file errors, got none" + ); + assert_eq!( + render_like_legacy(&outcome.errors), + legacy, + "labels and ordering must match the legacy aggregated string" + ); + assert!( + legacy.contains("lib::math:"), + "the legacy string labels the imported file, sanity-checking the fixture" + ); +} + +// --- Clean program ---------------------------------------------------------- + +#[test] +fn clean_program_has_no_errors_and_fully_usable_context() { + let source = r#"struct Point { x: i32; y: i32; } fn area(p: Point) -> i32 { return p.x + p.y; } pub fn main() -> i32 { let p: Point = Point { x: 3, y: 4 }; return area(p); }"#; + let outcome = type_check_with_diagnostics(parse_arena(source)); + + assert!( + outcome.errors.is_empty(), + "expected a clean program, got {:?}", + outcome.errors + ); + let ctx = &outcome.typed_context; + assert!( + ctx.lookup_struct("Point").is_some(), + "the struct index is populated for a clean program" + ); + let main = function_def_id_by_name(ctx, "main"); + let call = first_call_expr_in_body(ctx, main); + assert!( + ctx.get_node_typeinfo(NodeId::Expr(call)).is_some(), + "the call expression is typed" + ); + let Expr::FunctionCall { function, .. } = &ctx.arena()[call].kind else { + unreachable!("first_call_expr_in_body returns a FunctionCall"); + }; + assert!( + ctx.call_target(*function).is_some(), + "the resolved call target is recorded" + ); +} + +#[test] +fn clean_program_agrees_with_legacy_type_check() { + let source = r#"struct Point { x: i32; y: i32; } pub fn main() -> i32 { let p: Point = Point { x: 1, y: 2 }; return p.x; }"#; + let legacy = type_check(parse_arena(source)).expect("clean program type-checks"); + let outcome = type_check_with_diagnostics(parse_arena(source)); + + assert!(outcome.errors.is_empty()); + assert_eq!( + legacy.lookup_struct("Point").is_some(), + outcome.typed_context.lookup_struct("Point").is_some(), + "both entry points build the same struct index on success" + ); +} + +// --- Partial context after an error ----------------------------------------- + +#[test] +fn partial_context_serves_checked_parts_after_error_in_sibling() { + // `broken` fails to type-check; every other definition is well-formed. The + // returned context must still answer whole-program and per-node queries for + // the well-formed parts. + let source = r#"struct Point { x: i32; y: i32; fn sum(self) -> i32 { return self.x + self.y; } } enum Color { Red, Green, Blue } fn helper(n: i32) -> i32 { return n; } pub fn good() -> i32 { let s: i32 = helper(1); return s; } fn broken() -> i32 { return true; }"#; + let outcome = type_check_with_diagnostics(parse_arena(source)); + + assert!( + !outcome.errors.is_empty(), + "the broken sibling must produce an error" + ); + let ctx = &outcome.typed_context; + + // Whole-program tables survive the error in `broken`. + assert!( + ctx.lookup_struct("Point").is_some(), + "struct index survives a sibling error" + ); + assert!( + ctx.lookup_enum("Color").is_some(), + "enum index survives a sibling error" + ); + assert!( + ctx.lookup_method("Point", "sum").is_some(), + "method lookup survives a sibling error" + ); + + // Per-node results answer for the well-formed sibling `good`. + let good = function_def_id_by_name(ctx, "good"); + let call = first_call_expr_in_body(ctx, good); + assert!( + ctx.get_node_typeinfo(NodeId::Expr(call)).is_some(), + "a node in a checked sibling is typed despite an error elsewhere" + ); + let Expr::FunctionCall { function, .. } = &ctx.arena()[call].kind else { + unreachable!("first_call_expr_in_body returns a FunctionCall"); + }; + assert!( + ctx.call_target(*function).is_some(), + "a resolved call in a checked sibling has a recorded target" + ); + + // The arena is always fully present, regardless of errors. + assert!( + ctx.arena().source_files().len() >= 1, + "the parsed arena is preserved" + ); +} + +#[test] +fn partial_context_struct_used_correctly_alongside_error() { + // A struct is defined and used correctly in one function while another + // function has an unrelated error; the struct stays resolvable. + let source = r#"struct Vec2 { x: i32; y: i32; } fn ok(v: Vec2) -> i32 { return v.x; } fn bad() -> i32 { return undefined_name; }"#; + let outcome = type_check_with_diagnostics(parse_arena(source)); + + assert!(!outcome.errors.is_empty(), "the `bad` function must error"); + assert!( + outcome.typed_context.lookup_struct("Vec2").is_some(), + "a correctly-used struct is resolvable despite an unrelated error" + ); + let ok = function_def_id_by_name(&outcome.typed_context, "ok"); + if let Def::Function { args, .. } = &outcome.typed_context.arena()[ok].kind { + assert_eq!( + args.len(), + 1, + "the well-formed function is intact in the arena" + ); + } else { + panic!("`ok` is not a function"); + } +} + +// --- Extern-import diagnostics from an imported file ------------------------ + +#[test] +fn dangling_extern_import_in_imported_file_is_labeled_with_module_path() { + // Extern-binding collection scans the `use { .. } from ;` directives + // of every file in the closure while the cursor sits at the root (no open + // file). A dangling extern import that lives in an imported file must still + // name that file: its source location is per-file-local, so a `None` label + // makes the LSP render it against the entry document at out-of-bounds, + // entry-file-local offsets. + let arena = parse_multi_file(&[ + (&[], "use lib; fn main() -> i32 { return 0; }"), + ( + &["lib"], + "use { foo_undeclared } from env; pub fn helper() -> i32 { return 1; }", + ), + ]); + let outcome = type_check_with_diagnostics(arena); + + let dangling = outcome + .errors + .iter() + .find(|d| { + matches!(&d.error, TypeCheckError::ExternImportNotDeclared { name, .. } if name == "foo_undeclared") + }) + .expect("expected the dangling extern-import error from the imported file"); + assert_eq!( + dangling.file_label.as_deref(), + Some("lib"), + "an extern-import error names the file that owns the `use ... from` directive" + ); +} + +#[test] +fn ambiguous_extern_import_in_imported_file_is_labeled_with_module_path() { + // The ambiguous-module push shares the same root-cursor scan as the dangling + // one, so it must anchor to the file holding the first conflicting directive. + let arena = parse_multi_file(&[ + (&[], "use lib; fn main() -> i32 { return 0; }"), + ( + &["lib"], + "use { blend } from collections; use { blend } from algorithms; external fn blend(a: i32) -> i32; pub fn helper() -> i32 { return 1; }", + ), + ]); + let outcome = type_check_with_diagnostics(arena); + + let ambiguous = outcome + .errors + .iter() + .find(|d| { + matches!(&d.error, TypeCheckError::AmbiguousExternModule { name, .. } if name == "blend") + }) + .expect("expected the ambiguous extern-import error from the imported file"); + assert_eq!( + ambiguous.file_label.as_deref(), + Some("lib"), + "an ambiguous extern-import error names the file that owns the first `use ... from`" + ); +} + +// --- Annotated-let number-literal mismatch: source-level double emission ----- + +#[test] +fn annotated_let_number_literal_mismatch_double_emits_and_renders_in_legacy_twice() { + // A `let p: Point = 3;` reports the same variable-definition mismatch twice: + // once from the number-literal-vs-non-numeric-target check and once from the + // general initializer comparison it falls through to. This is deliberately + // left as-is at the type-checker source, because the legacy aggregated string + // renders the duplicate too (they share one error list), so deduping at the + // source would silently change pinned compiler-output. The user-visible + // squiggle duplication is instead collapsed downstream in the IDE/LSP + // diagnostics layer. This test pins the current source-level contract so any + // future change to emission is a conscious, coordinated one. + let source = r#"struct Point { x: i32; } fn main() -> i32 { let p: Point = 3; return 0; }"#; + let outcome = type_check_with_diagnostics(parse_arena(source)); + + let mismatches: Vec<_> = outcome + .errors + .iter() + .filter(|d| { + matches!(&d.error, TypeCheckError::TypeMismatch { .. }) + && d.error.to_string().contains("in variable definition") + }) + .collect(); + assert_eq!( + mismatches.len(), + 2, + "the number-literal path emits the variable-definition mismatch twice, got {:?}", + outcome.errors + ); + assert_eq!( + mismatches[0].error.location(), + mismatches[1].error.location(), + "both mismatches anchor at the same location" + ); + + let legacy = type_check(parse_arena(source)) + .err() + .expect("program has a type error") + .to_string(); + assert_eq!( + legacy + .matches("type mismatch in variable definition") + .count(), + 2, + "the legacy aggregated string renders the duplicate too, so source-level \ + emission must not be deduped without coordinating the pinned output: {legacy}" + ); +} diff --git a/core/type-checker/src/lib.rs b/core/type-checker/src/lib.rs index 870a911e..c6e85ea6 100644 --- a/core/type-checker/src/lib.rs +++ b/core/type-checker/src/lib.rs @@ -98,9 +98,10 @@ use std::marker::PhantomData; +use anyhow::bail; use inference_ast::arena::AstArena; -use crate::{type_checker::TypeChecker, typed_context::TypedContext}; +use crate::{errors::TypeCheckError, type_checker::TypeChecker, typed_context::TypedContext}; mod definition_graph; pub mod errors; @@ -158,20 +159,26 @@ impl TypeCheckerBuilder { pub fn build_typed_context( arena: AstArena, ) -> anyhow::Result> { - let mut ctx = TypedContext::new(arena); - let mut type_checker = TypeChecker::default(); - match type_checker.infer_types(&mut ctx) { - Ok(symbol_table) => { - ctx.symbol_table = symbol_table; - ctx.build_type_indexes(); - } - Err(e) => { - return Err(e); - } + let TypeCheckOutcome { + typed_context, + errors, + } = check_with_diagnostics(arena); + if !errors.is_empty() { + // Prefix each error with the `::`-joined module path of the file it + // was produced in; the entry file stays a bare `line:col` (its label + // is `None`), so single-file programs read exactly as before. + let error_messages: Vec = errors + .into_iter() + .map(|d| match d.file_label { + Some(label) => format!("{label}:{}", d.error), + None => d.error.to_string(), + }) + .collect(); + bail!(error_messages.join("; ")); } Ok(TypeCheckerBuilder { - typed_context: ctx, + typed_context, _state: PhantomData, }) } @@ -184,3 +191,103 @@ impl TypeCheckerBuilder { self.typed_context } } + +/// A single structured type-check diagnostic: a [`TypeCheckError`] paired with +/// the module-path file label of the file it was produced in. +/// +/// The label is required because source locations in a multi-file program are +/// per-file-local in the merged arena, so a bare `line:col` from an imported +/// file would otherwise be misattributed to the entry file. It matches +/// [`inference_ast::nodes::file_label`]: `None` for the entry file, the +/// `::`-joined module path (e.g. `lib::geom`) otherwise. The per-error source +/// location is available without string parsing via +/// [`TypeCheckError::location`](crate::errors::TypeCheckError::location). +#[derive(Debug, Clone)] +pub struct TypeCheckDiagnostic { + /// The `::`-joined module path of the file this error belongs to, or `None` + /// for the entry file. + pub file_label: Option, + /// The structured error, carrying its own per-file-local source location. + pub error: TypeCheckError, +} + +/// The lossless outcome of a type-check run: the typed context together with +/// every structured diagnostic collected. Produced by [`check_with_diagnostics`]. +/// +/// # Partial context guarantees +/// +/// The [`typed_context`](Self::typed_context) is returned whether or not type +/// checking found errors, because the checker recovers from errors and runs +/// every phase to completion rather than aborting on the first one. As a result +/// the *whole-program* tables are always fully built, up to what was resolvable: +/// +/// - [`TypedContext::arena`] — the parsed arena, always complete (type checking +/// never mutates it). +/// - [`TypedContext::lookup_struct`] / [`TypedContext::lookup_enum`] and the +/// underlying symbol table (methods, functions, imports) — populated for every +/// definition the checker could register, independent of body errors, because +/// the symbol table is assigned into the context and its canonical-key indexes +/// are built even on the error path. +/// +/// Only *per-node* results are affected by errors, and only for the nodes that +/// failed: +/// +/// - [`TypedContext::get_node_typeinfo`] answers for every node that was +/// successfully typed. A node inside a definition whose body failed to +/// type-check may be absent, but each definition is inferred independently, so +/// a node in a *sibling* definition that did check is unaffected. +/// - [`TypedContext::call_target`] answers for every call that resolved to a +/// known function; an unresolved (erroring) call is absent. +/// +/// When [`errors`](Self::errors) is empty the context is exactly the one +/// [`TypeCheckerBuilder::build_typed_context`] yields on success. +/// +/// [`TypedContext::arena`]: crate::typed_context::TypedContext::arena +/// [`TypedContext::lookup_struct`]: crate::typed_context::TypedContext::lookup_struct +/// [`TypedContext::lookup_enum`]: crate::typed_context::TypedContext::lookup_enum +/// [`TypedContext::get_node_typeinfo`]: crate::typed_context::TypedContext::get_node_typeinfo +/// [`TypedContext::call_target`]: crate::typed_context::TypedContext::call_target +pub struct TypeCheckOutcome { + /// The typed context, populated as far as error recovery allowed (see the + /// type-level docs for the exact partial guarantees). + pub typed_context: TypedContext, + /// Every structured diagnostic collected, in the same order the aggregated + /// [`TypeCheckerBuilder::build_typed_context`] message renders them. Empty + /// when the program type-checks cleanly. + pub errors: Vec, +} + +/// Type-checks `arena` losslessly: runs the same pipeline as +/// [`TypeCheckerBuilder::build_typed_context`] but returns the (possibly +/// partially populated) [`TypedContext`] together with the structured errors, +/// instead of discarding the context and joining the errors into one string. +/// +/// This is the structured entry point the IDE/LSP layer builds on: every error +/// keeps its variant, its per-file-local source location (via +/// [`TypeCheckError::location`](crate::errors::TypeCheckError::location)), and +/// its optional module-path file label without any string parsing. See +/// [`TypeCheckOutcome`] for what the returned context is guaranteed to contain +/// when errors are present. +/// +/// [`TypeCheckerBuilder::build_typed_context`] is re-expressed on top of this +/// function, so the two share exactly one checking implementation. +#[must_use = "the outcome carries both the typed context and the diagnostics"] +pub fn check_with_diagnostics(arena: AstArena) -> TypeCheckOutcome { + let mut ctx = TypedContext::new(arena); + let mut type_checker = TypeChecker::default(); + let (symbol_table, errors) = type_checker.check_collecting(&mut ctx); + // Assign the symbol table and build the canonical-key indexes even when there + // are errors, so the partial context answers `lookup_struct`/`lookup_enum` + // and method/call queries for the parts of the program that did check — the + // whole point of a lossless entry point for tooling. + ctx.symbol_table = symbol_table; + ctx.build_type_indexes(); + let errors = errors + .into_iter() + .map(|(file_label, error)| TypeCheckDiagnostic { file_label, error }) + .collect(); + TypeCheckOutcome { + typed_context: ctx, + errors, + } +} diff --git a/core/type-checker/src/type_checker.rs b/core/type-checker/src/type_checker.rs index a79b4a99..18fb04f3 100644 --- a/core/type-checker/src/type_checker.rs +++ b/core/type-checker/src/type_checker.rs @@ -30,7 +30,6 @@ //! `ConflictingTypeInference` / `CannotInferTypeParameter` when the //! substitution can't be determined unambiguously. -use anyhow::bail; use inference_ast::arena::AstArena; use inference_ast::extern_prelude::ExternPrelude; use inference_ast::ids::{DefId, ExprId, IdentId, NodeId, StmtId, TypeId}; @@ -171,7 +170,7 @@ impl TypeChecker { /// Load external modules from prelude before import resolution. /// /// The prelude is consumed (moved into symbol table as virtual scopes). - /// Call this before `infer_types()` to make external modules available. + /// Call this before `check_collecting()` to make external modules available. /// /// # Arguments /// * `prelude` - The external prelude containing parsed external modules @@ -189,7 +188,18 @@ impl TypeChecker { } impl TypeChecker { - /// Infer types for all definitions in the context. + /// Runs every type-check phase and returns the populated symbol table paired + /// with the structured errors collected along the way (empty on success). + /// + /// This is the single implementation of the phase pipeline; both entry points + /// go through it. It never fails: errors are collected rather than fatal (see + /// the module docs), so every phase runs to completion and the returned symbol + /// table is as complete as the checker could make it even when some bodies + /// failed to type-check. The caller decides how to surface the errors — + /// [`check_with_diagnostics`](crate::check_with_diagnostics) returns them + /// structured, while + /// [`TypeCheckerBuilder::build_typed_context`](crate::TypeCheckerBuilder::build_typed_context) + /// renders and joins them into one aggregated [`anyhow::Error`]. /// /// Phase ordering: /// 1. `process_directives()` - Register raw imports in scopes @@ -197,7 +207,10 @@ impl TypeChecker { /// 3. `resolve_imports()` - Bind import paths to symbols /// 4. `collect_function_and_constant_definitions()` - Register functions /// 5. Infer variable types in function bodies - pub fn infer_types(&mut self, ctx: &mut TypedContext) -> anyhow::Result { + pub(crate) fn check_collecting( + &mut self, + ctx: &mut TypedContext, + ) -> (SymbolTable, Vec<(Option, TypeCheckError)>) { self.process_directives(ctx); self.collect_extern_bindings(ctx); self.register_types(ctx); @@ -249,20 +262,7 @@ impl TypeChecker { } } self.exit_files(); - if !self.errors.is_empty() { - // Prefix each error with the `::`-joined module path of the file it was - // produced in; the entry file stays a bare `line:col` (its `label` is - // `None`), so single-file programs read exactly as before. - let error_messages: Vec = std::mem::take(&mut self.errors) - .into_iter() - .map(|(label, error)| match label { - Some(label) => format!("{label}:{error}"), - None => error.to_string(), - }) - .collect(); - bail!(error_messages.join("; ")) - } - Ok(self.symbol_table.clone()) + (self.symbol_table.clone(), std::mem::take(&mut self.errors)) } fn infer_def(&mut self, def_id: DefId, ctx: &mut TypedContext) { @@ -3757,9 +3757,16 @@ impl TypeChecker { let extern_decls = Self::collect_top_level_extern_decls(arena); - // field name → (distinct modules in first-seen order, first import location) - let mut imports: FxHashMap, Location)> = FxHashMap::default(); + // field name → (distinct modules in first-seen order, first import + // location, label of the file that owns that first `use … from`). The + // owning-file label rides alongside the location because this scan runs + // at the root cursor over every file's directives: a dangling or + // ambiguous import in an imported file must be stamped with that file, + // not the entry, or the location (per-file-local) is misattributed. + let mut imports: FxHashMap, Location, Option)> = + FxHashMap::default(); for sf in arena.source_files() { + let owner_label = inference_ast::nodes::file_label(&sf.module_path); for directive in &sf.directives { let Directive::Use(use_dir) = directive; let Some(module_ref) = &use_dir.from else { @@ -3775,7 +3782,7 @@ impl TypeChecker { let field = arena[field_id].name.clone(); let entry = imports .entry(field) - .or_insert_with(|| (Vec::new(), use_dir.location)); + .or_insert_with(|| (Vec::new(), use_dir.location, owner_label.clone())); if !entry.0.contains(&module) { entry.0.push(module.clone()); } @@ -3783,13 +3790,16 @@ impl TypeChecker { } } - for (field, (modules, location)) in imports { + for (field, (modules, location, owner_label)) in imports { let Some(&decl) = extern_decls.get(&field) else { - self.push_error(TypeCheckError::ExternImportNotDeclared { - name: field, - module: modules.join(", "), - location, - }); + self.push_error_with_label( + owner_label, + TypeCheckError::ExternImportNotDeclared { + name: field, + module: modules.join(", "), + location, + }, + ); continue; }; if modules.len() > 1 { @@ -3798,11 +3808,14 @@ impl TypeChecker { .map(|m| format!("`{m}`")) .collect::>() .join(", "); - self.push_error(TypeCheckError::AmbiguousExternModule { - name: field, - modules: module_list, - location, - }); + self.push_error_with_label( + owner_label, + TypeCheckError::AmbiguousExternModule { + name: field, + modules: module_list, + location, + }, + ); continue; } let logical_module = modules.into_iter().next().expect("one module"); @@ -4637,6 +4650,18 @@ impl TypeChecker { self.errors.push((label, error)); } + /// Records an error stamped with an explicit file label rather than the file + /// currently open. Extern-binding collection runs at the root (the current + /// label is `None`) while iterating the `use … from` directives of every + /// file in the closure, so a dangling or ambiguous import belonging to an + /// imported file must carry that file's label — computed from the owning + /// file's module path at scan time — or its per-file-local location is + /// misattributed to the entry document. The entry file's own directives pass + /// `None`, matching every other entry diagnostic. + fn push_error_with_label(&mut self, label: Option, error: TypeCheckError) { + self.errors.push((label, error)); + } + /// Records an import-resolution diagnostic stamped with the *importing* file's /// label (so an unresolvable re-export reads `lib::a:line:col`, not a bare /// `line:col`). diff --git a/editors/vscode/QA_GUIDE.md b/editors/vscode/QA_GUIDE.md index 2575121e..ebe1d47f 100644 --- a/editors/vscode/QA_GUIDE.md +++ b/editors/vscode/QA_GUIDE.md @@ -1,8 +1,8 @@ # Inference VS Code Extension -- Manual QA Guide -**Version:** 0.0.3 -**Branch:** `127-update-vscode-extension-after-removing-llvm` -**Date:** 2026-02-18 +**Version:** 0.0.5 +**Branch:** `33-feature-lsp-server` +**Date:** 2026-07-04 --- @@ -32,11 +32,12 @@ Many QA cases below are covered by automated tests (`npm test`). Cases marked wi | 5. Syntax Highlighting | Manual (requires VS Code host) | | 6. Language Configuration | Manual (requires VS Code host) | | 7. Walkthrough | **[A]** Schema validated (`settings-schema.test.ts`); interactive steps manual | -| 8. Settings | **[A]** Schema validated (9 commands in `settings-schema.test.ts`) | +| 8. Settings | **[A]** Schema validated (5 settings, 11 commands in `settings-schema.test.ts`) | | 9. Error Handling | **[A]** Most paths automated (`install-failures.test.ts`, `version-parsing.test.ts`, `e2e-installation.test.ts`) | | 10. Cross-Platform | Manual (requires physical platforms); detection and extraction logic tested | | 11. Privacy & Security | **[A]** HTTPS redirect + SHA-256 automated (`https-redirect.test.ts`, `download.test.ts`) | | 12. Component Management | Partial -- component args + doctor-attention logic automated (`components.test.ts`, `doctor.test.ts`); UI flows manual | +| 13. Language Server | Partial -- binary resolution + config-change logic automated (`lsp-resolve.test.ts`); client lifecycle and editor features manual | --- @@ -47,8 +48,8 @@ Many QA cases below are covered by automated tests (`npm test`). Cases marked wi | 0.1 | `npm install` in `editors/vscode/` | Installs without errors | | 0.2 | `npm run build` | Builds `dist/extension.js` without errors | | 0.3 | `npm run build:prod` | Production build succeeds | -| 0.4 | `npm test` | All 224 tests pass, 0 failures | -| 0.5 | `npm run package` | Produces `inference-0.0.3.vsix` without errors | +| 0.4 | `npm test` | All 257 tests pass, 0 failures | +| 0.5 | `npm run package` | Produces `inference-0.0.5.vsix` without errors (bundled; no `node_modules` inside the VSIX) | --- @@ -184,18 +185,25 @@ Many QA cases below are covered by automated tests (`npm test`). Cases marked wi | 4.4.8 | If install succeeds but setting default fails | Warning: "Inference: vX.Y.Z was installed but could not be set as default. Run `infs default X.Y.Z` manually." with "Show Output" button | | | 4.4.9 | If install itself fails | Error: "Inference: Failed to install vX.Y.Z: {error}" | | -### 4.5 Show Output (`inference.showOutput`) +### 4.5 Restart Language Server (`inference.restartLsp`) | # | Step | Expected | Pass? | |---|------|----------|-------| -| 4.5.1 | Ctrl+Shift+P > "Inference: Show Output" | Opens the "Inference" output channel panel | | +| 4.5.1 | Ctrl+Shift+P > "Inference: Restart Language Server" (server running) | Output channel "Inference" logs "Language server stopped." then "Language server started: {path} ({source})" | | +| 4.5.2 | Run the command with **no** `inference-lsp` binary available | No notification; Output channel logs "Language server not started: inference-lsp not found ..." | | -### 4.6 Reset PATH Fallback Preference (`inference.resetPathAcceptance`) +### 4.6 Show Output (`inference.showOutput`) | # | Step | Expected | Pass? | |---|------|----------|-------| -| 4.6.1 | Ctrl+Shift+P > "Inference: Reset PATH Fallback Preference" | Info: "Inference: PATH fallback preference has been reset." | | -| 4.6.2 | Reload window after reset (with INFERENCE_HOME set, infs only in PATH) | PATH fallback warning reappears | | +| 4.6.1 | Ctrl+Shift+P > "Inference: Show Output" | Opens the "Inference" output channel panel | | + +### 4.7 Reset PATH Fallback Preference (`inference.resetPathAcceptance`) + +| # | Step | Expected | Pass? | +|---|------|----------|-------| +| 4.7.1 | Ctrl+Shift+P > "Inference: Reset PATH Fallback Preference" | Info: "Inference: PATH fallback preference has been reset." | | +| 4.7.2 | Reload window after reset (with INFERENCE_HOME set, infs only in PATH) | PATH fallback warning reappears | | --- @@ -255,10 +263,12 @@ Many QA cases below are covered by automated tests (`npm test`). Cases marked wi | # | Step | Expected | Pass? | |---|------|----------|-------| -| 8.1 | Open Settings, search "inference" | Shows exactly 3 settings: path, autoInstall, checkForUpdates **[A]** | | +| 8.1 | Open Settings, search "inference" | Shows exactly 5 settings: path, autoInstall, checkForUpdates, lsp.enabled, lsp.path **[A]** | | | 8.2 | `inference.path` | Type: string, default: empty, scope: machine. Accepts file path to infs binary. **[A]** | | | 8.3 | `inference.autoInstall` | Type: boolean, default: true. Toggleable. **[A]** | | | 8.4 | `inference.checkForUpdates` | Type: boolean, default: true. Toggleable. **[A]** | | +| 8.5 | `inference.lsp.enabled` | Type: boolean, default: true. Toggleable. **[A]** | | +| 8.6 | `inference.lsp.path` | Type: string, default: empty, scope: machine. Accepts file path to inference-lsp binary. **[A]** | | --- @@ -313,7 +323,7 @@ host (F5) and, unless noted, a working toolchain (`infs` on PATH or in `INFERENC | # | Step | Expected | Pass? | |---|------|----------|-------| -| 12.1 | In `editors/vscode/`: `npm install`, `npm run build`, `npm test` | Installs and builds clean; all 224 tests pass, 0 failures | | +| 12.1 | In `editors/vscode/`: `npm install`, `npm run build`, `npm test` | Installs and builds clean; all 257 tests pass, 0 failures | | | 12.2 | Ctrl+Shift+P > "Inference: Install Component (wasm-opt)" | Progress notification "Inference Component" ("Installing wasm-opt..."). On success: info "Inference: component 'wasm-opt' installed." Doctor re-runs and the status bar refreshes. | | | 12.3 | After install, run `~/.inference/tools/binaryen/version_130/bin/wasm-opt --version` in a terminal | Prints a Binaryen version (>= 116) | | | 12.4 | Run the install command **again** (component already installed) | Completes quickly with a skip message in the Output channel; success info notification; no error | | @@ -325,3 +335,33 @@ host (F5) and, unless noted, a working toolchain (`infs` on PATH or in `INFERENC | 12.10 | Click "Show Output" on the failure notification | Reveals the Inference output channel with the failure details | | | 12.11 | Click "Retry" on the failure notification | Re-invokes the install command | | | 12.12 | **PATH shadowing:** place a `wasm-opt` on PATH while the managed copy exists, then Run Doctor | Doctor's `wasm-opt` OK line notes the managed copy is shadowed by PATH | | + +--- + +## 13. Language Server + +The extension starts the `inference-lsp` binary (stdio LSP server) automatically +when it can be resolved. Resolution mirrors `infs` detection: `inference.lsp.path` +setting (no fallback if set but not executable) > `INFERENCE_HOME/bin/inference-lsp` +> PATH. Resolution and config-change logic are automated in `lsp-resolve.test.ts`; +the cases below need a live extension host (F5) and a built `inference-lsp` binary. + +| # | Step | Expected | Pass? | +|---|------|----------|-------| +| 13.1 | With `inference-lsp` in `~/.inference/bin` (or on PATH), open a `.inf` file | Output channel "Inference" logs `Language server started: {path} (managed|path)`. A second output channel "Inference Language Server" appears for server traces. | | +| 13.2 | Introduce a syntax/type error in the `.inf` file | Squiggles appear; Problems panel lists the diagnostic | | +| 13.3 | Hover a non-deterministic construct (e.g. `forall`) | Hover popup explains the operator | | +| 13.4 | Hover a variable or function name | Hover shows type information | | +| 13.5 | F12 (Go to Definition) on a function call | Cursor jumps to the function definition | | +| 13.6 | Trigger completion (Ctrl+Space) in a function body | Context-aware completion items appear | | +| 13.7 | Open the Outline view | Document symbols (functions, types) are listed | | +| 13.8 | Rename note | Rename (F2) is not provided yet -- no crash, VS Code reports no rename provider | | +| 13.9 | **Missing binary (quiet path):** remove `inference-lsp` from all locations, reload window | NO notification. Output channel logs `Language server not started: inference-lsp not found ...`. Toolchain-missing notification (if any) comes from the toolchain check only. | | +| 13.10 | **Out-of-the-box story:** from 13.9, run "Inference: Install Toolchain" and wait for success | Language server starts automatically after the install completes, WITHOUT a window reload (Output shows `Language server started: ...`) | | +| 13.11 | **Disable:** set `inference.lsp.enabled: false` while the server is running | Server stops (Output: "Language server stopped."); diagnostics disappear | | +| 13.12 | **Re-enable:** set `inference.lsp.enabled: true` | Server starts again without a reload | | +| 13.13 | **Custom path:** set `inference.lsp.path` to a valid binary | Server restarts using that path; Output shows `(settings)` as the source | | +| 13.14 | **Invalid custom path (no fallback):** set `inference.lsp.path` to a nonexistent path while managed/PATH binaries exist | Server stops and does NOT fall back; Output logs the path is not executable; no notification | | +| 13.15 | Ctrl+Shift+P > "Inference: Restart Language Server" | Server stops and starts; fresh `Language server started` line in Output | | +| 13.16 | **Update pickup:** after "Inference: Update Toolchain" replaces the managed binary, run the restart command | Server restarts on the new binary version | | +| 13.17 | Close VS Code / reload window | No orphan `inference-lsp` processes remain (check with `ps`/Task Manager) | | diff --git a/editors/vscode/README.md b/editors/vscode/README.md index d9c21a46..4755f863 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -28,6 +28,25 @@ Full syntax highlighting support for Inference language constructs: - Automatically activates for `.inf` files - Custom file icon for Inference source files +### Language Server + +The extension automatically starts the Inference language server (`inference-lsp`) for `.inf` files, providing rich language intelligence: + +- **Diagnostics** - Compiler errors and warnings as you type +- **Hover** - Type information and documentation, including explanations of the non-deterministic operators (`forall`, `exists`, `assume`, `unique`, `@`) +- **Go to Definition** - Jump to symbol definitions (F12) +- **Completions** - Context-aware code completion +- **Document Symbols** - Outline view and breadcrumb navigation +- **Inlay Hints** - Inline type annotations + +The server binary is resolved using the following priority (mirroring `infs` detection): + +1. Custom path from `inference.lsp.path` setting (if set but not executable, the server is not started - no fallback) +2. Managed installation in `INFERENCE_HOME/bin/inference-lsp` (respects `INFERENCE_HOME` environment variable) +3. System `PATH` + +If the binary is not found, the extension stays quiet: a line is logged to the "Inference" output channel and the server simply stays off until the toolchain is installed or updated. Server traces are written to the dedicated "Inference Language Server" output channel. Use **Inference: Restart Language Server** to pick up a new binary after an update or a settings change made outside VS Code. + ### Toolchain Management The extension provides comprehensive toolchain management through integration with the `infs` CLI. All operations are fully automated and require no manual configuration. @@ -87,6 +106,7 @@ Open Command Palette (`Ctrl+Shift+P` / `Cmd+Shift+P`): - **Inference: Update Toolchain** - Check for updates and install the latest version - **Inference: Select Toolchain Version** - Browse and switch between available versions - **Inference: Run Doctor** - Execute comprehensive health diagnostics +- **Inference: Restart Language Server** - Stop and restart `inference-lsp`, re-resolving the binary location - **Inference: Refresh Configuration** - Reload the Configuration sidebar view - **Inference: Show Output** - Open the Inference output log channel - **Inference: Reset PATH Fallback Preference** - Clear saved PATH fallback acceptance @@ -116,6 +136,8 @@ A guided setup walkthrough is available via **Get Started: Open Walkthrough...** - **`inference.path`** (string, default: `""`) - Custom path to the `infs` binary. Leave empty for automatic detection. Scope: machine (not synced across devices). - **`inference.autoInstall`** (boolean, default: `true`) - Prompt to install toolchain if not found on activation. - **`inference.checkForUpdates`** (boolean, default: `true`) - Automatically check for toolchain updates on activation. +- **`inference.lsp.enabled`** (boolean, default: `true`) - Start the Inference language server automatically. Disable to turn off all language intelligence features. +- **`inference.lsp.path`** (string, default: `""`) - Custom path to the `inference-lsp` binary. Leave empty for automatic detection. Scope: machine (not synced across devices). ### Environment Variables @@ -184,6 +206,14 @@ Learn more: 3. Verify `inference.path` setting if using a custom location 4. Try **Inference: Install Toolchain** to install automatically +### Language server not running + +1. Check the Output panel (View > Output > Select "Inference") for a "Language server" log line explaining why it did not start +2. Ensure `inference.lsp.enabled` is `true` +3. Install or update the toolchain (**Inference: Install Toolchain** / **Inference: Update Toolchain**) so `inference-lsp` is present in `INFERENCE_HOME/bin` +4. Alternatively, set `inference.lsp.path` to the binary location (note: if this setting points to a non-executable path, the server is not started and no fallback occurs) +5. Run **Inference: Restart Language Server** after fixing the binary location + ### Terminal commands not found 1. Close all open terminals and open a new one (Terminal > New Terminal) diff --git a/editors/vscode/dist/extension.js b/editors/vscode/dist/extension.js index 7a8e2518..32b3fa7c 100644 --- a/editors/vscode/dist/extension.js +++ b/editors/vscode/dist/extension.js @@ -8,6 +8,9 @@ var __hasOwnProp = Object.prototype.hasOwnProperty; var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -64,79 +67,18169 @@ function exec(command, args, options) { stdout: Buffer.concat(stdoutChunks).toString("utf-8"), stderr: Buffer.concat(stderrChunks).toString("utf-8") }); - }); - }); -} -var cp, DEFAULT_TIMEOUT_MS; -var init_exec = __esm({ - "src/utils/exec.ts"() { - "use strict"; - cp = __toESM(require("child_process")); - DEFAULT_TIMEOUT_MS = 3e4; + }); + }); +} +var cp, DEFAULT_TIMEOUT_MS; +var init_exec = __esm({ + "src/utils/exec.ts"() { + "use strict"; + cp = __toESM(require("child_process")); + DEFAULT_TIMEOUT_MS = 3e4; + } +}); + +// src/toolchain/doctor.ts +var doctor_exports = {}; +__export(doctor_exports, { + parseDoctorOutput: () => parseDoctorOutput, + runDoctor: () => runDoctor +}); +function parseDoctorOutput(stdout) { + const checks = []; + const lines = stdout.split(/\r?\n/); + for (const line of lines) { + const match = line.match(CHECK_PATTERN); + if (match) { + checks.push({ + status: STATUS_MAP[match[1]], + name: match[2].trim(), + message: match[3].trim() + }); + } + } + let summary = ""; + for (let i = lines.length - 1; i >= 0; i--) { + const trimmed = lines[i].trim(); + if (trimmed.length > 0 && !CHECK_PATTERN.test(lines[i])) { + summary = trimmed; + break; + } + } + return { + checks, + hasErrors: checks.some((c) => c.status === "fail"), + hasWarnings: checks.some((c) => c.status === "warn"), + summary + }; +} +async function runDoctor(infsPath) { + try { + const binDir = path4.join(inferenceHome(), "bin"); + const sep = process.platform === "win32" ? ";" : ":"; + const augmentedPath = `${binDir}${sep}${process.env["PATH"] ?? ""}`; + const result = await exec(infsPath, ["doctor"], { + env: { PATH: augmentedPath } + }); + return parseDoctorOutput(result.stdout); + } catch (err) { + console.error("infs doctor failed:", err); + return null; + } +} +var path4, STATUS_MAP, CHECK_PATTERN; +var init_doctor = __esm({ + "src/toolchain/doctor.ts"() { + "use strict"; + path4 = __toESM(require("path")); + init_exec(); + init_home(); + STATUS_MAP = { + OK: "ok", + WARN: "warn", + FAIL: "fail" + }; + CHECK_PATTERN = /^\s+\[(OK|WARN|FAIL)]\s+(.+?):\s+(.*)/; + } +}); + +// node_modules/vscode-languageclient/lib/common/utils/is.js +var require_is = __commonJS({ + "node_modules/vscode-languageclient/lib/common/utils/is.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.asPromise = exports2.thenable = exports2.typedArray = exports2.stringArray = exports2.array = exports2.func = exports2.error = exports2.number = exports2.string = exports2.boolean = void 0; + function boolean(value) { + return value === true || value === false; + } + exports2.boolean = boolean; + function string(value) { + return typeof value === "string" || value instanceof String; + } + exports2.string = string; + function number(value) { + return typeof value === "number" || value instanceof Number; + } + exports2.number = number; + function error(value) { + return value instanceof Error; + } + exports2.error = error; + function func(value) { + return typeof value === "function"; + } + exports2.func = func; + function array(value) { + return Array.isArray(value); + } + exports2.array = array; + function stringArray(value) { + return array(value) && value.every((elem) => string(elem)); + } + exports2.stringArray = stringArray; + function typedArray(value, check) { + return Array.isArray(value) && value.every(check); + } + exports2.typedArray = typedArray; + function thenable(value) { + return value && func(value.then); + } + exports2.thenable = thenable; + function asPromise(value) { + if (value instanceof Promise) { + return value; + } else if (thenable(value)) { + return new Promise((resolve, reject) => { + value.then((resolved) => resolve(resolved), (error2) => reject(error2)); + }); + } else { + return Promise.resolve(value); + } + } + exports2.asPromise = asPromise; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/is.js +var require_is2 = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/is.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.stringArray = exports2.array = exports2.func = exports2.error = exports2.number = exports2.string = exports2.boolean = void 0; + function boolean(value) { + return value === true || value === false; + } + exports2.boolean = boolean; + function string(value) { + return typeof value === "string" || value instanceof String; + } + exports2.string = string; + function number(value) { + return typeof value === "number" || value instanceof Number; + } + exports2.number = number; + function error(value) { + return value instanceof Error; + } + exports2.error = error; + function func(value) { + return typeof value === "function"; + } + exports2.func = func; + function array(value) { + return Array.isArray(value); + } + exports2.array = array; + function stringArray(value) { + return array(value) && value.every((elem) => string(elem)); + } + exports2.stringArray = stringArray; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/messages.js +var require_messages = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/messages.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Message = exports2.NotificationType9 = exports2.NotificationType8 = exports2.NotificationType7 = exports2.NotificationType6 = exports2.NotificationType5 = exports2.NotificationType4 = exports2.NotificationType3 = exports2.NotificationType2 = exports2.NotificationType1 = exports2.NotificationType0 = exports2.NotificationType = exports2.RequestType9 = exports2.RequestType8 = exports2.RequestType7 = exports2.RequestType6 = exports2.RequestType5 = exports2.RequestType4 = exports2.RequestType3 = exports2.RequestType2 = exports2.RequestType1 = exports2.RequestType = exports2.RequestType0 = exports2.AbstractMessageSignature = exports2.ParameterStructures = exports2.ResponseError = exports2.ErrorCodes = void 0; + var is = require_is2(); + var ErrorCodes; + (function(ErrorCodes2) { + ErrorCodes2.ParseError = -32700; + ErrorCodes2.InvalidRequest = -32600; + ErrorCodes2.MethodNotFound = -32601; + ErrorCodes2.InvalidParams = -32602; + ErrorCodes2.InternalError = -32603; + ErrorCodes2.jsonrpcReservedErrorRangeStart = -32099; + ErrorCodes2.serverErrorStart = -32099; + ErrorCodes2.MessageWriteError = -32099; + ErrorCodes2.MessageReadError = -32098; + ErrorCodes2.PendingResponseRejected = -32097; + ErrorCodes2.ConnectionInactive = -32096; + ErrorCodes2.ServerNotInitialized = -32002; + ErrorCodes2.UnknownErrorCode = -32001; + ErrorCodes2.jsonrpcReservedErrorRangeEnd = -32e3; + ErrorCodes2.serverErrorEnd = -32e3; + })(ErrorCodes || (exports2.ErrorCodes = ErrorCodes = {})); + var ResponseError = class _ResponseError extends Error { + constructor(code, message, data) { + super(message); + this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode; + this.data = data; + Object.setPrototypeOf(this, _ResponseError.prototype); + } + toJson() { + const result = { + code: this.code, + message: this.message + }; + if (this.data !== void 0) { + result.data = this.data; + } + return result; + } + }; + exports2.ResponseError = ResponseError; + var ParameterStructures = class _ParameterStructures { + constructor(kind) { + this.kind = kind; + } + static is(value) { + return value === _ParameterStructures.auto || value === _ParameterStructures.byName || value === _ParameterStructures.byPosition; + } + toString() { + return this.kind; + } + }; + exports2.ParameterStructures = ParameterStructures; + ParameterStructures.auto = new ParameterStructures("auto"); + ParameterStructures.byPosition = new ParameterStructures("byPosition"); + ParameterStructures.byName = new ParameterStructures("byName"); + var AbstractMessageSignature = class { + constructor(method, numberOfParams) { + this.method = method; + this.numberOfParams = numberOfParams; + } + get parameterStructures() { + return ParameterStructures.auto; + } + }; + exports2.AbstractMessageSignature = AbstractMessageSignature; + var RequestType0 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 0); + } + }; + exports2.RequestType0 = RequestType0; + var RequestType = class extends AbstractMessageSignature { + constructor(method, _parameterStructures = ParameterStructures.auto) { + super(method, 1); + this._parameterStructures = _parameterStructures; + } + get parameterStructures() { + return this._parameterStructures; + } + }; + exports2.RequestType = RequestType; + var RequestType1 = class extends AbstractMessageSignature { + constructor(method, _parameterStructures = ParameterStructures.auto) { + super(method, 1); + this._parameterStructures = _parameterStructures; + } + get parameterStructures() { + return this._parameterStructures; + } + }; + exports2.RequestType1 = RequestType1; + var RequestType2 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 2); + } + }; + exports2.RequestType2 = RequestType2; + var RequestType3 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 3); + } + }; + exports2.RequestType3 = RequestType3; + var RequestType4 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 4); + } + }; + exports2.RequestType4 = RequestType4; + var RequestType5 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 5); + } + }; + exports2.RequestType5 = RequestType5; + var RequestType6 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 6); + } + }; + exports2.RequestType6 = RequestType6; + var RequestType7 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 7); + } + }; + exports2.RequestType7 = RequestType7; + var RequestType8 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 8); + } + }; + exports2.RequestType8 = RequestType8; + var RequestType9 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 9); + } + }; + exports2.RequestType9 = RequestType9; + var NotificationType = class extends AbstractMessageSignature { + constructor(method, _parameterStructures = ParameterStructures.auto) { + super(method, 1); + this._parameterStructures = _parameterStructures; + } + get parameterStructures() { + return this._parameterStructures; + } + }; + exports2.NotificationType = NotificationType; + var NotificationType0 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 0); + } + }; + exports2.NotificationType0 = NotificationType0; + var NotificationType1 = class extends AbstractMessageSignature { + constructor(method, _parameterStructures = ParameterStructures.auto) { + super(method, 1); + this._parameterStructures = _parameterStructures; + } + get parameterStructures() { + return this._parameterStructures; + } + }; + exports2.NotificationType1 = NotificationType1; + var NotificationType2 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 2); + } + }; + exports2.NotificationType2 = NotificationType2; + var NotificationType3 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 3); + } + }; + exports2.NotificationType3 = NotificationType3; + var NotificationType4 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 4); + } + }; + exports2.NotificationType4 = NotificationType4; + var NotificationType5 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 5); + } + }; + exports2.NotificationType5 = NotificationType5; + var NotificationType6 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 6); + } + }; + exports2.NotificationType6 = NotificationType6; + var NotificationType7 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 7); + } + }; + exports2.NotificationType7 = NotificationType7; + var NotificationType8 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 8); + } + }; + exports2.NotificationType8 = NotificationType8; + var NotificationType9 = class extends AbstractMessageSignature { + constructor(method) { + super(method, 9); + } + }; + exports2.NotificationType9 = NotificationType9; + var Message; + (function(Message2) { + function isRequest(message) { + const candidate = message; + return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id)); + } + Message2.isRequest = isRequest; + function isNotification(message) { + const candidate = message; + return candidate && is.string(candidate.method) && message.id === void 0; + } + Message2.isNotification = isNotification; + function isResponse(message) { + const candidate = message; + return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null); + } + Message2.isResponse = isResponse; + })(Message || (exports2.Message = Message = {})); + } +}); + +// node_modules/vscode-jsonrpc/lib/common/linkedMap.js +var require_linkedMap = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/linkedMap.js"(exports2) { + "use strict"; + var _a; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.LRUCache = exports2.LinkedMap = exports2.Touch = void 0; + var Touch; + (function(Touch2) { + Touch2.None = 0; + Touch2.First = 1; + Touch2.AsOld = Touch2.First; + Touch2.Last = 2; + Touch2.AsNew = Touch2.Last; + })(Touch || (exports2.Touch = Touch = {})); + var LinkedMap = class { + constructor() { + this[_a] = "LinkedMap"; + this._map = /* @__PURE__ */ new Map(); + this._head = void 0; + this._tail = void 0; + this._size = 0; + this._state = 0; + } + clear() { + this._map.clear(); + this._head = void 0; + this._tail = void 0; + this._size = 0; + this._state++; + } + isEmpty() { + return !this._head && !this._tail; + } + get size() { + return this._size; + } + get first() { + return this._head?.value; + } + get last() { + return this._tail?.value; + } + has(key) { + return this._map.has(key); + } + get(key, touch = Touch.None) { + const item = this._map.get(key); + if (!item) { + return void 0; + } + if (touch !== Touch.None) { + this.touch(item, touch); + } + return item.value; + } + set(key, value, touch = Touch.None) { + let item = this._map.get(key); + if (item) { + item.value = value; + if (touch !== Touch.None) { + this.touch(item, touch); + } + } else { + item = { key, value, next: void 0, previous: void 0 }; + switch (touch) { + case Touch.None: + this.addItemLast(item); + break; + case Touch.First: + this.addItemFirst(item); + break; + case Touch.Last: + this.addItemLast(item); + break; + default: + this.addItemLast(item); + break; + } + this._map.set(key, item); + this._size++; + } + return this; + } + delete(key) { + return !!this.remove(key); + } + remove(key) { + const item = this._map.get(key); + if (!item) { + return void 0; + } + this._map.delete(key); + this.removeItem(item); + this._size--; + return item.value; + } + shift() { + if (!this._head && !this._tail) { + return void 0; + } + if (!this._head || !this._tail) { + throw new Error("Invalid list"); + } + const item = this._head; + this._map.delete(item.key); + this.removeItem(item); + this._size--; + return item.value; + } + forEach(callbackfn, thisArg) { + const state = this._state; + let current = this._head; + while (current) { + if (thisArg) { + callbackfn.bind(thisArg)(current.value, current.key, this); + } else { + callbackfn(current.value, current.key, this); + } + if (this._state !== state) { + throw new Error(`LinkedMap got modified during iteration.`); + } + current = current.next; + } + } + keys() { + const state = this._state; + let current = this._head; + const iterator = { + [Symbol.iterator]: () => { + return iterator; + }, + next: () => { + if (this._state !== state) { + throw new Error(`LinkedMap got modified during iteration.`); + } + if (current) { + const result = { value: current.key, done: false }; + current = current.next; + return result; + } else { + return { value: void 0, done: true }; + } + } + }; + return iterator; + } + values() { + const state = this._state; + let current = this._head; + const iterator = { + [Symbol.iterator]: () => { + return iterator; + }, + next: () => { + if (this._state !== state) { + throw new Error(`LinkedMap got modified during iteration.`); + } + if (current) { + const result = { value: current.value, done: false }; + current = current.next; + return result; + } else { + return { value: void 0, done: true }; + } + } + }; + return iterator; + } + entries() { + const state = this._state; + let current = this._head; + const iterator = { + [Symbol.iterator]: () => { + return iterator; + }, + next: () => { + if (this._state !== state) { + throw new Error(`LinkedMap got modified during iteration.`); + } + if (current) { + const result = { value: [current.key, current.value], done: false }; + current = current.next; + return result; + } else { + return { value: void 0, done: true }; + } + } + }; + return iterator; + } + [(_a = Symbol.toStringTag, Symbol.iterator)]() { + return this.entries(); + } + trimOld(newSize) { + if (newSize >= this.size) { + return; + } + if (newSize === 0) { + this.clear(); + return; + } + let current = this._head; + let currentSize = this.size; + while (current && currentSize > newSize) { + this._map.delete(current.key); + current = current.next; + currentSize--; + } + this._head = current; + this._size = currentSize; + if (current) { + current.previous = void 0; + } + this._state++; + } + addItemFirst(item) { + if (!this._head && !this._tail) { + this._tail = item; + } else if (!this._head) { + throw new Error("Invalid list"); + } else { + item.next = this._head; + this._head.previous = item; + } + this._head = item; + this._state++; + } + addItemLast(item) { + if (!this._head && !this._tail) { + this._head = item; + } else if (!this._tail) { + throw new Error("Invalid list"); + } else { + item.previous = this._tail; + this._tail.next = item; + } + this._tail = item; + this._state++; + } + removeItem(item) { + if (item === this._head && item === this._tail) { + this._head = void 0; + this._tail = void 0; + } else if (item === this._head) { + if (!item.next) { + throw new Error("Invalid list"); + } + item.next.previous = void 0; + this._head = item.next; + } else if (item === this._tail) { + if (!item.previous) { + throw new Error("Invalid list"); + } + item.previous.next = void 0; + this._tail = item.previous; + } else { + const next = item.next; + const previous = item.previous; + if (!next || !previous) { + throw new Error("Invalid list"); + } + next.previous = previous; + previous.next = next; + } + item.next = void 0; + item.previous = void 0; + this._state++; + } + touch(item, touch) { + if (!this._head || !this._tail) { + throw new Error("Invalid list"); + } + if (touch !== Touch.First && touch !== Touch.Last) { + return; + } + if (touch === Touch.First) { + if (item === this._head) { + return; + } + const next = item.next; + const previous = item.previous; + if (item === this._tail) { + previous.next = void 0; + this._tail = previous; + } else { + next.previous = previous; + previous.next = next; + } + item.previous = void 0; + item.next = this._head; + this._head.previous = item; + this._head = item; + this._state++; + } else if (touch === Touch.Last) { + if (item === this._tail) { + return; + } + const next = item.next; + const previous = item.previous; + if (item === this._head) { + next.previous = void 0; + this._head = next; + } else { + next.previous = previous; + previous.next = next; + } + item.next = void 0; + item.previous = this._tail; + this._tail.next = item; + this._tail = item; + this._state++; + } + } + toJSON() { + const data = []; + this.forEach((value, key) => { + data.push([key, value]); + }); + return data; + } + fromJSON(data) { + this.clear(); + for (const [key, value] of data) { + this.set(key, value); + } + } + }; + exports2.LinkedMap = LinkedMap; + var LRUCache = class extends LinkedMap { + constructor(limit, ratio = 1) { + super(); + this._limit = limit; + this._ratio = Math.min(Math.max(0, ratio), 1); + } + get limit() { + return this._limit; + } + set limit(limit) { + this._limit = limit; + this.checkTrim(); + } + get ratio() { + return this._ratio; + } + set ratio(ratio) { + this._ratio = Math.min(Math.max(0, ratio), 1); + this.checkTrim(); + } + get(key, touch = Touch.AsNew) { + return super.get(key, touch); + } + peek(key) { + return super.get(key, Touch.None); + } + set(key, value) { + super.set(key, value, Touch.Last); + this.checkTrim(); + return this; + } + checkTrim() { + if (this.size > this._limit) { + this.trimOld(Math.round(this._limit * this._ratio)); + } + } + }; + exports2.LRUCache = LRUCache; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/disposable.js +var require_disposable = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/disposable.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Disposable = void 0; + var Disposable2; + (function(Disposable3) { + function create(func) { + return { + dispose: func + }; + } + Disposable3.create = create; + })(Disposable2 || (exports2.Disposable = Disposable2 = {})); + } +}); + +// node_modules/vscode-jsonrpc/lib/common/ral.js +var require_ral = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/ral.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var _ral; + function RAL() { + if (_ral === void 0) { + throw new Error(`No runtime abstraction layer installed`); + } + return _ral; + } + (function(RAL2) { + function install(ral) { + if (ral === void 0) { + throw new Error(`No runtime abstraction layer provided`); + } + _ral = ral; + } + RAL2.install = install; + })(RAL || (RAL = {})); + exports2.default = RAL; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/events.js +var require_events = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/events.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Emitter = exports2.Event = void 0; + var ral_1 = require_ral(); + var Event; + (function(Event2) { + const _disposable = { dispose() { + } }; + Event2.None = function() { + return _disposable; + }; + })(Event || (exports2.Event = Event = {})); + var CallbackList = class { + add(callback, context = null, bucket) { + if (!this._callbacks) { + this._callbacks = []; + this._contexts = []; + } + this._callbacks.push(callback); + this._contexts.push(context); + if (Array.isArray(bucket)) { + bucket.push({ dispose: () => this.remove(callback, context) }); + } + } + remove(callback, context = null) { + if (!this._callbacks) { + return; + } + let foundCallbackWithDifferentContext = false; + for (let i = 0, len = this._callbacks.length; i < len; i++) { + if (this._callbacks[i] === callback) { + if (this._contexts[i] === context) { + this._callbacks.splice(i, 1); + this._contexts.splice(i, 1); + return; + } else { + foundCallbackWithDifferentContext = true; + } + } + } + if (foundCallbackWithDifferentContext) { + throw new Error("When adding a listener with a context, you should remove it with the same context"); + } + } + invoke(...args) { + if (!this._callbacks) { + return []; + } + const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0); + for (let i = 0, len = callbacks.length; i < len; i++) { + try { + ret.push(callbacks[i].apply(contexts[i], args)); + } catch (e) { + (0, ral_1.default)().console.error(e); + } + } + return ret; + } + isEmpty() { + return !this._callbacks || this._callbacks.length === 0; + } + dispose() { + this._callbacks = void 0; + this._contexts = void 0; + } + }; + var Emitter = class _Emitter { + constructor(_options) { + this._options = _options; + } + /** + * For the public to allow to subscribe + * to events from this Emitter + */ + get event() { + if (!this._event) { + this._event = (listener, thisArgs, disposables) => { + if (!this._callbacks) { + this._callbacks = new CallbackList(); + } + if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) { + this._options.onFirstListenerAdd(this); + } + this._callbacks.add(listener, thisArgs); + const result = { + dispose: () => { + if (!this._callbacks) { + return; + } + this._callbacks.remove(listener, thisArgs); + result.dispose = _Emitter._noop; + if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) { + this._options.onLastListenerRemove(this); + } + } + }; + if (Array.isArray(disposables)) { + disposables.push(result); + } + return result; + }; + } + return this._event; + } + /** + * To be kept private to fire an event to + * subscribers + */ + fire(event) { + if (this._callbacks) { + this._callbacks.invoke.call(this._callbacks, event); + } + } + dispose() { + if (this._callbacks) { + this._callbacks.dispose(); + this._callbacks = void 0; + } + } + }; + exports2.Emitter = Emitter; + Emitter._noop = function() { + }; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/cancellation.js +var require_cancellation = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/cancellation.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CancellationTokenSource = exports2.CancellationToken = void 0; + var ral_1 = require_ral(); + var Is = require_is2(); + var events_1 = require_events(); + var CancellationToken; + (function(CancellationToken2) { + CancellationToken2.None = Object.freeze({ + isCancellationRequested: false, + onCancellationRequested: events_1.Event.None + }); + CancellationToken2.Cancelled = Object.freeze({ + isCancellationRequested: true, + onCancellationRequested: events_1.Event.None + }); + function is(value) { + const candidate = value; + return candidate && (candidate === CancellationToken2.None || candidate === CancellationToken2.Cancelled || Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested); + } + CancellationToken2.is = is; + })(CancellationToken || (exports2.CancellationToken = CancellationToken = {})); + var shortcutEvent = Object.freeze(function(callback, context) { + const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0); + return { dispose() { + handle.dispose(); + } }; + }); + var MutableToken = class { + constructor() { + this._isCancelled = false; + } + cancel() { + if (!this._isCancelled) { + this._isCancelled = true; + if (this._emitter) { + this._emitter.fire(void 0); + this.dispose(); + } + } + } + get isCancellationRequested() { + return this._isCancelled; + } + get onCancellationRequested() { + if (this._isCancelled) { + return shortcutEvent; + } + if (!this._emitter) { + this._emitter = new events_1.Emitter(); + } + return this._emitter.event; + } + dispose() { + if (this._emitter) { + this._emitter.dispose(); + this._emitter = void 0; + } + } + }; + var CancellationTokenSource = class { + get token() { + if (!this._token) { + this._token = new MutableToken(); + } + return this._token; + } + cancel() { + if (!this._token) { + this._token = CancellationToken.Cancelled; + } else { + this._token.cancel(); + } + } + dispose() { + if (!this._token) { + this._token = CancellationToken.None; + } else if (this._token instanceof MutableToken) { + this._token.dispose(); + } + } + }; + exports2.CancellationTokenSource = CancellationTokenSource; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js +var require_sharedArrayCancellation = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SharedArrayReceiverStrategy = exports2.SharedArraySenderStrategy = void 0; + var cancellation_1 = require_cancellation(); + var CancellationState; + (function(CancellationState2) { + CancellationState2.Continue = 0; + CancellationState2.Cancelled = 1; + })(CancellationState || (CancellationState = {})); + var SharedArraySenderStrategy = class { + constructor() { + this.buffers = /* @__PURE__ */ new Map(); + } + enableCancellation(request) { + if (request.id === null) { + return; + } + const buffer = new SharedArrayBuffer(4); + const data = new Int32Array(buffer, 0, 1); + data[0] = CancellationState.Continue; + this.buffers.set(request.id, buffer); + request.$cancellationData = buffer; + } + async sendCancellation(_conn, id) { + const buffer = this.buffers.get(id); + if (buffer === void 0) { + return; + } + const data = new Int32Array(buffer, 0, 1); + Atomics.store(data, 0, CancellationState.Cancelled); + } + cleanup(id) { + this.buffers.delete(id); + } + dispose() { + this.buffers.clear(); + } + }; + exports2.SharedArraySenderStrategy = SharedArraySenderStrategy; + var SharedArrayBufferCancellationToken = class { + constructor(buffer) { + this.data = new Int32Array(buffer, 0, 1); + } + get isCancellationRequested() { + return Atomics.load(this.data, 0) === CancellationState.Cancelled; + } + get onCancellationRequested() { + throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`); + } + }; + var SharedArrayBufferCancellationTokenSource = class { + constructor(buffer) { + this.token = new SharedArrayBufferCancellationToken(buffer); + } + cancel() { + } + dispose() { + } + }; + var SharedArrayReceiverStrategy = class { + constructor() { + this.kind = "request"; + } + createCancellationTokenSource(request) { + const buffer = request.$cancellationData; + if (buffer === void 0) { + return new cancellation_1.CancellationTokenSource(); + } + return new SharedArrayBufferCancellationTokenSource(buffer); + } + }; + exports2.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/semaphore.js +var require_semaphore = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/semaphore.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Semaphore = void 0; + var ral_1 = require_ral(); + var Semaphore = class { + constructor(capacity = 1) { + if (capacity <= 0) { + throw new Error("Capacity must be greater than 0"); + } + this._capacity = capacity; + this._active = 0; + this._waiting = []; + } + lock(thunk) { + return new Promise((resolve, reject) => { + this._waiting.push({ thunk, resolve, reject }); + this.runNext(); + }); + } + get active() { + return this._active; + } + runNext() { + if (this._waiting.length === 0 || this._active === this._capacity) { + return; + } + (0, ral_1.default)().timer.setImmediate(() => this.doRunNext()); + } + doRunNext() { + if (this._waiting.length === 0 || this._active === this._capacity) { + return; + } + const next = this._waiting.shift(); + this._active++; + if (this._active > this._capacity) { + throw new Error(`To many thunks active`); + } + try { + const result = next.thunk(); + if (result instanceof Promise) { + result.then((value) => { + this._active--; + next.resolve(value); + this.runNext(); + }, (err) => { + this._active--; + next.reject(err); + this.runNext(); + }); + } else { + this._active--; + next.resolve(result); + this.runNext(); + } + } catch (err) { + this._active--; + next.reject(err); + this.runNext(); + } + } + }; + exports2.Semaphore = Semaphore; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/messageReader.js +var require_messageReader = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/messageReader.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReadableStreamMessageReader = exports2.AbstractMessageReader = exports2.MessageReader = void 0; + var ral_1 = require_ral(); + var Is = require_is2(); + var events_1 = require_events(); + var semaphore_1 = require_semaphore(); + var MessageReader; + (function(MessageReader2) { + function is(value) { + let candidate = value; + return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) && Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage); + } + MessageReader2.is = is; + })(MessageReader || (exports2.MessageReader = MessageReader = {})); + var AbstractMessageReader = class { + constructor() { + this.errorEmitter = new events_1.Emitter(); + this.closeEmitter = new events_1.Emitter(); + this.partialMessageEmitter = new events_1.Emitter(); + } + dispose() { + this.errorEmitter.dispose(); + this.closeEmitter.dispose(); + } + get onError() { + return this.errorEmitter.event; + } + fireError(error) { + this.errorEmitter.fire(this.asError(error)); + } + get onClose() { + return this.closeEmitter.event; + } + fireClose() { + this.closeEmitter.fire(void 0); + } + get onPartialMessage() { + return this.partialMessageEmitter.event; + } + firePartialMessage(info) { + this.partialMessageEmitter.fire(info); + } + asError(error) { + if (error instanceof Error) { + return error; + } else { + return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`); + } + } + }; + exports2.AbstractMessageReader = AbstractMessageReader; + var ResolvedMessageReaderOptions; + (function(ResolvedMessageReaderOptions2) { + function fromOptions(options) { + let charset; + let result; + let contentDecoder; + const contentDecoders = /* @__PURE__ */ new Map(); + let contentTypeDecoder; + const contentTypeDecoders = /* @__PURE__ */ new Map(); + if (options === void 0 || typeof options === "string") { + charset = options ?? "utf-8"; + } else { + charset = options.charset ?? "utf-8"; + if (options.contentDecoder !== void 0) { + contentDecoder = options.contentDecoder; + contentDecoders.set(contentDecoder.name, contentDecoder); + } + if (options.contentDecoders !== void 0) { + for (const decoder of options.contentDecoders) { + contentDecoders.set(decoder.name, decoder); + } + } + if (options.contentTypeDecoder !== void 0) { + contentTypeDecoder = options.contentTypeDecoder; + contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder); + } + if (options.contentTypeDecoders !== void 0) { + for (const decoder of options.contentTypeDecoders) { + contentTypeDecoders.set(decoder.name, decoder); + } + } + } + if (contentTypeDecoder === void 0) { + contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder; + contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder); + } + return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders }; + } + ResolvedMessageReaderOptions2.fromOptions = fromOptions; + })(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {})); + var ReadableStreamMessageReader = class extends AbstractMessageReader { + constructor(readable, options) { + super(); + this.readable = readable; + this.options = ResolvedMessageReaderOptions.fromOptions(options); + this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset); + this._partialMessageTimeout = 1e4; + this.nextMessageLength = -1; + this.messageToken = 0; + this.readSemaphore = new semaphore_1.Semaphore(1); + } + set partialMessageTimeout(timeout) { + this._partialMessageTimeout = timeout; + } + get partialMessageTimeout() { + return this._partialMessageTimeout; + } + listen(callback) { + this.nextMessageLength = -1; + this.messageToken = 0; + this.partialMessageTimer = void 0; + this.callback = callback; + const result = this.readable.onData((data) => { + this.onData(data); + }); + this.readable.onError((error) => this.fireError(error)); + this.readable.onClose(() => this.fireClose()); + return result; + } + onData(data) { + try { + this.buffer.append(data); + while (true) { + if (this.nextMessageLength === -1) { + const headers = this.buffer.tryReadHeaders(true); + if (!headers) { + return; + } + const contentLength = headers.get("content-length"); + if (!contentLength) { + this.fireError(new Error(`Header must provide a Content-Length property. +${JSON.stringify(Object.fromEntries(headers))}`)); + return; + } + const length = parseInt(contentLength); + if (isNaN(length)) { + this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`)); + return; + } + this.nextMessageLength = length; + } + const body = this.buffer.tryReadBody(this.nextMessageLength); + if (body === void 0) { + this.setPartialMessageTimer(); + return; + } + this.clearPartialMessageTimer(); + this.nextMessageLength = -1; + this.readSemaphore.lock(async () => { + const bytes = this.options.contentDecoder !== void 0 ? await this.options.contentDecoder.decode(body) : body; + const message = await this.options.contentTypeDecoder.decode(bytes, this.options); + this.callback(message); + }).catch((error) => { + this.fireError(error); + }); + } + } catch (error) { + this.fireError(error); + } + } + clearPartialMessageTimer() { + if (this.partialMessageTimer) { + this.partialMessageTimer.dispose(); + this.partialMessageTimer = void 0; + } + } + setPartialMessageTimer() { + this.clearPartialMessageTimer(); + if (this._partialMessageTimeout <= 0) { + return; + } + this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => { + this.partialMessageTimer = void 0; + if (token === this.messageToken) { + this.firePartialMessage({ messageToken: token, waitingTime: timeout }); + this.setPartialMessageTimer(); + } + }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout); + } + }; + exports2.ReadableStreamMessageReader = ReadableStreamMessageReader; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/messageWriter.js +var require_messageWriter = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/messageWriter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WriteableStreamMessageWriter = exports2.AbstractMessageWriter = exports2.MessageWriter = void 0; + var ral_1 = require_ral(); + var Is = require_is2(); + var semaphore_1 = require_semaphore(); + var events_1 = require_events(); + var ContentLength = "Content-Length: "; + var CRLF = "\r\n"; + var MessageWriter; + (function(MessageWriter2) { + function is(value) { + let candidate = value; + return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) && Is.func(candidate.onError) && Is.func(candidate.write); + } + MessageWriter2.is = is; + })(MessageWriter || (exports2.MessageWriter = MessageWriter = {})); + var AbstractMessageWriter = class { + constructor() { + this.errorEmitter = new events_1.Emitter(); + this.closeEmitter = new events_1.Emitter(); + } + dispose() { + this.errorEmitter.dispose(); + this.closeEmitter.dispose(); + } + get onError() { + return this.errorEmitter.event; + } + fireError(error, message, count) { + this.errorEmitter.fire([this.asError(error), message, count]); + } + get onClose() { + return this.closeEmitter.event; + } + fireClose() { + this.closeEmitter.fire(void 0); + } + asError(error) { + if (error instanceof Error) { + return error; + } else { + return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`); + } + } + }; + exports2.AbstractMessageWriter = AbstractMessageWriter; + var ResolvedMessageWriterOptions; + (function(ResolvedMessageWriterOptions2) { + function fromOptions(options) { + if (options === void 0 || typeof options === "string") { + return { charset: options ?? "utf-8", contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder }; + } else { + return { charset: options.charset ?? "utf-8", contentEncoder: options.contentEncoder, contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder }; + } + } + ResolvedMessageWriterOptions2.fromOptions = fromOptions; + })(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {})); + var WriteableStreamMessageWriter = class extends AbstractMessageWriter { + constructor(writable, options) { + super(); + this.writable = writable; + this.options = ResolvedMessageWriterOptions.fromOptions(options); + this.errorCount = 0; + this.writeSemaphore = new semaphore_1.Semaphore(1); + this.writable.onError((error) => this.fireError(error)); + this.writable.onClose(() => this.fireClose()); + } + async write(msg) { + return this.writeSemaphore.lock(async () => { + const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => { + if (this.options.contentEncoder !== void 0) { + return this.options.contentEncoder.encode(buffer); + } else { + return buffer; + } + }); + return payload.then((buffer) => { + const headers = []; + headers.push(ContentLength, buffer.byteLength.toString(), CRLF); + headers.push(CRLF); + return this.doWrite(msg, headers, buffer); + }, (error) => { + this.fireError(error); + throw error; + }); + }); + } + async doWrite(msg, headers, data) { + try { + await this.writable.write(headers.join(""), "ascii"); + return this.writable.write(data); + } catch (error) { + this.handleError(error, msg); + return Promise.reject(error); + } + } + handleError(error, msg) { + this.errorCount++; + this.fireError(error, msg, this.errorCount); + } + end() { + this.writable.end(); + } + }; + exports2.WriteableStreamMessageWriter = WriteableStreamMessageWriter; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/messageBuffer.js +var require_messageBuffer = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/messageBuffer.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbstractMessageBuffer = void 0; + var CR = 13; + var LF = 10; + var CRLF = "\r\n"; + var AbstractMessageBuffer = class { + constructor(encoding = "utf-8") { + this._encoding = encoding; + this._chunks = []; + this._totalLength = 0; + } + get encoding() { + return this._encoding; + } + append(chunk) { + const toAppend = typeof chunk === "string" ? this.fromString(chunk, this._encoding) : chunk; + this._chunks.push(toAppend); + this._totalLength += toAppend.byteLength; + } + tryReadHeaders(lowerCaseKeys = false) { + if (this._chunks.length === 0) { + return void 0; + } + let state = 0; + let chunkIndex = 0; + let offset = 0; + let chunkBytesRead = 0; + row: while (chunkIndex < this._chunks.length) { + const chunk = this._chunks[chunkIndex]; + offset = 0; + column: while (offset < chunk.length) { + const value = chunk[offset]; + switch (value) { + case CR: + switch (state) { + case 0: + state = 1; + break; + case 2: + state = 3; + break; + default: + state = 0; + } + break; + case LF: + switch (state) { + case 1: + state = 2; + break; + case 3: + state = 4; + offset++; + break row; + default: + state = 0; + } + break; + default: + state = 0; + } + offset++; + } + chunkBytesRead += chunk.byteLength; + chunkIndex++; + } + if (state !== 4) { + return void 0; + } + const buffer = this._read(chunkBytesRead + offset); + const result = /* @__PURE__ */ new Map(); + const headers = this.toString(buffer, "ascii").split(CRLF); + if (headers.length < 2) { + return result; + } + for (let i = 0; i < headers.length - 2; i++) { + const header = headers[i]; + const index = header.indexOf(":"); + if (index === -1) { + throw new Error(`Message header must separate key and value using ':' +${header}`); + } + const key = header.substr(0, index); + const value = header.substr(index + 1).trim(); + result.set(lowerCaseKeys ? key.toLowerCase() : key, value); + } + return result; + } + tryReadBody(length) { + if (this._totalLength < length) { + return void 0; + } + return this._read(length); + } + get numberOfBytes() { + return this._totalLength; + } + _read(byteCount) { + if (byteCount === 0) { + return this.emptyBuffer(); + } + if (byteCount > this._totalLength) { + throw new Error(`Cannot read so many bytes!`); + } + if (this._chunks[0].byteLength === byteCount) { + const chunk = this._chunks[0]; + this._chunks.shift(); + this._totalLength -= byteCount; + return this.asNative(chunk); + } + if (this._chunks[0].byteLength > byteCount) { + const chunk = this._chunks[0]; + const result2 = this.asNative(chunk, byteCount); + this._chunks[0] = chunk.slice(byteCount); + this._totalLength -= byteCount; + return result2; + } + const result = this.allocNative(byteCount); + let resultOffset = 0; + let chunkIndex = 0; + while (byteCount > 0) { + const chunk = this._chunks[chunkIndex]; + if (chunk.byteLength > byteCount) { + const chunkPart = chunk.slice(0, byteCount); + result.set(chunkPart, resultOffset); + resultOffset += byteCount; + this._chunks[chunkIndex] = chunk.slice(byteCount); + this._totalLength -= byteCount; + byteCount -= byteCount; + } else { + result.set(chunk, resultOffset); + resultOffset += chunk.byteLength; + this._chunks.shift(); + this._totalLength -= chunk.byteLength; + byteCount -= chunk.byteLength; + } + } + return result; + } + }; + exports2.AbstractMessageBuffer = AbstractMessageBuffer; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/connection.js +var require_connection = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/connection.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createMessageConnection = exports2.ConnectionOptions = exports2.MessageStrategy = exports2.CancellationStrategy = exports2.CancellationSenderStrategy = exports2.CancellationReceiverStrategy = exports2.RequestCancellationReceiverStrategy = exports2.IdCancellationReceiverStrategy = exports2.ConnectionStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.TraceValues = exports2.Trace = exports2.NullLogger = exports2.ProgressType = exports2.ProgressToken = void 0; + var ral_1 = require_ral(); + var Is = require_is2(); + var messages_1 = require_messages(); + var linkedMap_1 = require_linkedMap(); + var events_1 = require_events(); + var cancellation_1 = require_cancellation(); + var CancelNotification; + (function(CancelNotification2) { + CancelNotification2.type = new messages_1.NotificationType("$/cancelRequest"); + })(CancelNotification || (CancelNotification = {})); + var ProgressToken; + (function(ProgressToken2) { + function is(value) { + return typeof value === "string" || typeof value === "number"; + } + ProgressToken2.is = is; + })(ProgressToken || (exports2.ProgressToken = ProgressToken = {})); + var ProgressNotification; + (function(ProgressNotification2) { + ProgressNotification2.type = new messages_1.NotificationType("$/progress"); + })(ProgressNotification || (ProgressNotification = {})); + var ProgressType = class { + constructor() { + } + }; + exports2.ProgressType = ProgressType; + var StarRequestHandler; + (function(StarRequestHandler2) { + function is(value) { + return Is.func(value); + } + StarRequestHandler2.is = is; + })(StarRequestHandler || (StarRequestHandler = {})); + exports2.NullLogger = Object.freeze({ + error: () => { + }, + warn: () => { + }, + info: () => { + }, + log: () => { + } + }); + var Trace; + (function(Trace2) { + Trace2[Trace2["Off"] = 0] = "Off"; + Trace2[Trace2["Messages"] = 1] = "Messages"; + Trace2[Trace2["Compact"] = 2] = "Compact"; + Trace2[Trace2["Verbose"] = 3] = "Verbose"; + })(Trace || (exports2.Trace = Trace = {})); + var TraceValues; + (function(TraceValues2) { + TraceValues2.Off = "off"; + TraceValues2.Messages = "messages"; + TraceValues2.Compact = "compact"; + TraceValues2.Verbose = "verbose"; + })(TraceValues || (exports2.TraceValues = TraceValues = {})); + (function(Trace2) { + function fromString(value) { + if (!Is.string(value)) { + return Trace2.Off; + } + value = value.toLowerCase(); + switch (value) { + case "off": + return Trace2.Off; + case "messages": + return Trace2.Messages; + case "compact": + return Trace2.Compact; + case "verbose": + return Trace2.Verbose; + default: + return Trace2.Off; + } + } + Trace2.fromString = fromString; + function toString(value) { + switch (value) { + case Trace2.Off: + return "off"; + case Trace2.Messages: + return "messages"; + case Trace2.Compact: + return "compact"; + case Trace2.Verbose: + return "verbose"; + default: + return "off"; + } + } + Trace2.toString = toString; + })(Trace || (exports2.Trace = Trace = {})); + var TraceFormat; + (function(TraceFormat2) { + TraceFormat2["Text"] = "text"; + TraceFormat2["JSON"] = "json"; + })(TraceFormat || (exports2.TraceFormat = TraceFormat = {})); + (function(TraceFormat2) { + function fromString(value) { + if (!Is.string(value)) { + return TraceFormat2.Text; + } + value = value.toLowerCase(); + if (value === "json") { + return TraceFormat2.JSON; + } else { + return TraceFormat2.Text; + } + } + TraceFormat2.fromString = fromString; + })(TraceFormat || (exports2.TraceFormat = TraceFormat = {})); + var SetTraceNotification; + (function(SetTraceNotification2) { + SetTraceNotification2.type = new messages_1.NotificationType("$/setTrace"); + })(SetTraceNotification || (exports2.SetTraceNotification = SetTraceNotification = {})); + var LogTraceNotification; + (function(LogTraceNotification2) { + LogTraceNotification2.type = new messages_1.NotificationType("$/logTrace"); + })(LogTraceNotification || (exports2.LogTraceNotification = LogTraceNotification = {})); + var ConnectionErrors; + (function(ConnectionErrors2) { + ConnectionErrors2[ConnectionErrors2["Closed"] = 1] = "Closed"; + ConnectionErrors2[ConnectionErrors2["Disposed"] = 2] = "Disposed"; + ConnectionErrors2[ConnectionErrors2["AlreadyListening"] = 3] = "AlreadyListening"; + })(ConnectionErrors || (exports2.ConnectionErrors = ConnectionErrors = {})); + var ConnectionError = class _ConnectionError extends Error { + constructor(code, message) { + super(message); + this.code = code; + Object.setPrototypeOf(this, _ConnectionError.prototype); + } + }; + exports2.ConnectionError = ConnectionError; + var ConnectionStrategy; + (function(ConnectionStrategy2) { + function is(value) { + const candidate = value; + return candidate && Is.func(candidate.cancelUndispatched); + } + ConnectionStrategy2.is = is; + })(ConnectionStrategy || (exports2.ConnectionStrategy = ConnectionStrategy = {})); + var IdCancellationReceiverStrategy; + (function(IdCancellationReceiverStrategy2) { + function is(value) { + const candidate = value; + return candidate && (candidate.kind === void 0 || candidate.kind === "id") && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is.func(candidate.dispose)); + } + IdCancellationReceiverStrategy2.is = is; + })(IdCancellationReceiverStrategy || (exports2.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {})); + var RequestCancellationReceiverStrategy; + (function(RequestCancellationReceiverStrategy2) { + function is(value) { + const candidate = value; + return candidate && candidate.kind === "request" && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is.func(candidate.dispose)); + } + RequestCancellationReceiverStrategy2.is = is; + })(RequestCancellationReceiverStrategy || (exports2.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {})); + var CancellationReceiverStrategy; + (function(CancellationReceiverStrategy2) { + CancellationReceiverStrategy2.Message = Object.freeze({ + createCancellationTokenSource(_) { + return new cancellation_1.CancellationTokenSource(); + } + }); + function is(value) { + return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value); + } + CancellationReceiverStrategy2.is = is; + })(CancellationReceiverStrategy || (exports2.CancellationReceiverStrategy = CancellationReceiverStrategy = {})); + var CancellationSenderStrategy; + (function(CancellationSenderStrategy2) { + CancellationSenderStrategy2.Message = Object.freeze({ + sendCancellation(conn, id) { + return conn.sendNotification(CancelNotification.type, { id }); + }, + cleanup(_) { + } + }); + function is(value) { + const candidate = value; + return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup); + } + CancellationSenderStrategy2.is = is; + })(CancellationSenderStrategy || (exports2.CancellationSenderStrategy = CancellationSenderStrategy = {})); + var CancellationStrategy; + (function(CancellationStrategy2) { + CancellationStrategy2.Message = Object.freeze({ + receiver: CancellationReceiverStrategy.Message, + sender: CancellationSenderStrategy.Message + }); + function is(value) { + const candidate = value; + return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender); + } + CancellationStrategy2.is = is; + })(CancellationStrategy || (exports2.CancellationStrategy = CancellationStrategy = {})); + var MessageStrategy; + (function(MessageStrategy2) { + function is(value) { + const candidate = value; + return candidate && Is.func(candidate.handleMessage); + } + MessageStrategy2.is = is; + })(MessageStrategy || (exports2.MessageStrategy = MessageStrategy = {})); + var ConnectionOptions; + (function(ConnectionOptions2) { + function is(value) { + const candidate = value; + return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy)); + } + ConnectionOptions2.is = is; + })(ConnectionOptions || (exports2.ConnectionOptions = ConnectionOptions = {})); + var ConnectionState; + (function(ConnectionState2) { + ConnectionState2[ConnectionState2["New"] = 1] = "New"; + ConnectionState2[ConnectionState2["Listening"] = 2] = "Listening"; + ConnectionState2[ConnectionState2["Closed"] = 3] = "Closed"; + ConnectionState2[ConnectionState2["Disposed"] = 4] = "Disposed"; + })(ConnectionState || (ConnectionState = {})); + function createMessageConnection(messageReader, messageWriter, _logger, options) { + const logger = _logger !== void 0 ? _logger : exports2.NullLogger; + let sequenceNumber = 0; + let notificationSequenceNumber = 0; + let unknownResponseSequenceNumber = 0; + const version = "2.0"; + let starRequestHandler = void 0; + const requestHandlers = /* @__PURE__ */ new Map(); + let starNotificationHandler = void 0; + const notificationHandlers = /* @__PURE__ */ new Map(); + const progressHandlers = /* @__PURE__ */ new Map(); + let timer; + let messageQueue = new linkedMap_1.LinkedMap(); + let responsePromises = /* @__PURE__ */ new Map(); + let knownCanceledRequests = /* @__PURE__ */ new Set(); + let requestTokens = /* @__PURE__ */ new Map(); + let trace = Trace.Off; + let traceFormat = TraceFormat.Text; + let tracer; + let state = ConnectionState.New; + const errorEmitter = new events_1.Emitter(); + const closeEmitter = new events_1.Emitter(); + const unhandledNotificationEmitter = new events_1.Emitter(); + const unhandledProgressEmitter = new events_1.Emitter(); + const disposeEmitter = new events_1.Emitter(); + const cancellationStrategy = options && options.cancellationStrategy ? options.cancellationStrategy : CancellationStrategy.Message; + function createRequestQueueKey(id) { + if (id === null) { + throw new Error(`Can't send requests with id null since the response can't be correlated.`); + } + return "req-" + id.toString(); + } + function createResponseQueueKey(id) { + if (id === null) { + return "res-unknown-" + (++unknownResponseSequenceNumber).toString(); + } else { + return "res-" + id.toString(); + } + } + function createNotificationQueueKey() { + return "not-" + (++notificationSequenceNumber).toString(); + } + function addMessageToQueue(queue2, message) { + if (messages_1.Message.isRequest(message)) { + queue2.set(createRequestQueueKey(message.id), message); + } else if (messages_1.Message.isResponse(message)) { + queue2.set(createResponseQueueKey(message.id), message); + } else { + queue2.set(createNotificationQueueKey(), message); + } + } + function cancelUndispatched(_message) { + return void 0; + } + function isListening() { + return state === ConnectionState.Listening; + } + function isClosed() { + return state === ConnectionState.Closed; + } + function isDisposed() { + return state === ConnectionState.Disposed; + } + function closeHandler() { + if (state === ConnectionState.New || state === ConnectionState.Listening) { + state = ConnectionState.Closed; + closeEmitter.fire(void 0); + } + } + function readErrorHandler(error) { + errorEmitter.fire([error, void 0, void 0]); + } + function writeErrorHandler(data) { + errorEmitter.fire(data); + } + messageReader.onClose(closeHandler); + messageReader.onError(readErrorHandler); + messageWriter.onClose(closeHandler); + messageWriter.onError(writeErrorHandler); + function triggerMessageQueue() { + if (timer || messageQueue.size === 0) { + return; + } + timer = (0, ral_1.default)().timer.setImmediate(() => { + timer = void 0; + processMessageQueue(); + }); + } + function handleMessage(message) { + if (messages_1.Message.isRequest(message)) { + handleRequest(message); + } else if (messages_1.Message.isNotification(message)) { + handleNotification(message); + } else if (messages_1.Message.isResponse(message)) { + handleResponse(message); + } else { + handleInvalidMessage(message); + } + } + function processMessageQueue() { + if (messageQueue.size === 0) { + return; + } + const message = messageQueue.shift(); + try { + const messageStrategy = options?.messageStrategy; + if (MessageStrategy.is(messageStrategy)) { + messageStrategy.handleMessage(message, handleMessage); + } else { + handleMessage(message); + } + } finally { + triggerMessageQueue(); + } + } + const callback = (message) => { + try { + if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) { + const cancelId = message.params.id; + const key = createRequestQueueKey(cancelId); + const toCancel = messageQueue.get(key); + if (messages_1.Message.isRequest(toCancel)) { + const strategy = options?.connectionStrategy; + const response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel); + if (response && (response.error !== void 0 || response.result !== void 0)) { + messageQueue.delete(key); + requestTokens.delete(cancelId); + response.id = toCancel.id; + traceSendingResponse(response, message.method, Date.now()); + messageWriter.write(response).catch(() => logger.error(`Sending response for canceled message failed.`)); + return; + } + } + const cancellationToken = requestTokens.get(cancelId); + if (cancellationToken !== void 0) { + cancellationToken.cancel(); + traceReceivedNotification(message); + return; + } else { + knownCanceledRequests.add(cancelId); + } + } + addMessageToQueue(messageQueue, message); + } finally { + triggerMessageQueue(); + } + }; + function handleRequest(requestMessage) { + if (isDisposed()) { + return; + } + function reply(resultOrError, method, startTime2) { + const message = { + jsonrpc: version, + id: requestMessage.id + }; + if (resultOrError instanceof messages_1.ResponseError) { + message.error = resultOrError.toJson(); + } else { + message.result = resultOrError === void 0 ? null : resultOrError; + } + traceSendingResponse(message, method, startTime2); + messageWriter.write(message).catch(() => logger.error(`Sending response failed.`)); + } + function replyError(error, method, startTime2) { + const message = { + jsonrpc: version, + id: requestMessage.id, + error: error.toJson() + }; + traceSendingResponse(message, method, startTime2); + messageWriter.write(message).catch(() => logger.error(`Sending response failed.`)); + } + function replySuccess(result, method, startTime2) { + if (result === void 0) { + result = null; + } + const message = { + jsonrpc: version, + id: requestMessage.id, + result + }; + traceSendingResponse(message, method, startTime2); + messageWriter.write(message).catch(() => logger.error(`Sending response failed.`)); + } + traceReceivedRequest(requestMessage); + const element = requestHandlers.get(requestMessage.method); + let type; + let requestHandler; + if (element) { + type = element.type; + requestHandler = element.handler; + } + const startTime = Date.now(); + if (requestHandler || starRequestHandler) { + const tokenKey = requestMessage.id ?? String(Date.now()); + const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver) ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey) : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage); + if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) { + cancellationSource.cancel(); + } + if (requestMessage.id !== null) { + requestTokens.set(tokenKey, cancellationSource); + } + try { + let handlerResult; + if (requestHandler) { + if (requestMessage.params === void 0) { + if (type !== void 0 && type.numberOfParams !== 0) { + replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime); + return; + } + handlerResult = requestHandler(cancellationSource.token); + } else if (Array.isArray(requestMessage.params)) { + if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byName) { + replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime); + return; + } + handlerResult = requestHandler(...requestMessage.params, cancellationSource.token); + } else { + if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) { + replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime); + return; + } + handlerResult = requestHandler(requestMessage.params, cancellationSource.token); + } + } else if (starRequestHandler) { + handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token); + } + const promise = handlerResult; + if (!handlerResult) { + requestTokens.delete(tokenKey); + replySuccess(handlerResult, requestMessage.method, startTime); + } else if (promise.then) { + promise.then((resultOrError) => { + requestTokens.delete(tokenKey); + reply(resultOrError, requestMessage.method, startTime); + }, (error) => { + requestTokens.delete(tokenKey); + if (error instanceof messages_1.ResponseError) { + replyError(error, requestMessage.method, startTime); + } else if (error && Is.string(error.message)) { + replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime); + } else { + replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime); + } + }); + } else { + requestTokens.delete(tokenKey); + reply(handlerResult, requestMessage.method, startTime); + } + } catch (error) { + requestTokens.delete(tokenKey); + if (error instanceof messages_1.ResponseError) { + reply(error, requestMessage.method, startTime); + } else if (error && Is.string(error.message)) { + replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime); + } else { + replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime); + } + } + } else { + replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime); + } + } + function handleResponse(responseMessage) { + if (isDisposed()) { + return; + } + if (responseMessage.id === null) { + if (responseMessage.error) { + logger.error(`Received response message without id: Error is: +${JSON.stringify(responseMessage.error, void 0, 4)}`); + } else { + logger.error(`Received response message without id. No further error information provided.`); + } + } else { + const key = responseMessage.id; + const responsePromise = responsePromises.get(key); + traceReceivedResponse(responseMessage, responsePromise); + if (responsePromise !== void 0) { + responsePromises.delete(key); + try { + if (responseMessage.error) { + const error = responseMessage.error; + responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data)); + } else if (responseMessage.result !== void 0) { + responsePromise.resolve(responseMessage.result); + } else { + throw new Error("Should never happen."); + } + } catch (error) { + if (error.message) { + logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`); + } else { + logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`); + } + } + } + } + } + function handleNotification(message) { + if (isDisposed()) { + return; + } + let type = void 0; + let notificationHandler; + if (message.method === CancelNotification.type.method) { + const cancelId = message.params.id; + knownCanceledRequests.delete(cancelId); + traceReceivedNotification(message); + return; + } else { + const element = notificationHandlers.get(message.method); + if (element) { + notificationHandler = element.handler; + type = element.type; + } + } + if (notificationHandler || starNotificationHandler) { + try { + traceReceivedNotification(message); + if (notificationHandler) { + if (message.params === void 0) { + if (type !== void 0) { + if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) { + logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`); + } + } + notificationHandler(); + } else if (Array.isArray(message.params)) { + const params = message.params; + if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) { + notificationHandler({ token: params[0], value: params[1] }); + } else { + if (type !== void 0) { + if (type.parameterStructures === messages_1.ParameterStructures.byName) { + logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`); + } + if (type.numberOfParams !== message.params.length) { + logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`); + } + } + notificationHandler(...params); + } + } else { + if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) { + logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`); + } + notificationHandler(message.params); + } + } else if (starNotificationHandler) { + starNotificationHandler(message.method, message.params); + } + } catch (error) { + if (error.message) { + logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`); + } else { + logger.error(`Notification handler '${message.method}' failed unexpectedly.`); + } + } + } else { + unhandledNotificationEmitter.fire(message); + } + } + function handleInvalidMessage(message) { + if (!message) { + logger.error("Received empty message."); + return; + } + logger.error(`Received message which is neither a response nor a notification message: +${JSON.stringify(message, null, 4)}`); + const responseMessage = message; + if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) { + const key = responseMessage.id; + const responseHandler = responsePromises.get(key); + if (responseHandler) { + responseHandler.reject(new Error("The received response has neither a result nor an error property.")); + } + } + } + function stringifyTrace(params) { + if (params === void 0 || params === null) { + return void 0; + } + switch (trace) { + case Trace.Verbose: + return JSON.stringify(params, null, 4); + case Trace.Compact: + return JSON.stringify(params); + default: + return void 0; + } + } + function traceSendingRequest(message) { + if (trace === Trace.Off || !tracer) { + return; + } + if (traceFormat === TraceFormat.Text) { + let data = void 0; + if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) { + data = `Params: ${stringifyTrace(message.params)} + +`; + } + tracer.log(`Sending request '${message.method} - (${message.id})'.`, data); + } else { + logLSPMessage("send-request", message); + } + } + function traceSendingNotification(message) { + if (trace === Trace.Off || !tracer) { + return; + } + if (traceFormat === TraceFormat.Text) { + let data = void 0; + if (trace === Trace.Verbose || trace === Trace.Compact) { + if (message.params) { + data = `Params: ${stringifyTrace(message.params)} + +`; + } else { + data = "No parameters provided.\n\n"; + } + } + tracer.log(`Sending notification '${message.method}'.`, data); + } else { + logLSPMessage("send-notification", message); + } + } + function traceSendingResponse(message, method, startTime) { + if (trace === Trace.Off || !tracer) { + return; + } + if (traceFormat === TraceFormat.Text) { + let data = void 0; + if (trace === Trace.Verbose || trace === Trace.Compact) { + if (message.error && message.error.data) { + data = `Error data: ${stringifyTrace(message.error.data)} + +`; + } else { + if (message.result) { + data = `Result: ${stringifyTrace(message.result)} + +`; + } else if (message.error === void 0) { + data = "No result returned.\n\n"; + } + } + } + tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data); + } else { + logLSPMessage("send-response", message); + } + } + function traceReceivedRequest(message) { + if (trace === Trace.Off || !tracer) { + return; + } + if (traceFormat === TraceFormat.Text) { + let data = void 0; + if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) { + data = `Params: ${stringifyTrace(message.params)} + +`; + } + tracer.log(`Received request '${message.method} - (${message.id})'.`, data); + } else { + logLSPMessage("receive-request", message); + } + } + function traceReceivedNotification(message) { + if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) { + return; + } + if (traceFormat === TraceFormat.Text) { + let data = void 0; + if (trace === Trace.Verbose || trace === Trace.Compact) { + if (message.params) { + data = `Params: ${stringifyTrace(message.params)} + +`; + } else { + data = "No parameters provided.\n\n"; + } + } + tracer.log(`Received notification '${message.method}'.`, data); + } else { + logLSPMessage("receive-notification", message); + } + } + function traceReceivedResponse(message, responsePromise) { + if (trace === Trace.Off || !tracer) { + return; + } + if (traceFormat === TraceFormat.Text) { + let data = void 0; + if (trace === Trace.Verbose || trace === Trace.Compact) { + if (message.error && message.error.data) { + data = `Error data: ${stringifyTrace(message.error.data)} + +`; + } else { + if (message.result) { + data = `Result: ${stringifyTrace(message.result)} + +`; + } else if (message.error === void 0) { + data = "No result returned.\n\n"; + } + } + } + if (responsePromise) { + const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : ""; + tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data); + } else { + tracer.log(`Received response ${message.id} without active response promise.`, data); + } + } else { + logLSPMessage("receive-response", message); + } + } + function logLSPMessage(type, message) { + if (!tracer || trace === Trace.Off) { + return; + } + const lspMessage = { + isLSPMessage: true, + type, + message, + timestamp: Date.now() + }; + tracer.log(lspMessage); + } + function throwIfClosedOrDisposed() { + if (isClosed()) { + throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed."); + } + if (isDisposed()) { + throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed."); + } + } + function throwIfListening() { + if (isListening()) { + throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening"); + } + } + function throwIfNotListening() { + if (!isListening()) { + throw new Error("Call listen() first."); + } + } + function undefinedToNull(param) { + if (param === void 0) { + return null; + } else { + return param; + } + } + function nullToUndefined(param) { + if (param === null) { + return void 0; + } else { + return param; + } + } + function isNamedParam(param) { + return param !== void 0 && param !== null && !Array.isArray(param) && typeof param === "object"; + } + function computeSingleParam(parameterStructures, param) { + switch (parameterStructures) { + case messages_1.ParameterStructures.auto: + if (isNamedParam(param)) { + return nullToUndefined(param); + } else { + return [undefinedToNull(param)]; + } + case messages_1.ParameterStructures.byName: + if (!isNamedParam(param)) { + throw new Error(`Received parameters by name but param is not an object literal.`); + } + return nullToUndefined(param); + case messages_1.ParameterStructures.byPosition: + return [undefinedToNull(param)]; + default: + throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`); + } + } + function computeMessageParams(type, params) { + let result; + const numberOfParams = type.numberOfParams; + switch (numberOfParams) { + case 0: + result = void 0; + break; + case 1: + result = computeSingleParam(type.parameterStructures, params[0]); + break; + default: + result = []; + for (let i = 0; i < params.length && i < numberOfParams; i++) { + result.push(undefinedToNull(params[i])); + } + if (params.length < numberOfParams) { + for (let i = params.length; i < numberOfParams; i++) { + result.push(null); + } + } + break; + } + return result; + } + const connection = { + sendNotification: (type, ...args) => { + throwIfClosedOrDisposed(); + let method; + let messageParams; + if (Is.string(type)) { + method = type; + const first = args[0]; + let paramStart = 0; + let parameterStructures = messages_1.ParameterStructures.auto; + if (messages_1.ParameterStructures.is(first)) { + paramStart = 1; + parameterStructures = first; + } + let paramEnd = args.length; + const numberOfParams = paramEnd - paramStart; + switch (numberOfParams) { + case 0: + messageParams = void 0; + break; + case 1: + messageParams = computeSingleParam(parameterStructures, args[paramStart]); + break; + default: + if (parameterStructures === messages_1.ParameterStructures.byName) { + throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`); + } + messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value)); + break; + } + } else { + const params = args; + method = type.method; + messageParams = computeMessageParams(type, params); + } + const notificationMessage = { + jsonrpc: version, + method, + params: messageParams + }; + traceSendingNotification(notificationMessage); + return messageWriter.write(notificationMessage).catch((error) => { + logger.error(`Sending notification failed.`); + throw error; + }); + }, + onNotification: (type, handler) => { + throwIfClosedOrDisposed(); + let method; + if (Is.func(type)) { + starNotificationHandler = type; + } else if (handler) { + if (Is.string(type)) { + method = type; + notificationHandlers.set(type, { type: void 0, handler }); + } else { + method = type.method; + notificationHandlers.set(type.method, { type, handler }); + } + } + return { + dispose: () => { + if (method !== void 0) { + notificationHandlers.delete(method); + } else { + starNotificationHandler = void 0; + } + } + }; + }, + onProgress: (_type, token, handler) => { + if (progressHandlers.has(token)) { + throw new Error(`Progress handler for token ${token} already registered`); + } + progressHandlers.set(token, handler); + return { + dispose: () => { + progressHandlers.delete(token); + } + }; + }, + sendProgress: (_type, token, value) => { + return connection.sendNotification(ProgressNotification.type, { token, value }); + }, + onUnhandledProgress: unhandledProgressEmitter.event, + sendRequest: (type, ...args) => { + throwIfClosedOrDisposed(); + throwIfNotListening(); + let method; + let messageParams; + let token = void 0; + if (Is.string(type)) { + method = type; + const first = args[0]; + const last = args[args.length - 1]; + let paramStart = 0; + let parameterStructures = messages_1.ParameterStructures.auto; + if (messages_1.ParameterStructures.is(first)) { + paramStart = 1; + parameterStructures = first; + } + let paramEnd = args.length; + if (cancellation_1.CancellationToken.is(last)) { + paramEnd = paramEnd - 1; + token = last; + } + const numberOfParams = paramEnd - paramStart; + switch (numberOfParams) { + case 0: + messageParams = void 0; + break; + case 1: + messageParams = computeSingleParam(parameterStructures, args[paramStart]); + break; + default: + if (parameterStructures === messages_1.ParameterStructures.byName) { + throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`); + } + messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value)); + break; + } + } else { + const params = args; + method = type.method; + messageParams = computeMessageParams(type, params); + const numberOfParams = type.numberOfParams; + token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : void 0; + } + const id = sequenceNumber++; + let disposable; + if (token) { + disposable = token.onCancellationRequested(() => { + const p = cancellationStrategy.sender.sendCancellation(connection, id); + if (p === void 0) { + logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`); + return Promise.resolve(); + } else { + return p.catch(() => { + logger.log(`Sending cancellation messages for id ${id} failed`); + }); + } + }); + } + const requestMessage = { + jsonrpc: version, + id, + method, + params: messageParams + }; + traceSendingRequest(requestMessage); + if (typeof cancellationStrategy.sender.enableCancellation === "function") { + cancellationStrategy.sender.enableCancellation(requestMessage); + } + return new Promise(async (resolve, reject) => { + const resolveWithCleanup = (r) => { + resolve(r); + cancellationStrategy.sender.cleanup(id); + disposable?.dispose(); + }; + const rejectWithCleanup = (r) => { + reject(r); + cancellationStrategy.sender.cleanup(id); + disposable?.dispose(); + }; + const responsePromise = { method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup }; + try { + await messageWriter.write(requestMessage); + responsePromises.set(id, responsePromise); + } catch (error) { + logger.error(`Sending request failed.`); + responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : "Unknown reason")); + throw error; + } + }); + }, + onRequest: (type, handler) => { + throwIfClosedOrDisposed(); + let method = null; + if (StarRequestHandler.is(type)) { + method = void 0; + starRequestHandler = type; + } else if (Is.string(type)) { + method = null; + if (handler !== void 0) { + method = type; + requestHandlers.set(type, { handler, type: void 0 }); + } + } else { + if (handler !== void 0) { + method = type.method; + requestHandlers.set(type.method, { type, handler }); + } + } + return { + dispose: () => { + if (method === null) { + return; + } + if (method !== void 0) { + requestHandlers.delete(method); + } else { + starRequestHandler = void 0; + } + } + }; + }, + hasPendingResponse: () => { + return responsePromises.size > 0; + }, + trace: async (_value, _tracer, sendNotificationOrTraceOptions) => { + let _sendNotification = false; + let _traceFormat = TraceFormat.Text; + if (sendNotificationOrTraceOptions !== void 0) { + if (Is.boolean(sendNotificationOrTraceOptions)) { + _sendNotification = sendNotificationOrTraceOptions; + } else { + _sendNotification = sendNotificationOrTraceOptions.sendNotification || false; + _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text; + } + } + trace = _value; + traceFormat = _traceFormat; + if (trace === Trace.Off) { + tracer = void 0; + } else { + tracer = _tracer; + } + if (_sendNotification && !isClosed() && !isDisposed()) { + await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) }); + } + }, + onError: errorEmitter.event, + onClose: closeEmitter.event, + onUnhandledNotification: unhandledNotificationEmitter.event, + onDispose: disposeEmitter.event, + end: () => { + messageWriter.end(); + }, + dispose: () => { + if (isDisposed()) { + return; + } + state = ConnectionState.Disposed; + disposeEmitter.fire(void 0); + const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, "Pending response rejected since connection got disposed"); + for (const promise of responsePromises.values()) { + promise.reject(error); + } + responsePromises = /* @__PURE__ */ new Map(); + requestTokens = /* @__PURE__ */ new Map(); + knownCanceledRequests = /* @__PURE__ */ new Set(); + messageQueue = new linkedMap_1.LinkedMap(); + if (Is.func(messageWriter.dispose)) { + messageWriter.dispose(); + } + if (Is.func(messageReader.dispose)) { + messageReader.dispose(); + } + }, + listen: () => { + throwIfClosedOrDisposed(); + throwIfListening(); + state = ConnectionState.Listening; + messageReader.listen(callback); + }, + inspect: () => { + (0, ral_1.default)().console.log("inspect"); + } + }; + connection.onNotification(LogTraceNotification.type, (params) => { + if (trace === Trace.Off || !tracer) { + return; + } + const verbose = trace === Trace.Verbose || trace === Trace.Compact; + tracer.log(params.message, verbose ? params.verbose : void 0); + }); + connection.onNotification(ProgressNotification.type, (params) => { + const handler = progressHandlers.get(params.token); + if (handler) { + handler(params.value); + } else { + unhandledProgressEmitter.fire(params); + } + }); + return connection; + } + exports2.createMessageConnection = createMessageConnection; + } +}); + +// node_modules/vscode-jsonrpc/lib/common/api.js +var require_api = __commonJS({ + "node_modules/vscode-jsonrpc/lib/common/api.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ProgressType = exports2.ProgressToken = exports2.createMessageConnection = exports2.NullLogger = exports2.ConnectionOptions = exports2.ConnectionStrategy = exports2.AbstractMessageBuffer = exports2.WriteableStreamMessageWriter = exports2.AbstractMessageWriter = exports2.MessageWriter = exports2.ReadableStreamMessageReader = exports2.AbstractMessageReader = exports2.MessageReader = exports2.SharedArrayReceiverStrategy = exports2.SharedArraySenderStrategy = exports2.CancellationToken = exports2.CancellationTokenSource = exports2.Emitter = exports2.Event = exports2.Disposable = exports2.LRUCache = exports2.Touch = exports2.LinkedMap = exports2.ParameterStructures = exports2.NotificationType9 = exports2.NotificationType8 = exports2.NotificationType7 = exports2.NotificationType6 = exports2.NotificationType5 = exports2.NotificationType4 = exports2.NotificationType3 = exports2.NotificationType2 = exports2.NotificationType1 = exports2.NotificationType0 = exports2.NotificationType = exports2.ErrorCodes = exports2.ResponseError = exports2.RequestType9 = exports2.RequestType8 = exports2.RequestType7 = exports2.RequestType6 = exports2.RequestType5 = exports2.RequestType4 = exports2.RequestType3 = exports2.RequestType2 = exports2.RequestType1 = exports2.RequestType0 = exports2.RequestType = exports2.Message = exports2.RAL = void 0; + exports2.MessageStrategy = exports2.CancellationStrategy = exports2.CancellationSenderStrategy = exports2.CancellationReceiverStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.TraceValues = exports2.Trace = void 0; + var messages_1 = require_messages(); + Object.defineProperty(exports2, "Message", { enumerable: true, get: function() { + return messages_1.Message; + } }); + Object.defineProperty(exports2, "RequestType", { enumerable: true, get: function() { + return messages_1.RequestType; + } }); + Object.defineProperty(exports2, "RequestType0", { enumerable: true, get: function() { + return messages_1.RequestType0; + } }); + Object.defineProperty(exports2, "RequestType1", { enumerable: true, get: function() { + return messages_1.RequestType1; + } }); + Object.defineProperty(exports2, "RequestType2", { enumerable: true, get: function() { + return messages_1.RequestType2; + } }); + Object.defineProperty(exports2, "RequestType3", { enumerable: true, get: function() { + return messages_1.RequestType3; + } }); + Object.defineProperty(exports2, "RequestType4", { enumerable: true, get: function() { + return messages_1.RequestType4; + } }); + Object.defineProperty(exports2, "RequestType5", { enumerable: true, get: function() { + return messages_1.RequestType5; + } }); + Object.defineProperty(exports2, "RequestType6", { enumerable: true, get: function() { + return messages_1.RequestType6; + } }); + Object.defineProperty(exports2, "RequestType7", { enumerable: true, get: function() { + return messages_1.RequestType7; + } }); + Object.defineProperty(exports2, "RequestType8", { enumerable: true, get: function() { + return messages_1.RequestType8; + } }); + Object.defineProperty(exports2, "RequestType9", { enumerable: true, get: function() { + return messages_1.RequestType9; + } }); + Object.defineProperty(exports2, "ResponseError", { enumerable: true, get: function() { + return messages_1.ResponseError; + } }); + Object.defineProperty(exports2, "ErrorCodes", { enumerable: true, get: function() { + return messages_1.ErrorCodes; + } }); + Object.defineProperty(exports2, "NotificationType", { enumerable: true, get: function() { + return messages_1.NotificationType; + } }); + Object.defineProperty(exports2, "NotificationType0", { enumerable: true, get: function() { + return messages_1.NotificationType0; + } }); + Object.defineProperty(exports2, "NotificationType1", { enumerable: true, get: function() { + return messages_1.NotificationType1; + } }); + Object.defineProperty(exports2, "NotificationType2", { enumerable: true, get: function() { + return messages_1.NotificationType2; + } }); + Object.defineProperty(exports2, "NotificationType3", { enumerable: true, get: function() { + return messages_1.NotificationType3; + } }); + Object.defineProperty(exports2, "NotificationType4", { enumerable: true, get: function() { + return messages_1.NotificationType4; + } }); + Object.defineProperty(exports2, "NotificationType5", { enumerable: true, get: function() { + return messages_1.NotificationType5; + } }); + Object.defineProperty(exports2, "NotificationType6", { enumerable: true, get: function() { + return messages_1.NotificationType6; + } }); + Object.defineProperty(exports2, "NotificationType7", { enumerable: true, get: function() { + return messages_1.NotificationType7; + } }); + Object.defineProperty(exports2, "NotificationType8", { enumerable: true, get: function() { + return messages_1.NotificationType8; + } }); + Object.defineProperty(exports2, "NotificationType9", { enumerable: true, get: function() { + return messages_1.NotificationType9; + } }); + Object.defineProperty(exports2, "ParameterStructures", { enumerable: true, get: function() { + return messages_1.ParameterStructures; + } }); + var linkedMap_1 = require_linkedMap(); + Object.defineProperty(exports2, "LinkedMap", { enumerable: true, get: function() { + return linkedMap_1.LinkedMap; + } }); + Object.defineProperty(exports2, "LRUCache", { enumerable: true, get: function() { + return linkedMap_1.LRUCache; + } }); + Object.defineProperty(exports2, "Touch", { enumerable: true, get: function() { + return linkedMap_1.Touch; + } }); + var disposable_1 = require_disposable(); + Object.defineProperty(exports2, "Disposable", { enumerable: true, get: function() { + return disposable_1.Disposable; + } }); + var events_1 = require_events(); + Object.defineProperty(exports2, "Event", { enumerable: true, get: function() { + return events_1.Event; + } }); + Object.defineProperty(exports2, "Emitter", { enumerable: true, get: function() { + return events_1.Emitter; + } }); + var cancellation_1 = require_cancellation(); + Object.defineProperty(exports2, "CancellationTokenSource", { enumerable: true, get: function() { + return cancellation_1.CancellationTokenSource; + } }); + Object.defineProperty(exports2, "CancellationToken", { enumerable: true, get: function() { + return cancellation_1.CancellationToken; + } }); + var sharedArrayCancellation_1 = require_sharedArrayCancellation(); + Object.defineProperty(exports2, "SharedArraySenderStrategy", { enumerable: true, get: function() { + return sharedArrayCancellation_1.SharedArraySenderStrategy; + } }); + Object.defineProperty(exports2, "SharedArrayReceiverStrategy", { enumerable: true, get: function() { + return sharedArrayCancellation_1.SharedArrayReceiverStrategy; + } }); + var messageReader_1 = require_messageReader(); + Object.defineProperty(exports2, "MessageReader", { enumerable: true, get: function() { + return messageReader_1.MessageReader; + } }); + Object.defineProperty(exports2, "AbstractMessageReader", { enumerable: true, get: function() { + return messageReader_1.AbstractMessageReader; + } }); + Object.defineProperty(exports2, "ReadableStreamMessageReader", { enumerable: true, get: function() { + return messageReader_1.ReadableStreamMessageReader; + } }); + var messageWriter_1 = require_messageWriter(); + Object.defineProperty(exports2, "MessageWriter", { enumerable: true, get: function() { + return messageWriter_1.MessageWriter; + } }); + Object.defineProperty(exports2, "AbstractMessageWriter", { enumerable: true, get: function() { + return messageWriter_1.AbstractMessageWriter; + } }); + Object.defineProperty(exports2, "WriteableStreamMessageWriter", { enumerable: true, get: function() { + return messageWriter_1.WriteableStreamMessageWriter; + } }); + var messageBuffer_1 = require_messageBuffer(); + Object.defineProperty(exports2, "AbstractMessageBuffer", { enumerable: true, get: function() { + return messageBuffer_1.AbstractMessageBuffer; + } }); + var connection_1 = require_connection(); + Object.defineProperty(exports2, "ConnectionStrategy", { enumerable: true, get: function() { + return connection_1.ConnectionStrategy; + } }); + Object.defineProperty(exports2, "ConnectionOptions", { enumerable: true, get: function() { + return connection_1.ConnectionOptions; + } }); + Object.defineProperty(exports2, "NullLogger", { enumerable: true, get: function() { + return connection_1.NullLogger; + } }); + Object.defineProperty(exports2, "createMessageConnection", { enumerable: true, get: function() { + return connection_1.createMessageConnection; + } }); + Object.defineProperty(exports2, "ProgressToken", { enumerable: true, get: function() { + return connection_1.ProgressToken; + } }); + Object.defineProperty(exports2, "ProgressType", { enumerable: true, get: function() { + return connection_1.ProgressType; + } }); + Object.defineProperty(exports2, "Trace", { enumerable: true, get: function() { + return connection_1.Trace; + } }); + Object.defineProperty(exports2, "TraceValues", { enumerable: true, get: function() { + return connection_1.TraceValues; + } }); + Object.defineProperty(exports2, "TraceFormat", { enumerable: true, get: function() { + return connection_1.TraceFormat; + } }); + Object.defineProperty(exports2, "SetTraceNotification", { enumerable: true, get: function() { + return connection_1.SetTraceNotification; + } }); + Object.defineProperty(exports2, "LogTraceNotification", { enumerable: true, get: function() { + return connection_1.LogTraceNotification; + } }); + Object.defineProperty(exports2, "ConnectionErrors", { enumerable: true, get: function() { + return connection_1.ConnectionErrors; + } }); + Object.defineProperty(exports2, "ConnectionError", { enumerable: true, get: function() { + return connection_1.ConnectionError; + } }); + Object.defineProperty(exports2, "CancellationReceiverStrategy", { enumerable: true, get: function() { + return connection_1.CancellationReceiverStrategy; + } }); + Object.defineProperty(exports2, "CancellationSenderStrategy", { enumerable: true, get: function() { + return connection_1.CancellationSenderStrategy; + } }); + Object.defineProperty(exports2, "CancellationStrategy", { enumerable: true, get: function() { + return connection_1.CancellationStrategy; + } }); + Object.defineProperty(exports2, "MessageStrategy", { enumerable: true, get: function() { + return connection_1.MessageStrategy; + } }); + var ral_1 = require_ral(); + exports2.RAL = ral_1.default; + } +}); + +// node_modules/vscode-jsonrpc/lib/node/ril.js +var require_ril = __commonJS({ + "node_modules/vscode-jsonrpc/lib/node/ril.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var util_1 = require("util"); + var api_1 = require_api(); + var MessageBuffer = class _MessageBuffer extends api_1.AbstractMessageBuffer { + constructor(encoding = "utf-8") { + super(encoding); + } + emptyBuffer() { + return _MessageBuffer.emptyBuffer; + } + fromString(value, encoding) { + return Buffer.from(value, encoding); + } + toString(value, encoding) { + if (value instanceof Buffer) { + return value.toString(encoding); + } else { + return new util_1.TextDecoder(encoding).decode(value); + } + } + asNative(buffer, length) { + if (length === void 0) { + return buffer instanceof Buffer ? buffer : Buffer.from(buffer); + } else { + return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length); + } + } + allocNative(length) { + return Buffer.allocUnsafe(length); + } + }; + MessageBuffer.emptyBuffer = Buffer.allocUnsafe(0); + var ReadableStreamWrapper = class { + constructor(stream) { + this.stream = stream; + } + onClose(listener) { + this.stream.on("close", listener); + return api_1.Disposable.create(() => this.stream.off("close", listener)); + } + onError(listener) { + this.stream.on("error", listener); + return api_1.Disposable.create(() => this.stream.off("error", listener)); + } + onEnd(listener) { + this.stream.on("end", listener); + return api_1.Disposable.create(() => this.stream.off("end", listener)); + } + onData(listener) { + this.stream.on("data", listener); + return api_1.Disposable.create(() => this.stream.off("data", listener)); + } + }; + var WritableStreamWrapper = class { + constructor(stream) { + this.stream = stream; + } + onClose(listener) { + this.stream.on("close", listener); + return api_1.Disposable.create(() => this.stream.off("close", listener)); + } + onError(listener) { + this.stream.on("error", listener); + return api_1.Disposable.create(() => this.stream.off("error", listener)); + } + onEnd(listener) { + this.stream.on("end", listener); + return api_1.Disposable.create(() => this.stream.off("end", listener)); + } + write(data, encoding) { + return new Promise((resolve, reject) => { + const callback = (error) => { + if (error === void 0 || error === null) { + resolve(); + } else { + reject(error); + } + }; + if (typeof data === "string") { + this.stream.write(data, encoding, callback); + } else { + this.stream.write(data, callback); + } + }); + } + end() { + this.stream.end(); + } + }; + var _ril = Object.freeze({ + messageBuffer: Object.freeze({ + create: (encoding) => new MessageBuffer(encoding) + }), + applicationJson: Object.freeze({ + encoder: Object.freeze({ + name: "application/json", + encode: (msg, options) => { + try { + return Promise.resolve(Buffer.from(JSON.stringify(msg, void 0, 0), options.charset)); + } catch (err) { + return Promise.reject(err); + } + } + }), + decoder: Object.freeze({ + name: "application/json", + decode: (buffer, options) => { + try { + if (buffer instanceof Buffer) { + return Promise.resolve(JSON.parse(buffer.toString(options.charset))); + } else { + return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer))); + } + } catch (err) { + return Promise.reject(err); + } + } + }) + }), + stream: Object.freeze({ + asReadableStream: (stream) => new ReadableStreamWrapper(stream), + asWritableStream: (stream) => new WritableStreamWrapper(stream) + }), + console, + timer: Object.freeze({ + setTimeout(callback, ms, ...args) { + const handle = setTimeout(callback, ms, ...args); + return { dispose: () => clearTimeout(handle) }; + }, + setImmediate(callback, ...args) { + const handle = setImmediate(callback, ...args); + return { dispose: () => clearImmediate(handle) }; + }, + setInterval(callback, ms, ...args) { + const handle = setInterval(callback, ms, ...args); + return { dispose: () => clearInterval(handle) }; + } + }) + }); + function RIL() { + return _ril; + } + (function(RIL2) { + function install() { + api_1.RAL.install(_ril); + } + RIL2.install = install; + })(RIL || (RIL = {})); + exports2.default = RIL; + } +}); + +// node_modules/vscode-jsonrpc/lib/node/main.js +var require_main = __commonJS({ + "node_modules/vscode-jsonrpc/lib/node/main.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createMessageConnection = exports2.createServerSocketTransport = exports2.createClientSocketTransport = exports2.createServerPipeTransport = exports2.createClientPipeTransport = exports2.generateRandomPipeName = exports2.StreamMessageWriter = exports2.StreamMessageReader = exports2.SocketMessageWriter = exports2.SocketMessageReader = exports2.PortMessageWriter = exports2.PortMessageReader = exports2.IPCMessageWriter = exports2.IPCMessageReader = void 0; + var ril_1 = require_ril(); + ril_1.default.install(); + var path8 = require("path"); + var os4 = require("os"); + var crypto_1 = require("crypto"); + var net_1 = require("net"); + var api_1 = require_api(); + __exportStar(require_api(), exports2); + var IPCMessageReader = class extends api_1.AbstractMessageReader { + constructor(process2) { + super(); + this.process = process2; + let eventEmitter = this.process; + eventEmitter.on("error", (error) => this.fireError(error)); + eventEmitter.on("close", () => this.fireClose()); + } + listen(callback) { + this.process.on("message", callback); + return api_1.Disposable.create(() => this.process.off("message", callback)); + } + }; + exports2.IPCMessageReader = IPCMessageReader; + var IPCMessageWriter = class extends api_1.AbstractMessageWriter { + constructor(process2) { + super(); + this.process = process2; + this.errorCount = 0; + const eventEmitter = this.process; + eventEmitter.on("error", (error) => this.fireError(error)); + eventEmitter.on("close", () => this.fireClose); + } + write(msg) { + try { + if (typeof this.process.send === "function") { + this.process.send(msg, void 0, void 0, (error) => { + if (error) { + this.errorCount++; + this.handleError(error, msg); + } else { + this.errorCount = 0; + } + }); + } + return Promise.resolve(); + } catch (error) { + this.handleError(error, msg); + return Promise.reject(error); + } + } + handleError(error, msg) { + this.errorCount++; + this.fireError(error, msg, this.errorCount); + } + end() { + } + }; + exports2.IPCMessageWriter = IPCMessageWriter; + var PortMessageReader = class extends api_1.AbstractMessageReader { + constructor(port) { + super(); + this.onData = new api_1.Emitter(); + port.on("close", () => this.fireClose); + port.on("error", (error) => this.fireError(error)); + port.on("message", (message) => { + this.onData.fire(message); + }); + } + listen(callback) { + return this.onData.event(callback); + } + }; + exports2.PortMessageReader = PortMessageReader; + var PortMessageWriter = class extends api_1.AbstractMessageWriter { + constructor(port) { + super(); + this.port = port; + this.errorCount = 0; + port.on("close", () => this.fireClose()); + port.on("error", (error) => this.fireError(error)); + } + write(msg) { + try { + this.port.postMessage(msg); + return Promise.resolve(); + } catch (error) { + this.handleError(error, msg); + return Promise.reject(error); + } + } + handleError(error, msg) { + this.errorCount++; + this.fireError(error, msg, this.errorCount); + } + end() { + } + }; + exports2.PortMessageWriter = PortMessageWriter; + var SocketMessageReader = class extends api_1.ReadableStreamMessageReader { + constructor(socket, encoding = "utf-8") { + super((0, ril_1.default)().stream.asReadableStream(socket), encoding); + } + }; + exports2.SocketMessageReader = SocketMessageReader; + var SocketMessageWriter = class extends api_1.WriteableStreamMessageWriter { + constructor(socket, options) { + super((0, ril_1.default)().stream.asWritableStream(socket), options); + this.socket = socket; + } + dispose() { + super.dispose(); + this.socket.destroy(); + } + }; + exports2.SocketMessageWriter = SocketMessageWriter; + var StreamMessageReader = class extends api_1.ReadableStreamMessageReader { + constructor(readable, encoding) { + super((0, ril_1.default)().stream.asReadableStream(readable), encoding); + } + }; + exports2.StreamMessageReader = StreamMessageReader; + var StreamMessageWriter = class extends api_1.WriteableStreamMessageWriter { + constructor(writable, options) { + super((0, ril_1.default)().stream.asWritableStream(writable), options); + } + }; + exports2.StreamMessageWriter = StreamMessageWriter; + var XDG_RUNTIME_DIR = process.env["XDG_RUNTIME_DIR"]; + var safeIpcPathLengths = /* @__PURE__ */ new Map([ + ["linux", 107], + ["darwin", 103] + ]); + function generateRandomPipeName() { + const randomSuffix = (0, crypto_1.randomBytes)(21).toString("hex"); + if (process.platform === "win32") { + return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`; + } + let result; + if (XDG_RUNTIME_DIR) { + result = path8.join(XDG_RUNTIME_DIR, `vscode-ipc-${randomSuffix}.sock`); + } else { + result = path8.join(os4.tmpdir(), `vscode-${randomSuffix}.sock`); + } + const limit = safeIpcPathLengths.get(process.platform); + if (limit !== void 0 && result.length > limit) { + (0, ril_1.default)().console.warn(`WARNING: IPC handle "${result}" is longer than ${limit} characters.`); + } + return result; + } + exports2.generateRandomPipeName = generateRandomPipeName; + function createClientPipeTransport(pipeName, encoding = "utf-8") { + let connectResolve; + const connected = new Promise((resolve, _reject) => { + connectResolve = resolve; + }); + return new Promise((resolve, reject) => { + let server = (0, net_1.createServer)((socket) => { + server.close(); + connectResolve([ + new SocketMessageReader(socket, encoding), + new SocketMessageWriter(socket, encoding) + ]); + }); + server.on("error", reject); + server.listen(pipeName, () => { + server.removeListener("error", reject); + resolve({ + onConnected: () => { + return connected; + } + }); + }); + }); + } + exports2.createClientPipeTransport = createClientPipeTransport; + function createServerPipeTransport(pipeName, encoding = "utf-8") { + const socket = (0, net_1.createConnection)(pipeName); + return [ + new SocketMessageReader(socket, encoding), + new SocketMessageWriter(socket, encoding) + ]; + } + exports2.createServerPipeTransport = createServerPipeTransport; + function createClientSocketTransport(port, encoding = "utf-8") { + let connectResolve; + const connected = new Promise((resolve, _reject) => { + connectResolve = resolve; + }); + return new Promise((resolve, reject) => { + const server = (0, net_1.createServer)((socket) => { + server.close(); + connectResolve([ + new SocketMessageReader(socket, encoding), + new SocketMessageWriter(socket, encoding) + ]); + }); + server.on("error", reject); + server.listen(port, "127.0.0.1", () => { + server.removeListener("error", reject); + resolve({ + onConnected: () => { + return connected; + } + }); + }); + }); + } + exports2.createClientSocketTransport = createClientSocketTransport; + function createServerSocketTransport(port, encoding = "utf-8") { + const socket = (0, net_1.createConnection)(port, "127.0.0.1"); + return [ + new SocketMessageReader(socket, encoding), + new SocketMessageWriter(socket, encoding) + ]; + } + exports2.createServerSocketTransport = createServerSocketTransport; + function isReadableStream(value) { + const candidate = value; + return candidate.read !== void 0 && candidate.addListener !== void 0; + } + function isWritableStream(value) { + const candidate = value; + return candidate.write !== void 0 && candidate.addListener !== void 0; + } + function createMessageConnection(input, output, logger, options) { + if (!logger) { + logger = api_1.NullLogger; + } + const reader = isReadableStream(input) ? new StreamMessageReader(input) : input; + const writer = isWritableStream(output) ? new StreamMessageWriter(output) : output; + if (api_1.ConnectionStrategy.is(options)) { + options = { connectionStrategy: options }; + } + return (0, api_1.createMessageConnection)(reader, writer, logger, options); + } + exports2.createMessageConnection = createMessageConnection; + } +}); + +// node_modules/vscode-jsonrpc/node.js +var require_node = __commonJS({ + "node_modules/vscode-jsonrpc/node.js"(exports2, module2) { + "use strict"; + module2.exports = require_main(); + } +}); + +// node_modules/vscode-languageserver-types/lib/umd/main.js +var require_main2 = __commonJS({ + "node_modules/vscode-languageserver-types/lib/umd/main.js"(exports2, module2) { + (function(factory) { + if (typeof module2 === "object" && typeof module2.exports === "object") { + var v = factory(require, exports2); + if (v !== void 0) module2.exports = v; + } else if (typeof define === "function" && define.amd) { + define(["require", "exports"], factory); + } + })(function(require2, exports3) { + "use strict"; + Object.defineProperty(exports3, "__esModule", { value: true }); + exports3.TextDocument = exports3.EOL = exports3.WorkspaceFolder = exports3.InlineCompletionContext = exports3.SelectedCompletionInfo = exports3.InlineCompletionTriggerKind = exports3.InlineCompletionList = exports3.InlineCompletionItem = exports3.StringValue = exports3.InlayHint = exports3.InlayHintLabelPart = exports3.InlayHintKind = exports3.InlineValueContext = exports3.InlineValueEvaluatableExpression = exports3.InlineValueVariableLookup = exports3.InlineValueText = exports3.SemanticTokens = exports3.SemanticTokenModifiers = exports3.SemanticTokenTypes = exports3.SelectionRange = exports3.DocumentLink = exports3.FormattingOptions = exports3.CodeLens = exports3.CodeAction = exports3.CodeActionContext = exports3.CodeActionTriggerKind = exports3.CodeActionKind = exports3.DocumentSymbol = exports3.WorkspaceSymbol = exports3.SymbolInformation = exports3.SymbolTag = exports3.SymbolKind = exports3.DocumentHighlight = exports3.DocumentHighlightKind = exports3.SignatureInformation = exports3.ParameterInformation = exports3.Hover = exports3.MarkedString = exports3.CompletionList = exports3.CompletionItem = exports3.CompletionItemLabelDetails = exports3.InsertTextMode = exports3.InsertReplaceEdit = exports3.CompletionItemTag = exports3.InsertTextFormat = exports3.CompletionItemKind = exports3.MarkupContent = exports3.MarkupKind = exports3.TextDocumentItem = exports3.OptionalVersionedTextDocumentIdentifier = exports3.VersionedTextDocumentIdentifier = exports3.TextDocumentIdentifier = exports3.WorkspaceChange = exports3.WorkspaceEdit = exports3.DeleteFile = exports3.RenameFile = exports3.CreateFile = exports3.TextDocumentEdit = exports3.AnnotatedTextEdit = exports3.ChangeAnnotationIdentifier = exports3.ChangeAnnotation = exports3.TextEdit = exports3.Command = exports3.Diagnostic = exports3.CodeDescription = exports3.DiagnosticTag = exports3.DiagnosticSeverity = exports3.DiagnosticRelatedInformation = exports3.FoldingRange = exports3.FoldingRangeKind = exports3.ColorPresentation = exports3.ColorInformation = exports3.Color = exports3.LocationLink = exports3.Location = exports3.Range = exports3.Position = exports3.uinteger = exports3.integer = exports3.URI = exports3.DocumentUri = void 0; + var DocumentUri; + (function(DocumentUri2) { + function is(value) { + return typeof value === "string"; + } + DocumentUri2.is = is; + })(DocumentUri || (exports3.DocumentUri = DocumentUri = {})); + var URI; + (function(URI2) { + function is(value) { + return typeof value === "string"; + } + URI2.is = is; + })(URI || (exports3.URI = URI = {})); + var integer; + (function(integer2) { + integer2.MIN_VALUE = -2147483648; + integer2.MAX_VALUE = 2147483647; + function is(value) { + return typeof value === "number" && integer2.MIN_VALUE <= value && value <= integer2.MAX_VALUE; + } + integer2.is = is; + })(integer || (exports3.integer = integer = {})); + var uinteger; + (function(uinteger2) { + uinteger2.MIN_VALUE = 0; + uinteger2.MAX_VALUE = 2147483647; + function is(value) { + return typeof value === "number" && uinteger2.MIN_VALUE <= value && value <= uinteger2.MAX_VALUE; + } + uinteger2.is = is; + })(uinteger || (exports3.uinteger = uinteger = {})); + var Position; + (function(Position2) { + function create(line, character) { + if (line === Number.MAX_VALUE) { + line = uinteger.MAX_VALUE; + } + if (character === Number.MAX_VALUE) { + character = uinteger.MAX_VALUE; + } + return { line, character }; + } + Position2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character); + } + Position2.is = is; + })(Position || (exports3.Position = Position = {})); + var Range; + (function(Range2) { + function create(one, two, three, four) { + if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) { + return { start: Position.create(one, two), end: Position.create(three, four) }; + } else if (Position.is(one) && Position.is(two)) { + return { start: one, end: two }; + } else { + throw new Error("Range#create called with invalid arguments[".concat(one, ", ").concat(two, ", ").concat(three, ", ").concat(four, "]")); + } + } + Range2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end); + } + Range2.is = is; + })(Range || (exports3.Range = Range = {})); + var Location; + (function(Location2) { + function create(uri, range) { + return { uri, range }; + } + Location2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri)); + } + Location2.is = is; + })(Location || (exports3.Location = Location = {})); + var LocationLink; + (function(LocationLink2) { + function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) { + return { targetUri, targetRange, targetSelectionRange, originSelectionRange }; + } + LocationLink2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && Range.is(candidate.targetSelectionRange) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange)); + } + LocationLink2.is = is; + })(LocationLink || (exports3.LocationLink = LocationLink = {})); + var Color; + (function(Color2) { + function create(red, green, blue, alpha) { + return { + red, + green, + blue, + alpha + }; + } + Color2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1); + } + Color2.is = is; + })(Color || (exports3.Color = Color = {})); + var ColorInformation; + (function(ColorInformation2) { + function create(range, color) { + return { + range, + color + }; + } + ColorInformation2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color); + } + ColorInformation2.is = is; + })(ColorInformation || (exports3.ColorInformation = ColorInformation = {})); + var ColorPresentation; + (function(ColorPresentation2) { + function create(label, textEdit, additionalTextEdits) { + return { + label, + textEdit, + additionalTextEdits + }; + } + ColorPresentation2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is)); + } + ColorPresentation2.is = is; + })(ColorPresentation || (exports3.ColorPresentation = ColorPresentation = {})); + var FoldingRangeKind; + (function(FoldingRangeKind2) { + FoldingRangeKind2.Comment = "comment"; + FoldingRangeKind2.Imports = "imports"; + FoldingRangeKind2.Region = "region"; + })(FoldingRangeKind || (exports3.FoldingRangeKind = FoldingRangeKind = {})); + var FoldingRange; + (function(FoldingRange2) { + function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) { + var result = { + startLine, + endLine + }; + if (Is.defined(startCharacter)) { + result.startCharacter = startCharacter; + } + if (Is.defined(endCharacter)) { + result.endCharacter = endCharacter; + } + if (Is.defined(kind)) { + result.kind = kind; + } + if (Is.defined(collapsedText)) { + result.collapsedText = collapsedText; + } + return result; + } + FoldingRange2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind)); + } + FoldingRange2.is = is; + })(FoldingRange || (exports3.FoldingRange = FoldingRange = {})); + var DiagnosticRelatedInformation; + (function(DiagnosticRelatedInformation2) { + function create(location, message) { + return { + location, + message + }; + } + DiagnosticRelatedInformation2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message); + } + DiagnosticRelatedInformation2.is = is; + })(DiagnosticRelatedInformation || (exports3.DiagnosticRelatedInformation = DiagnosticRelatedInformation = {})); + var DiagnosticSeverity; + (function(DiagnosticSeverity2) { + DiagnosticSeverity2.Error = 1; + DiagnosticSeverity2.Warning = 2; + DiagnosticSeverity2.Information = 3; + DiagnosticSeverity2.Hint = 4; + })(DiagnosticSeverity || (exports3.DiagnosticSeverity = DiagnosticSeverity = {})); + var DiagnosticTag; + (function(DiagnosticTag2) { + DiagnosticTag2.Unnecessary = 1; + DiagnosticTag2.Deprecated = 2; + })(DiagnosticTag || (exports3.DiagnosticTag = DiagnosticTag = {})); + var CodeDescription; + (function(CodeDescription2) { + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.href); + } + CodeDescription2.is = is; + })(CodeDescription || (exports3.CodeDescription = CodeDescription = {})); + var Diagnostic; + (function(Diagnostic2) { + function create(range, message, severity, code, source, relatedInformation) { + var result = { range, message }; + if (Is.defined(severity)) { + result.severity = severity; + } + if (Is.defined(code)) { + result.code = code; + } + if (Is.defined(source)) { + result.source = source; + } + if (Is.defined(relatedInformation)) { + result.relatedInformation = relatedInformation; + } + return result; + } + Diagnostic2.create = create; + function is(value) { + var _a; + var candidate = value; + return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is)); + } + Diagnostic2.is = is; + })(Diagnostic || (exports3.Diagnostic = Diagnostic = {})); + var Command; + (function(Command2) { + function create(title, command) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var result = { title, command }; + if (Is.defined(args) && args.length > 0) { + result.arguments = args; + } + return result; + } + Command2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command); + } + Command2.is = is; + })(Command || (exports3.Command = Command = {})); + var TextEdit; + (function(TextEdit2) { + function replace(range, newText) { + return { range, newText }; + } + TextEdit2.replace = replace; + function insert(position, newText) { + return { range: { start: position, end: position }, newText }; + } + TextEdit2.insert = insert; + function del(range) { + return { range, newText: "" }; + } + TextEdit2.del = del; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range); + } + TextEdit2.is = is; + })(TextEdit || (exports3.TextEdit = TextEdit = {})); + var ChangeAnnotation; + (function(ChangeAnnotation2) { + function create(label, needsConfirmation, description) { + var result = { label }; + if (needsConfirmation !== void 0) { + result.needsConfirmation = needsConfirmation; + } + if (description !== void 0) { + result.description = description; + } + return result; + } + ChangeAnnotation2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === void 0) && (Is.string(candidate.description) || candidate.description === void 0); + } + ChangeAnnotation2.is = is; + })(ChangeAnnotation || (exports3.ChangeAnnotation = ChangeAnnotation = {})); + var ChangeAnnotationIdentifier; + (function(ChangeAnnotationIdentifier2) { + function is(value) { + var candidate = value; + return Is.string(candidate); + } + ChangeAnnotationIdentifier2.is = is; + })(ChangeAnnotationIdentifier || (exports3.ChangeAnnotationIdentifier = ChangeAnnotationIdentifier = {})); + var AnnotatedTextEdit; + (function(AnnotatedTextEdit2) { + function replace(range, newText, annotation) { + return { range, newText, annotationId: annotation }; + } + AnnotatedTextEdit2.replace = replace; + function insert(position, newText, annotation) { + return { range: { start: position, end: position }, newText, annotationId: annotation }; + } + AnnotatedTextEdit2.insert = insert; + function del(range, annotation) { + return { range, newText: "", annotationId: annotation }; + } + AnnotatedTextEdit2.del = del; + function is(value) { + var candidate = value; + return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId)); + } + AnnotatedTextEdit2.is = is; + })(AnnotatedTextEdit || (exports3.AnnotatedTextEdit = AnnotatedTextEdit = {})); + var TextDocumentEdit; + (function(TextDocumentEdit2) { + function create(textDocument, edits) { + return { textDocument, edits }; + } + TextDocumentEdit2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits); + } + TextDocumentEdit2.is = is; + })(TextDocumentEdit || (exports3.TextDocumentEdit = TextDocumentEdit = {})); + var CreateFile; + (function(CreateFile2) { + function create(uri, options, annotation) { + var result = { + kind: "create", + uri + }; + if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) { + result.options = options; + } + if (annotation !== void 0) { + result.annotationId = annotation; + } + return result; + } + CreateFile2.create = create; + function is(value) { + var candidate = value; + return candidate && candidate.kind === "create" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId)); + } + CreateFile2.is = is; + })(CreateFile || (exports3.CreateFile = CreateFile = {})); + var RenameFile; + (function(RenameFile2) { + function create(oldUri, newUri, options, annotation) { + var result = { + kind: "rename", + oldUri, + newUri + }; + if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) { + result.options = options; + } + if (annotation !== void 0) { + result.annotationId = annotation; + } + return result; + } + RenameFile2.create = create; + function is(value) { + var candidate = value; + return candidate && candidate.kind === "rename" && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId)); + } + RenameFile2.is = is; + })(RenameFile || (exports3.RenameFile = RenameFile = {})); + var DeleteFile; + (function(DeleteFile2) { + function create(uri, options, annotation) { + var result = { + kind: "delete", + uri + }; + if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) { + result.options = options; + } + if (annotation !== void 0) { + result.annotationId = annotation; + } + return result; + } + DeleteFile2.create = create; + function is(value) { + var candidate = value; + return candidate && candidate.kind === "delete" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId)); + } + DeleteFile2.is = is; + })(DeleteFile || (exports3.DeleteFile = DeleteFile = {})); + var WorkspaceEdit; + (function(WorkspaceEdit2) { + function is(value) { + var candidate = value; + return candidate && (candidate.changes !== void 0 || candidate.documentChanges !== void 0) && (candidate.documentChanges === void 0 || candidate.documentChanges.every(function(change) { + if (Is.string(change.kind)) { + return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change); + } else { + return TextDocumentEdit.is(change); + } + })); + } + WorkspaceEdit2.is = is; + })(WorkspaceEdit || (exports3.WorkspaceEdit = WorkspaceEdit = {})); + var TextEditChangeImpl = ( + /** @class */ + (function() { + function TextEditChangeImpl2(edits, changeAnnotations) { + this.edits = edits; + this.changeAnnotations = changeAnnotations; + } + TextEditChangeImpl2.prototype.insert = function(position, newText, annotation) { + var edit; + var id; + if (annotation === void 0) { + edit = TextEdit.insert(position, newText); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.insert(position, newText, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.insert(position, newText, id); + } + this.edits.push(edit); + if (id !== void 0) { + return id; + } + }; + TextEditChangeImpl2.prototype.replace = function(range, newText, annotation) { + var edit; + var id; + if (annotation === void 0) { + edit = TextEdit.replace(range, newText); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.replace(range, newText, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.replace(range, newText, id); + } + this.edits.push(edit); + if (id !== void 0) { + return id; + } + }; + TextEditChangeImpl2.prototype.delete = function(range, annotation) { + var edit; + var id; + if (annotation === void 0) { + edit = TextEdit.del(range); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.del(range, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.del(range, id); + } + this.edits.push(edit); + if (id !== void 0) { + return id; + } + }; + TextEditChangeImpl2.prototype.add = function(edit) { + this.edits.push(edit); + }; + TextEditChangeImpl2.prototype.all = function() { + return this.edits; + }; + TextEditChangeImpl2.prototype.clear = function() { + this.edits.splice(0, this.edits.length); + }; + TextEditChangeImpl2.prototype.assertChangeAnnotations = function(value) { + if (value === void 0) { + throw new Error("Text edit change is not configured to manage change annotations."); + } + }; + return TextEditChangeImpl2; + })() + ); + var ChangeAnnotations = ( + /** @class */ + (function() { + function ChangeAnnotations2(annotations) { + this._annotations = annotations === void 0 ? /* @__PURE__ */ Object.create(null) : annotations; + this._counter = 0; + this._size = 0; + } + ChangeAnnotations2.prototype.all = function() { + return this._annotations; + }; + Object.defineProperty(ChangeAnnotations2.prototype, "size", { + get: function() { + return this._size; + }, + enumerable: false, + configurable: true + }); + ChangeAnnotations2.prototype.manage = function(idOrAnnotation, annotation) { + var id; + if (ChangeAnnotationIdentifier.is(idOrAnnotation)) { + id = idOrAnnotation; + } else { + id = this.nextId(); + annotation = idOrAnnotation; + } + if (this._annotations[id] !== void 0) { + throw new Error("Id ".concat(id, " is already in use.")); + } + if (annotation === void 0) { + throw new Error("No annotation provided for id ".concat(id)); + } + this._annotations[id] = annotation; + this._size++; + return id; + }; + ChangeAnnotations2.prototype.nextId = function() { + this._counter++; + return this._counter.toString(); + }; + return ChangeAnnotations2; + })() + ); + var WorkspaceChange = ( + /** @class */ + (function() { + function WorkspaceChange2(workspaceEdit) { + var _this = this; + this._textEditChanges = /* @__PURE__ */ Object.create(null); + if (workspaceEdit !== void 0) { + this._workspaceEdit = workspaceEdit; + if (workspaceEdit.documentChanges) { + this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations); + workspaceEdit.changeAnnotations = this._changeAnnotations.all(); + workspaceEdit.documentChanges.forEach(function(change) { + if (TextDocumentEdit.is(change)) { + var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations); + _this._textEditChanges[change.textDocument.uri] = textEditChange; + } + }); + } else if (workspaceEdit.changes) { + Object.keys(workspaceEdit.changes).forEach(function(key) { + var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]); + _this._textEditChanges[key] = textEditChange; + }); + } + } else { + this._workspaceEdit = {}; + } + } + Object.defineProperty(WorkspaceChange2.prototype, "edit", { + /** + * Returns the underlying {@link WorkspaceEdit} literal + * use to be returned from a workspace edit operation like rename. + */ + get: function() { + this.initDocumentChanges(); + if (this._changeAnnotations !== void 0) { + if (this._changeAnnotations.size === 0) { + this._workspaceEdit.changeAnnotations = void 0; + } else { + this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); + } + } + return this._workspaceEdit; + }, + enumerable: false, + configurable: true + }); + WorkspaceChange2.prototype.getTextEditChange = function(key) { + if (OptionalVersionedTextDocumentIdentifier.is(key)) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === void 0) { + throw new Error("Workspace edit is not configured for document changes."); + } + var textDocument = { uri: key.uri, version: key.version }; + var result = this._textEditChanges[textDocument.uri]; + if (!result) { + var edits = []; + var textDocumentEdit = { + textDocument, + edits + }; + this._workspaceEdit.documentChanges.push(textDocumentEdit); + result = new TextEditChangeImpl(edits, this._changeAnnotations); + this._textEditChanges[textDocument.uri] = result; + } + return result; + } else { + this.initChanges(); + if (this._workspaceEdit.changes === void 0) { + throw new Error("Workspace edit is not configured for normal text edit changes."); + } + var result = this._textEditChanges[key]; + if (!result) { + var edits = []; + this._workspaceEdit.changes[key] = edits; + result = new TextEditChangeImpl(edits); + this._textEditChanges[key] = result; + } + return result; + } + }; + WorkspaceChange2.prototype.initDocumentChanges = function() { + if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) { + this._changeAnnotations = new ChangeAnnotations(); + this._workspaceEdit.documentChanges = []; + this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); + } + }; + WorkspaceChange2.prototype.initChanges = function() { + if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) { + this._workspaceEdit.changes = /* @__PURE__ */ Object.create(null); + } + }; + WorkspaceChange2.prototype.createFile = function(uri, optionsOrAnnotation, options) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === void 0) { + throw new Error("Workspace edit is not configured for document changes."); + } + var annotation; + if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === void 0) { + operation = CreateFile.create(uri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); + operation = CreateFile.create(uri, options, id); + } + this._workspaceEdit.documentChanges.push(operation); + if (id !== void 0) { + return id; + } + }; + WorkspaceChange2.prototype.renameFile = function(oldUri, newUri, optionsOrAnnotation, options) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === void 0) { + throw new Error("Workspace edit is not configured for document changes."); + } + var annotation; + if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === void 0) { + operation = RenameFile.create(oldUri, newUri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); + operation = RenameFile.create(oldUri, newUri, options, id); + } + this._workspaceEdit.documentChanges.push(operation); + if (id !== void 0) { + return id; + } + }; + WorkspaceChange2.prototype.deleteFile = function(uri, optionsOrAnnotation, options) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === void 0) { + throw new Error("Workspace edit is not configured for document changes."); + } + var annotation; + if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === void 0) { + operation = DeleteFile.create(uri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); + operation = DeleteFile.create(uri, options, id); + } + this._workspaceEdit.documentChanges.push(operation); + if (id !== void 0) { + return id; + } + }; + return WorkspaceChange2; + })() + ); + exports3.WorkspaceChange = WorkspaceChange; + var TextDocumentIdentifier; + (function(TextDocumentIdentifier2) { + function create(uri) { + return { uri }; + } + TextDocumentIdentifier2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri); + } + TextDocumentIdentifier2.is = is; + })(TextDocumentIdentifier || (exports3.TextDocumentIdentifier = TextDocumentIdentifier = {})); + var VersionedTextDocumentIdentifier; + (function(VersionedTextDocumentIdentifier2) { + function create(uri, version) { + return { uri, version }; + } + VersionedTextDocumentIdentifier2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version); + } + VersionedTextDocumentIdentifier2.is = is; + })(VersionedTextDocumentIdentifier || (exports3.VersionedTextDocumentIdentifier = VersionedTextDocumentIdentifier = {})); + var OptionalVersionedTextDocumentIdentifier; + (function(OptionalVersionedTextDocumentIdentifier2) { + function create(uri, version) { + return { uri, version }; + } + OptionalVersionedTextDocumentIdentifier2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version)); + } + OptionalVersionedTextDocumentIdentifier2.is = is; + })(OptionalVersionedTextDocumentIdentifier || (exports3.OptionalVersionedTextDocumentIdentifier = OptionalVersionedTextDocumentIdentifier = {})); + var TextDocumentItem; + (function(TextDocumentItem2) { + function create(uri, languageId, version, text) { + return { uri, languageId, version, text }; + } + TextDocumentItem2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text); + } + TextDocumentItem2.is = is; + })(TextDocumentItem || (exports3.TextDocumentItem = TextDocumentItem = {})); + var MarkupKind; + (function(MarkupKind2) { + MarkupKind2.PlainText = "plaintext"; + MarkupKind2.Markdown = "markdown"; + function is(value) { + var candidate = value; + return candidate === MarkupKind2.PlainText || candidate === MarkupKind2.Markdown; + } + MarkupKind2.is = is; + })(MarkupKind || (exports3.MarkupKind = MarkupKind = {})); + var MarkupContent; + (function(MarkupContent2) { + function is(value) { + var candidate = value; + return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value); + } + MarkupContent2.is = is; + })(MarkupContent || (exports3.MarkupContent = MarkupContent = {})); + var CompletionItemKind; + (function(CompletionItemKind2) { + CompletionItemKind2.Text = 1; + CompletionItemKind2.Method = 2; + CompletionItemKind2.Function = 3; + CompletionItemKind2.Constructor = 4; + CompletionItemKind2.Field = 5; + CompletionItemKind2.Variable = 6; + CompletionItemKind2.Class = 7; + CompletionItemKind2.Interface = 8; + CompletionItemKind2.Module = 9; + CompletionItemKind2.Property = 10; + CompletionItemKind2.Unit = 11; + CompletionItemKind2.Value = 12; + CompletionItemKind2.Enum = 13; + CompletionItemKind2.Keyword = 14; + CompletionItemKind2.Snippet = 15; + CompletionItemKind2.Color = 16; + CompletionItemKind2.File = 17; + CompletionItemKind2.Reference = 18; + CompletionItemKind2.Folder = 19; + CompletionItemKind2.EnumMember = 20; + CompletionItemKind2.Constant = 21; + CompletionItemKind2.Struct = 22; + CompletionItemKind2.Event = 23; + CompletionItemKind2.Operator = 24; + CompletionItemKind2.TypeParameter = 25; + })(CompletionItemKind || (exports3.CompletionItemKind = CompletionItemKind = {})); + var InsertTextFormat; + (function(InsertTextFormat2) { + InsertTextFormat2.PlainText = 1; + InsertTextFormat2.Snippet = 2; + })(InsertTextFormat || (exports3.InsertTextFormat = InsertTextFormat = {})); + var CompletionItemTag; + (function(CompletionItemTag2) { + CompletionItemTag2.Deprecated = 1; + })(CompletionItemTag || (exports3.CompletionItemTag = CompletionItemTag = {})); + var InsertReplaceEdit; + (function(InsertReplaceEdit2) { + function create(newText, insert, replace) { + return { newText, insert, replace }; + } + InsertReplaceEdit2.create = create; + function is(value) { + var candidate = value; + return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace); + } + InsertReplaceEdit2.is = is; + })(InsertReplaceEdit || (exports3.InsertReplaceEdit = InsertReplaceEdit = {})); + var InsertTextMode; + (function(InsertTextMode2) { + InsertTextMode2.asIs = 1; + InsertTextMode2.adjustIndentation = 2; + })(InsertTextMode || (exports3.InsertTextMode = InsertTextMode = {})); + var CompletionItemLabelDetails; + (function(CompletionItemLabelDetails2) { + function is(value) { + var candidate = value; + return candidate && (Is.string(candidate.detail) || candidate.detail === void 0) && (Is.string(candidate.description) || candidate.description === void 0); + } + CompletionItemLabelDetails2.is = is; + })(CompletionItemLabelDetails || (exports3.CompletionItemLabelDetails = CompletionItemLabelDetails = {})); + var CompletionItem; + (function(CompletionItem2) { + function create(label) { + return { label }; + } + CompletionItem2.create = create; + })(CompletionItem || (exports3.CompletionItem = CompletionItem = {})); + var CompletionList; + (function(CompletionList2) { + function create(items, isIncomplete) { + return { items: items ? items : [], isIncomplete: !!isIncomplete }; + } + CompletionList2.create = create; + })(CompletionList || (exports3.CompletionList = CompletionList = {})); + var MarkedString; + (function(MarkedString2) { + function fromPlainText(plainText) { + return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); + } + MarkedString2.fromPlainText = fromPlainText; + function is(value) { + var candidate = value; + return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value); + } + MarkedString2.is = is; + })(MarkedString || (exports3.MarkedString = MarkedString = {})); + var Hover; + (function(Hover2) { + function is(value) { + var candidate = value; + return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range)); + } + Hover2.is = is; + })(Hover || (exports3.Hover = Hover = {})); + var ParameterInformation; + (function(ParameterInformation2) { + function create(label, documentation) { + return documentation ? { label, documentation } : { label }; + } + ParameterInformation2.create = create; + })(ParameterInformation || (exports3.ParameterInformation = ParameterInformation = {})); + var SignatureInformation; + (function(SignatureInformation2) { + function create(label, documentation) { + var parameters = []; + for (var _i = 2; _i < arguments.length; _i++) { + parameters[_i - 2] = arguments[_i]; + } + var result = { label }; + if (Is.defined(documentation)) { + result.documentation = documentation; + } + if (Is.defined(parameters)) { + result.parameters = parameters; + } else { + result.parameters = []; + } + return result; + } + SignatureInformation2.create = create; + })(SignatureInformation || (exports3.SignatureInformation = SignatureInformation = {})); + var DocumentHighlightKind; + (function(DocumentHighlightKind2) { + DocumentHighlightKind2.Text = 1; + DocumentHighlightKind2.Read = 2; + DocumentHighlightKind2.Write = 3; + })(DocumentHighlightKind || (exports3.DocumentHighlightKind = DocumentHighlightKind = {})); + var DocumentHighlight; + (function(DocumentHighlight2) { + function create(range, kind) { + var result = { range }; + if (Is.number(kind)) { + result.kind = kind; + } + return result; + } + DocumentHighlight2.create = create; + })(DocumentHighlight || (exports3.DocumentHighlight = DocumentHighlight = {})); + var SymbolKind; + (function(SymbolKind2) { + SymbolKind2.File = 1; + SymbolKind2.Module = 2; + SymbolKind2.Namespace = 3; + SymbolKind2.Package = 4; + SymbolKind2.Class = 5; + SymbolKind2.Method = 6; + SymbolKind2.Property = 7; + SymbolKind2.Field = 8; + SymbolKind2.Constructor = 9; + SymbolKind2.Enum = 10; + SymbolKind2.Interface = 11; + SymbolKind2.Function = 12; + SymbolKind2.Variable = 13; + SymbolKind2.Constant = 14; + SymbolKind2.String = 15; + SymbolKind2.Number = 16; + SymbolKind2.Boolean = 17; + SymbolKind2.Array = 18; + SymbolKind2.Object = 19; + SymbolKind2.Key = 20; + SymbolKind2.Null = 21; + SymbolKind2.EnumMember = 22; + SymbolKind2.Struct = 23; + SymbolKind2.Event = 24; + SymbolKind2.Operator = 25; + SymbolKind2.TypeParameter = 26; + })(SymbolKind || (exports3.SymbolKind = SymbolKind = {})); + var SymbolTag; + (function(SymbolTag2) { + SymbolTag2.Deprecated = 1; + })(SymbolTag || (exports3.SymbolTag = SymbolTag = {})); + var SymbolInformation; + (function(SymbolInformation2) { + function create(name, kind, range, uri, containerName) { + var result = { + name, + kind, + location: { uri, range } + }; + if (containerName) { + result.containerName = containerName; + } + return result; + } + SymbolInformation2.create = create; + })(SymbolInformation || (exports3.SymbolInformation = SymbolInformation = {})); + var WorkspaceSymbol; + (function(WorkspaceSymbol2) { + function create(name, kind, uri, range) { + return range !== void 0 ? { name, kind, location: { uri, range } } : { name, kind, location: { uri } }; + } + WorkspaceSymbol2.create = create; + })(WorkspaceSymbol || (exports3.WorkspaceSymbol = WorkspaceSymbol = {})); + var DocumentSymbol; + (function(DocumentSymbol2) { + function create(name, detail, kind, range, selectionRange, children) { + var result = { + name, + detail, + kind, + range, + selectionRange + }; + if (children !== void 0) { + result.children = children; + } + return result; + } + DocumentSymbol2.create = create; + function is(value) { + var candidate = value; + return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === void 0 || Is.string(candidate.detail)) && (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) && (candidate.children === void 0 || Array.isArray(candidate.children)) && (candidate.tags === void 0 || Array.isArray(candidate.tags)); + } + DocumentSymbol2.is = is; + })(DocumentSymbol || (exports3.DocumentSymbol = DocumentSymbol = {})); + var CodeActionKind; + (function(CodeActionKind2) { + CodeActionKind2.Empty = ""; + CodeActionKind2.QuickFix = "quickfix"; + CodeActionKind2.Refactor = "refactor"; + CodeActionKind2.RefactorExtract = "refactor.extract"; + CodeActionKind2.RefactorInline = "refactor.inline"; + CodeActionKind2.RefactorRewrite = "refactor.rewrite"; + CodeActionKind2.Source = "source"; + CodeActionKind2.SourceOrganizeImports = "source.organizeImports"; + CodeActionKind2.SourceFixAll = "source.fixAll"; + })(CodeActionKind || (exports3.CodeActionKind = CodeActionKind = {})); + var CodeActionTriggerKind; + (function(CodeActionTriggerKind2) { + CodeActionTriggerKind2.Invoked = 1; + CodeActionTriggerKind2.Automatic = 2; + })(CodeActionTriggerKind || (exports3.CodeActionTriggerKind = CodeActionTriggerKind = {})); + var CodeActionContext; + (function(CodeActionContext2) { + function create(diagnostics, only, triggerKind) { + var result = { diagnostics }; + if (only !== void 0 && only !== null) { + result.only = only; + } + if (triggerKind !== void 0 && triggerKind !== null) { + result.triggerKind = triggerKind; + } + return result; + } + CodeActionContext2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string)) && (candidate.triggerKind === void 0 || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic); + } + CodeActionContext2.is = is; + })(CodeActionContext || (exports3.CodeActionContext = CodeActionContext = {})); + var CodeAction; + (function(CodeAction2) { + function create(title, kindOrCommandOrEdit, kind) { + var result = { title }; + var checkKind = true; + if (typeof kindOrCommandOrEdit === "string") { + checkKind = false; + result.kind = kindOrCommandOrEdit; + } else if (Command.is(kindOrCommandOrEdit)) { + result.command = kindOrCommandOrEdit; + } else { + result.edit = kindOrCommandOrEdit; + } + if (checkKind && kind !== void 0) { + result.kind = kind; + } + return result; + } + CodeAction2.create = create; + function is(value) { + var candidate = value; + return candidate && Is.string(candidate.title) && (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === void 0 || Is.string(candidate.kind)) && (candidate.edit !== void 0 || candidate.command !== void 0) && (candidate.command === void 0 || Command.is(candidate.command)) && (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) && (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit)); + } + CodeAction2.is = is; + })(CodeAction || (exports3.CodeAction = CodeAction = {})); + var CodeLens; + (function(CodeLens2) { + function create(range, data) { + var result = { range }; + if (Is.defined(data)) { + result.data = data; + } + return result; + } + CodeLens2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command)); + } + CodeLens2.is = is; + })(CodeLens || (exports3.CodeLens = CodeLens = {})); + var FormattingOptions; + (function(FormattingOptions2) { + function create(tabSize, insertSpaces) { + return { tabSize, insertSpaces }; + } + FormattingOptions2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces); + } + FormattingOptions2.is = is; + })(FormattingOptions || (exports3.FormattingOptions = FormattingOptions = {})); + var DocumentLink; + (function(DocumentLink2) { + function create(range, target, data) { + return { range, target, data }; + } + DocumentLink2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target)); + } + DocumentLink2.is = is; + })(DocumentLink || (exports3.DocumentLink = DocumentLink = {})); + var SelectionRange; + (function(SelectionRange2) { + function create(range, parent) { + return { range, parent }; + } + SelectionRange2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === void 0 || SelectionRange2.is(candidate.parent)); + } + SelectionRange2.is = is; + })(SelectionRange || (exports3.SelectionRange = SelectionRange = {})); + var SemanticTokenTypes; + (function(SemanticTokenTypes2) { + SemanticTokenTypes2["namespace"] = "namespace"; + SemanticTokenTypes2["type"] = "type"; + SemanticTokenTypes2["class"] = "class"; + SemanticTokenTypes2["enum"] = "enum"; + SemanticTokenTypes2["interface"] = "interface"; + SemanticTokenTypes2["struct"] = "struct"; + SemanticTokenTypes2["typeParameter"] = "typeParameter"; + SemanticTokenTypes2["parameter"] = "parameter"; + SemanticTokenTypes2["variable"] = "variable"; + SemanticTokenTypes2["property"] = "property"; + SemanticTokenTypes2["enumMember"] = "enumMember"; + SemanticTokenTypes2["event"] = "event"; + SemanticTokenTypes2["function"] = "function"; + SemanticTokenTypes2["method"] = "method"; + SemanticTokenTypes2["macro"] = "macro"; + SemanticTokenTypes2["keyword"] = "keyword"; + SemanticTokenTypes2["modifier"] = "modifier"; + SemanticTokenTypes2["comment"] = "comment"; + SemanticTokenTypes2["string"] = "string"; + SemanticTokenTypes2["number"] = "number"; + SemanticTokenTypes2["regexp"] = "regexp"; + SemanticTokenTypes2["operator"] = "operator"; + SemanticTokenTypes2["decorator"] = "decorator"; + })(SemanticTokenTypes || (exports3.SemanticTokenTypes = SemanticTokenTypes = {})); + var SemanticTokenModifiers; + (function(SemanticTokenModifiers2) { + SemanticTokenModifiers2["declaration"] = "declaration"; + SemanticTokenModifiers2["definition"] = "definition"; + SemanticTokenModifiers2["readonly"] = "readonly"; + SemanticTokenModifiers2["static"] = "static"; + SemanticTokenModifiers2["deprecated"] = "deprecated"; + SemanticTokenModifiers2["abstract"] = "abstract"; + SemanticTokenModifiers2["async"] = "async"; + SemanticTokenModifiers2["modification"] = "modification"; + SemanticTokenModifiers2["documentation"] = "documentation"; + SemanticTokenModifiers2["defaultLibrary"] = "defaultLibrary"; + })(SemanticTokenModifiers || (exports3.SemanticTokenModifiers = SemanticTokenModifiers = {})); + var SemanticTokens; + (function(SemanticTokens2) { + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && (candidate.resultId === void 0 || typeof candidate.resultId === "string") && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === "number"); + } + SemanticTokens2.is = is; + })(SemanticTokens || (exports3.SemanticTokens = SemanticTokens = {})); + var InlineValueText; + (function(InlineValueText2) { + function create(range, text) { + return { range, text }; + } + InlineValueText2.create = create; + function is(value) { + var candidate = value; + return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text); + } + InlineValueText2.is = is; + })(InlineValueText || (exports3.InlineValueText = InlineValueText = {})); + var InlineValueVariableLookup; + (function(InlineValueVariableLookup2) { + function create(range, variableName, caseSensitiveLookup) { + return { range, variableName, caseSensitiveLookup }; + } + InlineValueVariableLookup2.create = create; + function is(value) { + var candidate = value; + return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup) && (Is.string(candidate.variableName) || candidate.variableName === void 0); + } + InlineValueVariableLookup2.is = is; + })(InlineValueVariableLookup || (exports3.InlineValueVariableLookup = InlineValueVariableLookup = {})); + var InlineValueEvaluatableExpression; + (function(InlineValueEvaluatableExpression2) { + function create(range, expression) { + return { range, expression }; + } + InlineValueEvaluatableExpression2.create = create; + function is(value) { + var candidate = value; + return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && (Is.string(candidate.expression) || candidate.expression === void 0); + } + InlineValueEvaluatableExpression2.is = is; + })(InlineValueEvaluatableExpression || (exports3.InlineValueEvaluatableExpression = InlineValueEvaluatableExpression = {})); + var InlineValueContext; + (function(InlineValueContext2) { + function create(frameId, stoppedLocation) { + return { frameId, stoppedLocation }; + } + InlineValueContext2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Range.is(value.stoppedLocation); + } + InlineValueContext2.is = is; + })(InlineValueContext || (exports3.InlineValueContext = InlineValueContext = {})); + var InlayHintKind; + (function(InlayHintKind2) { + InlayHintKind2.Type = 1; + InlayHintKind2.Parameter = 2; + function is(value) { + return value === 1 || value === 2; + } + InlayHintKind2.is = is; + })(InlayHintKind || (exports3.InlayHintKind = InlayHintKind = {})); + var InlayHintLabelPart; + (function(InlayHintLabelPart2) { + function create(value) { + return { value }; + } + InlayHintLabelPart2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && (candidate.tooltip === void 0 || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.location === void 0 || Location.is(candidate.location)) && (candidate.command === void 0 || Command.is(candidate.command)); + } + InlayHintLabelPart2.is = is; + })(InlayHintLabelPart || (exports3.InlayHintLabelPart = InlayHintLabelPart = {})); + var InlayHint; + (function(InlayHint2) { + function create(position, label, kind) { + var result = { position, label }; + if (kind !== void 0) { + result.kind = kind; + } + return result; + } + InlayHint2.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Position.is(candidate.position) && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is)) && (candidate.kind === void 0 || InlayHintKind.is(candidate.kind)) && candidate.textEdits === void 0 || Is.typedArray(candidate.textEdits, TextEdit.is) && (candidate.tooltip === void 0 || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.paddingLeft === void 0 || Is.boolean(candidate.paddingLeft)) && (candidate.paddingRight === void 0 || Is.boolean(candidate.paddingRight)); + } + InlayHint2.is = is; + })(InlayHint || (exports3.InlayHint = InlayHint = {})); + var StringValue; + (function(StringValue2) { + function createSnippet(value) { + return { kind: "snippet", value }; + } + StringValue2.createSnippet = createSnippet; + })(StringValue || (exports3.StringValue = StringValue = {})); + var InlineCompletionItem; + (function(InlineCompletionItem2) { + function create(insertText, filterText, range, command) { + return { insertText, filterText, range, command }; + } + InlineCompletionItem2.create = create; + })(InlineCompletionItem || (exports3.InlineCompletionItem = InlineCompletionItem = {})); + var InlineCompletionList; + (function(InlineCompletionList2) { + function create(items) { + return { items }; + } + InlineCompletionList2.create = create; + })(InlineCompletionList || (exports3.InlineCompletionList = InlineCompletionList = {})); + var InlineCompletionTriggerKind; + (function(InlineCompletionTriggerKind2) { + InlineCompletionTriggerKind2.Invoked = 0; + InlineCompletionTriggerKind2.Automatic = 1; + })(InlineCompletionTriggerKind || (exports3.InlineCompletionTriggerKind = InlineCompletionTriggerKind = {})); + var SelectedCompletionInfo; + (function(SelectedCompletionInfo2) { + function create(range, text) { + return { range, text }; + } + SelectedCompletionInfo2.create = create; + })(SelectedCompletionInfo || (exports3.SelectedCompletionInfo = SelectedCompletionInfo = {})); + var InlineCompletionContext; + (function(InlineCompletionContext2) { + function create(triggerKind, selectedCompletionInfo) { + return { triggerKind, selectedCompletionInfo }; + } + InlineCompletionContext2.create = create; + })(InlineCompletionContext || (exports3.InlineCompletionContext = InlineCompletionContext = {})); + var WorkspaceFolder; + (function(WorkspaceFolder2) { + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name); + } + WorkspaceFolder2.is = is; + })(WorkspaceFolder || (exports3.WorkspaceFolder = WorkspaceFolder = {})); + exports3.EOL = ["\n", "\r\n", "\r"]; + var TextDocument; + (function(TextDocument2) { + function create(uri, languageId, version, content) { + return new FullTextDocument(uri, languageId, version, content); + } + TextDocument2.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false; + } + TextDocument2.is = is; + function applyEdits(document, edits) { + var text = document.getText(); + var sortedEdits = mergeSort(edits, function(a, b) { + var diff = a.range.start.line - b.range.start.line; + if (diff === 0) { + return a.range.start.character - b.range.start.character; + } + return diff; + }); + var lastModifiedOffset = text.length; + for (var i = sortedEdits.length - 1; i >= 0; i--) { + var e = sortedEdits[i]; + var startOffset = document.offsetAt(e.range.start); + var endOffset = document.offsetAt(e.range.end); + if (endOffset <= lastModifiedOffset) { + text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length); + } else { + throw new Error("Overlapping edit"); + } + lastModifiedOffset = startOffset; + } + return text; + } + TextDocument2.applyEdits = applyEdits; + function mergeSort(data, compare) { + if (data.length <= 1) { + return data; + } + var p = data.length / 2 | 0; + var left = data.slice(0, p); + var right = data.slice(p); + mergeSort(left, compare); + mergeSort(right, compare); + var leftIdx = 0; + var rightIdx = 0; + var i = 0; + while (leftIdx < left.length && rightIdx < right.length) { + var ret = compare(left[leftIdx], right[rightIdx]); + if (ret <= 0) { + data[i++] = left[leftIdx++]; + } else { + data[i++] = right[rightIdx++]; + } + } + while (leftIdx < left.length) { + data[i++] = left[leftIdx++]; + } + while (rightIdx < right.length) { + data[i++] = right[rightIdx++]; + } + return data; + } + })(TextDocument || (exports3.TextDocument = TextDocument = {})); + var FullTextDocument = ( + /** @class */ + (function() { + function FullTextDocument2(uri, languageId, version, content) { + this._uri = uri; + this._languageId = languageId; + this._version = version; + this._content = content; + this._lineOffsets = void 0; + } + Object.defineProperty(FullTextDocument2.prototype, "uri", { + get: function() { + return this._uri; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FullTextDocument2.prototype, "languageId", { + get: function() { + return this._languageId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FullTextDocument2.prototype, "version", { + get: function() { + return this._version; + }, + enumerable: false, + configurable: true + }); + FullTextDocument2.prototype.getText = function(range) { + if (range) { + var start = this.offsetAt(range.start); + var end = this.offsetAt(range.end); + return this._content.substring(start, end); + } + return this._content; + }; + FullTextDocument2.prototype.update = function(event, version) { + this._content = event.text; + this._version = version; + this._lineOffsets = void 0; + }; + FullTextDocument2.prototype.getLineOffsets = function() { + if (this._lineOffsets === void 0) { + var lineOffsets = []; + var text = this._content; + var isLineStart = true; + for (var i = 0; i < text.length; i++) { + if (isLineStart) { + lineOffsets.push(i); + isLineStart = false; + } + var ch = text.charAt(i); + isLineStart = ch === "\r" || ch === "\n"; + if (ch === "\r" && i + 1 < text.length && text.charAt(i + 1) === "\n") { + i++; + } + } + if (isLineStart && text.length > 0) { + lineOffsets.push(text.length); + } + this._lineOffsets = lineOffsets; + } + return this._lineOffsets; + }; + FullTextDocument2.prototype.positionAt = function(offset) { + offset = Math.max(Math.min(offset, this._content.length), 0); + var lineOffsets = this.getLineOffsets(); + var low = 0, high = lineOffsets.length; + if (high === 0) { + return Position.create(0, offset); + } + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (lineOffsets[mid] > offset) { + high = mid; + } else { + low = mid + 1; + } + } + var line = low - 1; + return Position.create(line, offset - lineOffsets[line]); + }; + FullTextDocument2.prototype.offsetAt = function(position) { + var lineOffsets = this.getLineOffsets(); + if (position.line >= lineOffsets.length) { + return this._content.length; + } else if (position.line < 0) { + return 0; + } + var lineOffset = lineOffsets[position.line]; + var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length; + return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); + }; + Object.defineProperty(FullTextDocument2.prototype, "lineCount", { + get: function() { + return this.getLineOffsets().length; + }, + enumerable: false, + configurable: true + }); + return FullTextDocument2; + })() + ); + var Is; + (function(Is2) { + var toString = Object.prototype.toString; + function defined(value) { + return typeof value !== "undefined"; + } + Is2.defined = defined; + function undefined2(value) { + return typeof value === "undefined"; + } + Is2.undefined = undefined2; + function boolean(value) { + return value === true || value === false; + } + Is2.boolean = boolean; + function string(value) { + return toString.call(value) === "[object String]"; + } + Is2.string = string; + function number(value) { + return toString.call(value) === "[object Number]"; + } + Is2.number = number; + function numberRange(value, min, max) { + return toString.call(value) === "[object Number]" && min <= value && value <= max; + } + Is2.numberRange = numberRange; + function integer2(value) { + return toString.call(value) === "[object Number]" && -2147483648 <= value && value <= 2147483647; + } + Is2.integer = integer2; + function uinteger2(value) { + return toString.call(value) === "[object Number]" && 0 <= value && value <= 2147483647; + } + Is2.uinteger = uinteger2; + function func(value) { + return toString.call(value) === "[object Function]"; + } + Is2.func = func; + function objectLiteral(value) { + return value !== null && typeof value === "object"; + } + Is2.objectLiteral = objectLiteral; + function typedArray(value, check) { + return Array.isArray(value) && value.every(check); + } + Is2.typedArray = typedArray; + })(Is || (Is = {})); + }); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/messages.js +var require_messages2 = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/messages.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ProtocolNotificationType = exports2.ProtocolNotificationType0 = exports2.ProtocolRequestType = exports2.ProtocolRequestType0 = exports2.RegistrationType = exports2.MessageDirection = void 0; + var vscode_jsonrpc_1 = require_main(); + var MessageDirection; + (function(MessageDirection2) { + MessageDirection2["clientToServer"] = "clientToServer"; + MessageDirection2["serverToClient"] = "serverToClient"; + MessageDirection2["both"] = "both"; + })(MessageDirection || (exports2.MessageDirection = MessageDirection = {})); + var RegistrationType = class { + constructor(method) { + this.method = method; + } + }; + exports2.RegistrationType = RegistrationType; + var ProtocolRequestType0 = class extends vscode_jsonrpc_1.RequestType0 { + constructor(method) { + super(method); + } + }; + exports2.ProtocolRequestType0 = ProtocolRequestType0; + var ProtocolRequestType = class extends vscode_jsonrpc_1.RequestType { + constructor(method) { + super(method, vscode_jsonrpc_1.ParameterStructures.byName); + } + }; + exports2.ProtocolRequestType = ProtocolRequestType; + var ProtocolNotificationType0 = class extends vscode_jsonrpc_1.NotificationType0 { + constructor(method) { + super(method); + } + }; + exports2.ProtocolNotificationType0 = ProtocolNotificationType0; + var ProtocolNotificationType = class extends vscode_jsonrpc_1.NotificationType { + constructor(method) { + super(method, vscode_jsonrpc_1.ParameterStructures.byName); + } + }; + exports2.ProtocolNotificationType = ProtocolNotificationType; + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/utils/is.js +var require_is3 = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/utils/is.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.objectLiteral = exports2.typedArray = exports2.stringArray = exports2.array = exports2.func = exports2.error = exports2.number = exports2.string = exports2.boolean = void 0; + function boolean(value) { + return value === true || value === false; + } + exports2.boolean = boolean; + function string(value) { + return typeof value === "string" || value instanceof String; + } + exports2.string = string; + function number(value) { + return typeof value === "number" || value instanceof Number; + } + exports2.number = number; + function error(value) { + return value instanceof Error; + } + exports2.error = error; + function func(value) { + return typeof value === "function"; + } + exports2.func = func; + function array(value) { + return Array.isArray(value); + } + exports2.array = array; + function stringArray(value) { + return array(value) && value.every((elem) => string(elem)); + } + exports2.stringArray = stringArray; + function typedArray(value, check) { + return Array.isArray(value) && value.every(check); + } + exports2.typedArray = typedArray; + function objectLiteral(value) { + return value !== null && typeof value === "object"; + } + exports2.objectLiteral = objectLiteral; + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js +var require_protocol_implementation = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ImplementationRequest = void 0; + var messages_1 = require_messages2(); + var ImplementationRequest; + (function(ImplementationRequest2) { + ImplementationRequest2.method = "textDocument/implementation"; + ImplementationRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + ImplementationRequest2.type = new messages_1.ProtocolRequestType(ImplementationRequest2.method); + })(ImplementationRequest || (exports2.ImplementationRequest = ImplementationRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js +var require_protocol_typeDefinition = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeDefinitionRequest = void 0; + var messages_1 = require_messages2(); + var TypeDefinitionRequest; + (function(TypeDefinitionRequest2) { + TypeDefinitionRequest2.method = "textDocument/typeDefinition"; + TypeDefinitionRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + TypeDefinitionRequest2.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest2.method); + })(TypeDefinitionRequest || (exports2.TypeDefinitionRequest = TypeDefinitionRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolder.js +var require_protocol_workspaceFolder = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolder.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DidChangeWorkspaceFoldersNotification = exports2.WorkspaceFoldersRequest = void 0; + var messages_1 = require_messages2(); + var WorkspaceFoldersRequest; + (function(WorkspaceFoldersRequest2) { + WorkspaceFoldersRequest2.method = "workspace/workspaceFolders"; + WorkspaceFoldersRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + WorkspaceFoldersRequest2.type = new messages_1.ProtocolRequestType0(WorkspaceFoldersRequest2.method); + })(WorkspaceFoldersRequest || (exports2.WorkspaceFoldersRequest = WorkspaceFoldersRequest = {})); + var DidChangeWorkspaceFoldersNotification; + (function(DidChangeWorkspaceFoldersNotification2) { + DidChangeWorkspaceFoldersNotification2.method = "workspace/didChangeWorkspaceFolders"; + DidChangeWorkspaceFoldersNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidChangeWorkspaceFoldersNotification2.type = new messages_1.ProtocolNotificationType(DidChangeWorkspaceFoldersNotification2.method); + })(DidChangeWorkspaceFoldersNotification || (exports2.DidChangeWorkspaceFoldersNotification = DidChangeWorkspaceFoldersNotification = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js +var require_protocol_configuration = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ConfigurationRequest = void 0; + var messages_1 = require_messages2(); + var ConfigurationRequest; + (function(ConfigurationRequest2) { + ConfigurationRequest2.method = "workspace/configuration"; + ConfigurationRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + ConfigurationRequest2.type = new messages_1.ProtocolRequestType(ConfigurationRequest2.method); + })(ConfigurationRequest || (exports2.ConfigurationRequest = ConfigurationRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js +var require_protocol_colorProvider = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ColorPresentationRequest = exports2.DocumentColorRequest = void 0; + var messages_1 = require_messages2(); + var DocumentColorRequest; + (function(DocumentColorRequest2) { + DocumentColorRequest2.method = "textDocument/documentColor"; + DocumentColorRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DocumentColorRequest2.type = new messages_1.ProtocolRequestType(DocumentColorRequest2.method); + })(DocumentColorRequest || (exports2.DocumentColorRequest = DocumentColorRequest = {})); + var ColorPresentationRequest; + (function(ColorPresentationRequest2) { + ColorPresentationRequest2.method = "textDocument/colorPresentation"; + ColorPresentationRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + ColorPresentationRequest2.type = new messages_1.ProtocolRequestType(ColorPresentationRequest2.method); + })(ColorPresentationRequest || (exports2.ColorPresentationRequest = ColorPresentationRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js +var require_protocol_foldingRange = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.FoldingRangeRefreshRequest = exports2.FoldingRangeRequest = void 0; + var messages_1 = require_messages2(); + var FoldingRangeRequest; + (function(FoldingRangeRequest2) { + FoldingRangeRequest2.method = "textDocument/foldingRange"; + FoldingRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + FoldingRangeRequest2.type = new messages_1.ProtocolRequestType(FoldingRangeRequest2.method); + })(FoldingRangeRequest || (exports2.FoldingRangeRequest = FoldingRangeRequest = {})); + var FoldingRangeRefreshRequest; + (function(FoldingRangeRefreshRequest2) { + FoldingRangeRefreshRequest2.method = `workspace/foldingRange/refresh`; + FoldingRangeRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + FoldingRangeRefreshRequest2.type = new messages_1.ProtocolRequestType0(FoldingRangeRefreshRequest2.method); + })(FoldingRangeRefreshRequest || (exports2.FoldingRangeRefreshRequest = FoldingRangeRefreshRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js +var require_protocol_declaration = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DeclarationRequest = void 0; + var messages_1 = require_messages2(); + var DeclarationRequest; + (function(DeclarationRequest2) { + DeclarationRequest2.method = "textDocument/declaration"; + DeclarationRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DeclarationRequest2.type = new messages_1.ProtocolRequestType(DeclarationRequest2.method); + })(DeclarationRequest || (exports2.DeclarationRequest = DeclarationRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js +var require_protocol_selectionRange = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SelectionRangeRequest = void 0; + var messages_1 = require_messages2(); + var SelectionRangeRequest; + (function(SelectionRangeRequest2) { + SelectionRangeRequest2.method = "textDocument/selectionRange"; + SelectionRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + SelectionRangeRequest2.type = new messages_1.ProtocolRequestType(SelectionRangeRequest2.method); + })(SelectionRangeRequest || (exports2.SelectionRangeRequest = SelectionRangeRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js +var require_protocol_progress = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCreateRequest = exports2.WorkDoneProgress = void 0; + var vscode_jsonrpc_1 = require_main(); + var messages_1 = require_messages2(); + var WorkDoneProgress; + (function(WorkDoneProgress2) { + WorkDoneProgress2.type = new vscode_jsonrpc_1.ProgressType(); + function is(value) { + return value === WorkDoneProgress2.type; + } + WorkDoneProgress2.is = is; + })(WorkDoneProgress || (exports2.WorkDoneProgress = WorkDoneProgress = {})); + var WorkDoneProgressCreateRequest; + (function(WorkDoneProgressCreateRequest2) { + WorkDoneProgressCreateRequest2.method = "window/workDoneProgress/create"; + WorkDoneProgressCreateRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + WorkDoneProgressCreateRequest2.type = new messages_1.ProtocolRequestType(WorkDoneProgressCreateRequest2.method); + })(WorkDoneProgressCreateRequest || (exports2.WorkDoneProgressCreateRequest = WorkDoneProgressCreateRequest = {})); + var WorkDoneProgressCancelNotification; + (function(WorkDoneProgressCancelNotification2) { + WorkDoneProgressCancelNotification2.method = "window/workDoneProgress/cancel"; + WorkDoneProgressCancelNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + WorkDoneProgressCancelNotification2.type = new messages_1.ProtocolNotificationType(WorkDoneProgressCancelNotification2.method); + })(WorkDoneProgressCancelNotification || (exports2.WorkDoneProgressCancelNotification = WorkDoneProgressCancelNotification = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js +var require_protocol_callHierarchy = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyIncomingCallsRequest = exports2.CallHierarchyPrepareRequest = void 0; + var messages_1 = require_messages2(); + var CallHierarchyPrepareRequest; + (function(CallHierarchyPrepareRequest2) { + CallHierarchyPrepareRequest2.method = "textDocument/prepareCallHierarchy"; + CallHierarchyPrepareRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + CallHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest2.method); + })(CallHierarchyPrepareRequest || (exports2.CallHierarchyPrepareRequest = CallHierarchyPrepareRequest = {})); + var CallHierarchyIncomingCallsRequest; + (function(CallHierarchyIncomingCallsRequest2) { + CallHierarchyIncomingCallsRequest2.method = "callHierarchy/incomingCalls"; + CallHierarchyIncomingCallsRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + CallHierarchyIncomingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest2.method); + })(CallHierarchyIncomingCallsRequest || (exports2.CallHierarchyIncomingCallsRequest = CallHierarchyIncomingCallsRequest = {})); + var CallHierarchyOutgoingCallsRequest; + (function(CallHierarchyOutgoingCallsRequest2) { + CallHierarchyOutgoingCallsRequest2.method = "callHierarchy/outgoingCalls"; + CallHierarchyOutgoingCallsRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + CallHierarchyOutgoingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest2.method); + })(CallHierarchyOutgoingCallsRequest || (exports2.CallHierarchyOutgoingCallsRequest = CallHierarchyOutgoingCallsRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js +var require_protocol_semanticTokens = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SemanticTokensRefreshRequest = exports2.SemanticTokensRangeRequest = exports2.SemanticTokensDeltaRequest = exports2.SemanticTokensRequest = exports2.SemanticTokensRegistrationType = exports2.TokenFormat = void 0; + var messages_1 = require_messages2(); + var TokenFormat; + (function(TokenFormat2) { + TokenFormat2.Relative = "relative"; + })(TokenFormat || (exports2.TokenFormat = TokenFormat = {})); + var SemanticTokensRegistrationType; + (function(SemanticTokensRegistrationType2) { + SemanticTokensRegistrationType2.method = "textDocument/semanticTokens"; + SemanticTokensRegistrationType2.type = new messages_1.RegistrationType(SemanticTokensRegistrationType2.method); + })(SemanticTokensRegistrationType || (exports2.SemanticTokensRegistrationType = SemanticTokensRegistrationType = {})); + var SemanticTokensRequest; + (function(SemanticTokensRequest2) { + SemanticTokensRequest2.method = "textDocument/semanticTokens/full"; + SemanticTokensRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + SemanticTokensRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRequest2.method); + SemanticTokensRequest2.registrationMethod = SemanticTokensRegistrationType.method; + })(SemanticTokensRequest || (exports2.SemanticTokensRequest = SemanticTokensRequest = {})); + var SemanticTokensDeltaRequest; + (function(SemanticTokensDeltaRequest2) { + SemanticTokensDeltaRequest2.method = "textDocument/semanticTokens/full/delta"; + SemanticTokensDeltaRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + SemanticTokensDeltaRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensDeltaRequest2.method); + SemanticTokensDeltaRequest2.registrationMethod = SemanticTokensRegistrationType.method; + })(SemanticTokensDeltaRequest || (exports2.SemanticTokensDeltaRequest = SemanticTokensDeltaRequest = {})); + var SemanticTokensRangeRequest; + (function(SemanticTokensRangeRequest2) { + SemanticTokensRangeRequest2.method = "textDocument/semanticTokens/range"; + SemanticTokensRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + SemanticTokensRangeRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest2.method); + SemanticTokensRangeRequest2.registrationMethod = SemanticTokensRegistrationType.method; + })(SemanticTokensRangeRequest || (exports2.SemanticTokensRangeRequest = SemanticTokensRangeRequest = {})); + var SemanticTokensRefreshRequest; + (function(SemanticTokensRefreshRequest2) { + SemanticTokensRefreshRequest2.method = `workspace/semanticTokens/refresh`; + SemanticTokensRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + SemanticTokensRefreshRequest2.type = new messages_1.ProtocolRequestType0(SemanticTokensRefreshRequest2.method); + })(SemanticTokensRefreshRequest || (exports2.SemanticTokensRefreshRequest = SemanticTokensRefreshRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js +var require_protocol_showDocument = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ShowDocumentRequest = void 0; + var messages_1 = require_messages2(); + var ShowDocumentRequest; + (function(ShowDocumentRequest2) { + ShowDocumentRequest2.method = "window/showDocument"; + ShowDocumentRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + ShowDocumentRequest2.type = new messages_1.ProtocolRequestType(ShowDocumentRequest2.method); + })(ShowDocumentRequest || (exports2.ShowDocumentRequest = ShowDocumentRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js +var require_protocol_linkedEditingRange = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.LinkedEditingRangeRequest = void 0; + var messages_1 = require_messages2(); + var LinkedEditingRangeRequest; + (function(LinkedEditingRangeRequest2) { + LinkedEditingRangeRequest2.method = "textDocument/linkedEditingRange"; + LinkedEditingRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + LinkedEditingRangeRequest2.type = new messages_1.ProtocolRequestType(LinkedEditingRangeRequest2.method); + })(LinkedEditingRangeRequest || (exports2.LinkedEditingRangeRequest = LinkedEditingRangeRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js +var require_protocol_fileOperations = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WillDeleteFilesRequest = exports2.DidDeleteFilesNotification = exports2.DidRenameFilesNotification = exports2.WillRenameFilesRequest = exports2.DidCreateFilesNotification = exports2.WillCreateFilesRequest = exports2.FileOperationPatternKind = void 0; + var messages_1 = require_messages2(); + var FileOperationPatternKind; + (function(FileOperationPatternKind2) { + FileOperationPatternKind2.file = "file"; + FileOperationPatternKind2.folder = "folder"; + })(FileOperationPatternKind || (exports2.FileOperationPatternKind = FileOperationPatternKind = {})); + var WillCreateFilesRequest; + (function(WillCreateFilesRequest2) { + WillCreateFilesRequest2.method = "workspace/willCreateFiles"; + WillCreateFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + WillCreateFilesRequest2.type = new messages_1.ProtocolRequestType(WillCreateFilesRequest2.method); + })(WillCreateFilesRequest || (exports2.WillCreateFilesRequest = WillCreateFilesRequest = {})); + var DidCreateFilesNotification; + (function(DidCreateFilesNotification2) { + DidCreateFilesNotification2.method = "workspace/didCreateFiles"; + DidCreateFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidCreateFilesNotification2.type = new messages_1.ProtocolNotificationType(DidCreateFilesNotification2.method); + })(DidCreateFilesNotification || (exports2.DidCreateFilesNotification = DidCreateFilesNotification = {})); + var WillRenameFilesRequest; + (function(WillRenameFilesRequest2) { + WillRenameFilesRequest2.method = "workspace/willRenameFiles"; + WillRenameFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + WillRenameFilesRequest2.type = new messages_1.ProtocolRequestType(WillRenameFilesRequest2.method); + })(WillRenameFilesRequest || (exports2.WillRenameFilesRequest = WillRenameFilesRequest = {})); + var DidRenameFilesNotification; + (function(DidRenameFilesNotification2) { + DidRenameFilesNotification2.method = "workspace/didRenameFiles"; + DidRenameFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidRenameFilesNotification2.type = new messages_1.ProtocolNotificationType(DidRenameFilesNotification2.method); + })(DidRenameFilesNotification || (exports2.DidRenameFilesNotification = DidRenameFilesNotification = {})); + var DidDeleteFilesNotification; + (function(DidDeleteFilesNotification2) { + DidDeleteFilesNotification2.method = "workspace/didDeleteFiles"; + DidDeleteFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidDeleteFilesNotification2.type = new messages_1.ProtocolNotificationType(DidDeleteFilesNotification2.method); + })(DidDeleteFilesNotification || (exports2.DidDeleteFilesNotification = DidDeleteFilesNotification = {})); + var WillDeleteFilesRequest; + (function(WillDeleteFilesRequest2) { + WillDeleteFilesRequest2.method = "workspace/willDeleteFiles"; + WillDeleteFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + WillDeleteFilesRequest2.type = new messages_1.ProtocolRequestType(WillDeleteFilesRequest2.method); + })(WillDeleteFilesRequest || (exports2.WillDeleteFilesRequest = WillDeleteFilesRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js +var require_protocol_moniker = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MonikerRequest = exports2.MonikerKind = exports2.UniquenessLevel = void 0; + var messages_1 = require_messages2(); + var UniquenessLevel; + (function(UniquenessLevel2) { + UniquenessLevel2.document = "document"; + UniquenessLevel2.project = "project"; + UniquenessLevel2.group = "group"; + UniquenessLevel2.scheme = "scheme"; + UniquenessLevel2.global = "global"; + })(UniquenessLevel || (exports2.UniquenessLevel = UniquenessLevel = {})); + var MonikerKind; + (function(MonikerKind2) { + MonikerKind2.$import = "import"; + MonikerKind2.$export = "export"; + MonikerKind2.local = "local"; + })(MonikerKind || (exports2.MonikerKind = MonikerKind = {})); + var MonikerRequest; + (function(MonikerRequest2) { + MonikerRequest2.method = "textDocument/moniker"; + MonikerRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + MonikerRequest2.type = new messages_1.ProtocolRequestType(MonikerRequest2.method); + })(MonikerRequest || (exports2.MonikerRequest = MonikerRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.typeHierarchy.js +var require_protocol_typeHierarchy = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.typeHierarchy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeHierarchySubtypesRequest = exports2.TypeHierarchySupertypesRequest = exports2.TypeHierarchyPrepareRequest = void 0; + var messages_1 = require_messages2(); + var TypeHierarchyPrepareRequest; + (function(TypeHierarchyPrepareRequest2) { + TypeHierarchyPrepareRequest2.method = "textDocument/prepareTypeHierarchy"; + TypeHierarchyPrepareRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + TypeHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchyPrepareRequest2.method); + })(TypeHierarchyPrepareRequest || (exports2.TypeHierarchyPrepareRequest = TypeHierarchyPrepareRequest = {})); + var TypeHierarchySupertypesRequest; + (function(TypeHierarchySupertypesRequest2) { + TypeHierarchySupertypesRequest2.method = "typeHierarchy/supertypes"; + TypeHierarchySupertypesRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + TypeHierarchySupertypesRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchySupertypesRequest2.method); + })(TypeHierarchySupertypesRequest || (exports2.TypeHierarchySupertypesRequest = TypeHierarchySupertypesRequest = {})); + var TypeHierarchySubtypesRequest; + (function(TypeHierarchySubtypesRequest2) { + TypeHierarchySubtypesRequest2.method = "typeHierarchy/subtypes"; + TypeHierarchySubtypesRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + TypeHierarchySubtypesRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchySubtypesRequest2.method); + })(TypeHierarchySubtypesRequest || (exports2.TypeHierarchySubtypesRequest = TypeHierarchySubtypesRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineValue.js +var require_protocol_inlineValue = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineValue.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.InlineValueRefreshRequest = exports2.InlineValueRequest = void 0; + var messages_1 = require_messages2(); + var InlineValueRequest; + (function(InlineValueRequest2) { + InlineValueRequest2.method = "textDocument/inlineValue"; + InlineValueRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + InlineValueRequest2.type = new messages_1.ProtocolRequestType(InlineValueRequest2.method); + })(InlineValueRequest || (exports2.InlineValueRequest = InlineValueRequest = {})); + var InlineValueRefreshRequest; + (function(InlineValueRefreshRequest2) { + InlineValueRefreshRequest2.method = `workspace/inlineValue/refresh`; + InlineValueRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + InlineValueRefreshRequest2.type = new messages_1.ProtocolRequestType0(InlineValueRefreshRequest2.method); + })(InlineValueRefreshRequest || (exports2.InlineValueRefreshRequest = InlineValueRefreshRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.inlayHint.js +var require_protocol_inlayHint = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.inlayHint.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.InlayHintRefreshRequest = exports2.InlayHintResolveRequest = exports2.InlayHintRequest = void 0; + var messages_1 = require_messages2(); + var InlayHintRequest; + (function(InlayHintRequest2) { + InlayHintRequest2.method = "textDocument/inlayHint"; + InlayHintRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + InlayHintRequest2.type = new messages_1.ProtocolRequestType(InlayHintRequest2.method); + })(InlayHintRequest || (exports2.InlayHintRequest = InlayHintRequest = {})); + var InlayHintResolveRequest; + (function(InlayHintResolveRequest2) { + InlayHintResolveRequest2.method = "inlayHint/resolve"; + InlayHintResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + InlayHintResolveRequest2.type = new messages_1.ProtocolRequestType(InlayHintResolveRequest2.method); + })(InlayHintResolveRequest || (exports2.InlayHintResolveRequest = InlayHintResolveRequest = {})); + var InlayHintRefreshRequest; + (function(InlayHintRefreshRequest2) { + InlayHintRefreshRequest2.method = `workspace/inlayHint/refresh`; + InlayHintRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + InlayHintRefreshRequest2.type = new messages_1.ProtocolRequestType0(InlayHintRefreshRequest2.method); + })(InlayHintRefreshRequest || (exports2.InlayHintRefreshRequest = InlayHintRefreshRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.diagnostic.js +var require_protocol_diagnostic = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.diagnostic.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DiagnosticRefreshRequest = exports2.WorkspaceDiagnosticRequest = exports2.DocumentDiagnosticRequest = exports2.DocumentDiagnosticReportKind = exports2.DiagnosticServerCancellationData = void 0; + var vscode_jsonrpc_1 = require_main(); + var Is = require_is3(); + var messages_1 = require_messages2(); + var DiagnosticServerCancellationData; + (function(DiagnosticServerCancellationData2) { + function is(value) { + const candidate = value; + return candidate && Is.boolean(candidate.retriggerRequest); + } + DiagnosticServerCancellationData2.is = is; + })(DiagnosticServerCancellationData || (exports2.DiagnosticServerCancellationData = DiagnosticServerCancellationData = {})); + var DocumentDiagnosticReportKind; + (function(DocumentDiagnosticReportKind2) { + DocumentDiagnosticReportKind2.Full = "full"; + DocumentDiagnosticReportKind2.Unchanged = "unchanged"; + })(DocumentDiagnosticReportKind || (exports2.DocumentDiagnosticReportKind = DocumentDiagnosticReportKind = {})); + var DocumentDiagnosticRequest; + (function(DocumentDiagnosticRequest2) { + DocumentDiagnosticRequest2.method = "textDocument/diagnostic"; + DocumentDiagnosticRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DocumentDiagnosticRequest2.type = new messages_1.ProtocolRequestType(DocumentDiagnosticRequest2.method); + DocumentDiagnosticRequest2.partialResult = new vscode_jsonrpc_1.ProgressType(); + })(DocumentDiagnosticRequest || (exports2.DocumentDiagnosticRequest = DocumentDiagnosticRequest = {})); + var WorkspaceDiagnosticRequest; + (function(WorkspaceDiagnosticRequest2) { + WorkspaceDiagnosticRequest2.method = "workspace/diagnostic"; + WorkspaceDiagnosticRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + WorkspaceDiagnosticRequest2.type = new messages_1.ProtocolRequestType(WorkspaceDiagnosticRequest2.method); + WorkspaceDiagnosticRequest2.partialResult = new vscode_jsonrpc_1.ProgressType(); + })(WorkspaceDiagnosticRequest || (exports2.WorkspaceDiagnosticRequest = WorkspaceDiagnosticRequest = {})); + var DiagnosticRefreshRequest; + (function(DiagnosticRefreshRequest2) { + DiagnosticRefreshRequest2.method = `workspace/diagnostic/refresh`; + DiagnosticRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + DiagnosticRefreshRequest2.type = new messages_1.ProtocolRequestType0(DiagnosticRefreshRequest2.method); + })(DiagnosticRefreshRequest || (exports2.DiagnosticRefreshRequest = DiagnosticRefreshRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.notebook.js +var require_protocol_notebook = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.notebook.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DidCloseNotebookDocumentNotification = exports2.DidSaveNotebookDocumentNotification = exports2.DidChangeNotebookDocumentNotification = exports2.NotebookCellArrayChange = exports2.DidOpenNotebookDocumentNotification = exports2.NotebookDocumentSyncRegistrationType = exports2.NotebookDocument = exports2.NotebookCell = exports2.ExecutionSummary = exports2.NotebookCellKind = void 0; + var vscode_languageserver_types_1 = require_main2(); + var Is = require_is3(); + var messages_1 = require_messages2(); + var NotebookCellKind; + (function(NotebookCellKind2) { + NotebookCellKind2.Markup = 1; + NotebookCellKind2.Code = 2; + function is(value) { + return value === 1 || value === 2; + } + NotebookCellKind2.is = is; + })(NotebookCellKind || (exports2.NotebookCellKind = NotebookCellKind = {})); + var ExecutionSummary; + (function(ExecutionSummary2) { + function create(executionOrder, success) { + const result = { executionOrder }; + if (success === true || success === false) { + result.success = success; + } + return result; + } + ExecutionSummary2.create = create; + function is(value) { + const candidate = value; + return Is.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.executionOrder) && (candidate.success === void 0 || Is.boolean(candidate.success)); + } + ExecutionSummary2.is = is; + function equals(one, other) { + if (one === other) { + return true; + } + if (one === null || one === void 0 || other === null || other === void 0) { + return false; + } + return one.executionOrder === other.executionOrder && one.success === other.success; + } + ExecutionSummary2.equals = equals; + })(ExecutionSummary || (exports2.ExecutionSummary = ExecutionSummary = {})); + var NotebookCell; + (function(NotebookCell2) { + function create(kind, document) { + return { kind, document }; + } + NotebookCell2.create = create; + function is(value) { + const candidate = value; + return Is.objectLiteral(candidate) && NotebookCellKind.is(candidate.kind) && vscode_languageserver_types_1.DocumentUri.is(candidate.document) && (candidate.metadata === void 0 || Is.objectLiteral(candidate.metadata)); + } + NotebookCell2.is = is; + function diff(one, two) { + const result = /* @__PURE__ */ new Set(); + if (one.document !== two.document) { + result.add("document"); + } + if (one.kind !== two.kind) { + result.add("kind"); + } + if (one.executionSummary !== two.executionSummary) { + result.add("executionSummary"); + } + if ((one.metadata !== void 0 || two.metadata !== void 0) && !equalsMetadata(one.metadata, two.metadata)) { + result.add("metadata"); + } + if ((one.executionSummary !== void 0 || two.executionSummary !== void 0) && !ExecutionSummary.equals(one.executionSummary, two.executionSummary)) { + result.add("executionSummary"); + } + return result; + } + NotebookCell2.diff = diff; + function equalsMetadata(one, other) { + if (one === other) { + return true; + } + if (one === null || one === void 0 || other === null || other === void 0) { + return false; + } + if (typeof one !== typeof other) { + return false; + } + if (typeof one !== "object") { + return false; + } + const oneArray = Array.isArray(one); + const otherArray = Array.isArray(other); + if (oneArray !== otherArray) { + return false; + } + if (oneArray && otherArray) { + if (one.length !== other.length) { + return false; + } + for (let i = 0; i < one.length; i++) { + if (!equalsMetadata(one[i], other[i])) { + return false; + } + } + } + if (Is.objectLiteral(one) && Is.objectLiteral(other)) { + const oneKeys = Object.keys(one); + const otherKeys = Object.keys(other); + if (oneKeys.length !== otherKeys.length) { + return false; + } + oneKeys.sort(); + otherKeys.sort(); + if (!equalsMetadata(oneKeys, otherKeys)) { + return false; + } + for (let i = 0; i < oneKeys.length; i++) { + const prop = oneKeys[i]; + if (!equalsMetadata(one[prop], other[prop])) { + return false; + } + } + } + return true; + } + })(NotebookCell || (exports2.NotebookCell = NotebookCell = {})); + var NotebookDocument; + (function(NotebookDocument2) { + function create(uri, notebookType, version, cells) { + return { uri, notebookType, version, cells }; + } + NotebookDocument2.create = create; + function is(value) { + const candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.uri) && vscode_languageserver_types_1.integer.is(candidate.version) && Is.typedArray(candidate.cells, NotebookCell.is); + } + NotebookDocument2.is = is; + })(NotebookDocument || (exports2.NotebookDocument = NotebookDocument = {})); + var NotebookDocumentSyncRegistrationType; + (function(NotebookDocumentSyncRegistrationType2) { + NotebookDocumentSyncRegistrationType2.method = "notebookDocument/sync"; + NotebookDocumentSyncRegistrationType2.messageDirection = messages_1.MessageDirection.clientToServer; + NotebookDocumentSyncRegistrationType2.type = new messages_1.RegistrationType(NotebookDocumentSyncRegistrationType2.method); + })(NotebookDocumentSyncRegistrationType || (exports2.NotebookDocumentSyncRegistrationType = NotebookDocumentSyncRegistrationType = {})); + var DidOpenNotebookDocumentNotification; + (function(DidOpenNotebookDocumentNotification2) { + DidOpenNotebookDocumentNotification2.method = "notebookDocument/didOpen"; + DidOpenNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidOpenNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenNotebookDocumentNotification2.method); + DidOpenNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method; + })(DidOpenNotebookDocumentNotification || (exports2.DidOpenNotebookDocumentNotification = DidOpenNotebookDocumentNotification = {})); + var NotebookCellArrayChange; + (function(NotebookCellArrayChange2) { + function is(value) { + const candidate = value; + return Is.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.start) && vscode_languageserver_types_1.uinteger.is(candidate.deleteCount) && (candidate.cells === void 0 || Is.typedArray(candidate.cells, NotebookCell.is)); + } + NotebookCellArrayChange2.is = is; + function create(start, deleteCount, cells) { + const result = { start, deleteCount }; + if (cells !== void 0) { + result.cells = cells; + } + return result; + } + NotebookCellArrayChange2.create = create; + })(NotebookCellArrayChange || (exports2.NotebookCellArrayChange = NotebookCellArrayChange = {})); + var DidChangeNotebookDocumentNotification; + (function(DidChangeNotebookDocumentNotification2) { + DidChangeNotebookDocumentNotification2.method = "notebookDocument/didChange"; + DidChangeNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidChangeNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeNotebookDocumentNotification2.method); + DidChangeNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method; + })(DidChangeNotebookDocumentNotification || (exports2.DidChangeNotebookDocumentNotification = DidChangeNotebookDocumentNotification = {})); + var DidSaveNotebookDocumentNotification; + (function(DidSaveNotebookDocumentNotification2) { + DidSaveNotebookDocumentNotification2.method = "notebookDocument/didSave"; + DidSaveNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidSaveNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveNotebookDocumentNotification2.method); + DidSaveNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method; + })(DidSaveNotebookDocumentNotification || (exports2.DidSaveNotebookDocumentNotification = DidSaveNotebookDocumentNotification = {})); + var DidCloseNotebookDocumentNotification; + (function(DidCloseNotebookDocumentNotification2) { + DidCloseNotebookDocumentNotification2.method = "notebookDocument/didClose"; + DidCloseNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidCloseNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseNotebookDocumentNotification2.method); + DidCloseNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method; + })(DidCloseNotebookDocumentNotification || (exports2.DidCloseNotebookDocumentNotification = DidCloseNotebookDocumentNotification = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineCompletion.js +var require_protocol_inlineCompletion = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineCompletion.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.InlineCompletionRequest = void 0; + var messages_1 = require_messages2(); + var InlineCompletionRequest; + (function(InlineCompletionRequest2) { + InlineCompletionRequest2.method = "textDocument/inlineCompletion"; + InlineCompletionRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + InlineCompletionRequest2.type = new messages_1.ProtocolRequestType(InlineCompletionRequest2.method); + })(InlineCompletionRequest || (exports2.InlineCompletionRequest = InlineCompletionRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/protocol.js +var require_protocol = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/protocol.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WorkspaceSymbolRequest = exports2.CodeActionResolveRequest = exports2.CodeActionRequest = exports2.DocumentSymbolRequest = exports2.DocumentHighlightRequest = exports2.ReferencesRequest = exports2.DefinitionRequest = exports2.SignatureHelpRequest = exports2.SignatureHelpTriggerKind = exports2.HoverRequest = exports2.CompletionResolveRequest = exports2.CompletionRequest = exports2.CompletionTriggerKind = exports2.PublishDiagnosticsNotification = exports2.WatchKind = exports2.RelativePattern = exports2.FileChangeType = exports2.DidChangeWatchedFilesNotification = exports2.WillSaveTextDocumentWaitUntilRequest = exports2.WillSaveTextDocumentNotification = exports2.TextDocumentSaveReason = exports2.DidSaveTextDocumentNotification = exports2.DidCloseTextDocumentNotification = exports2.DidChangeTextDocumentNotification = exports2.TextDocumentContentChangeEvent = exports2.DidOpenTextDocumentNotification = exports2.TextDocumentSyncKind = exports2.TelemetryEventNotification = exports2.LogMessageNotification = exports2.ShowMessageRequest = exports2.ShowMessageNotification = exports2.MessageType = exports2.DidChangeConfigurationNotification = exports2.ExitNotification = exports2.ShutdownRequest = exports2.InitializedNotification = exports2.InitializeErrorCodes = exports2.InitializeRequest = exports2.WorkDoneProgressOptions = exports2.TextDocumentRegistrationOptions = exports2.StaticRegistrationOptions = exports2.PositionEncodingKind = exports2.FailureHandlingKind = exports2.ResourceOperationKind = exports2.UnregistrationRequest = exports2.RegistrationRequest = exports2.DocumentSelector = exports2.NotebookCellTextDocumentFilter = exports2.NotebookDocumentFilter = exports2.TextDocumentFilter = void 0; + exports2.MonikerRequest = exports2.MonikerKind = exports2.UniquenessLevel = exports2.WillDeleteFilesRequest = exports2.DidDeleteFilesNotification = exports2.WillRenameFilesRequest = exports2.DidRenameFilesNotification = exports2.WillCreateFilesRequest = exports2.DidCreateFilesNotification = exports2.FileOperationPatternKind = exports2.LinkedEditingRangeRequest = exports2.ShowDocumentRequest = exports2.SemanticTokensRegistrationType = exports2.SemanticTokensRefreshRequest = exports2.SemanticTokensRangeRequest = exports2.SemanticTokensDeltaRequest = exports2.SemanticTokensRequest = exports2.TokenFormat = exports2.CallHierarchyPrepareRequest = exports2.CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyIncomingCallsRequest = exports2.WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCreateRequest = exports2.WorkDoneProgress = exports2.SelectionRangeRequest = exports2.DeclarationRequest = exports2.FoldingRangeRefreshRequest = exports2.FoldingRangeRequest = exports2.ColorPresentationRequest = exports2.DocumentColorRequest = exports2.ConfigurationRequest = exports2.DidChangeWorkspaceFoldersNotification = exports2.WorkspaceFoldersRequest = exports2.TypeDefinitionRequest = exports2.ImplementationRequest = exports2.ApplyWorkspaceEditRequest = exports2.ExecuteCommandRequest = exports2.PrepareRenameRequest = exports2.RenameRequest = exports2.PrepareSupportDefaultBehavior = exports2.DocumentOnTypeFormattingRequest = exports2.DocumentRangesFormattingRequest = exports2.DocumentRangeFormattingRequest = exports2.DocumentFormattingRequest = exports2.DocumentLinkResolveRequest = exports2.DocumentLinkRequest = exports2.CodeLensRefreshRequest = exports2.CodeLensResolveRequest = exports2.CodeLensRequest = exports2.WorkspaceSymbolResolveRequest = void 0; + exports2.InlineCompletionRequest = exports2.DidCloseNotebookDocumentNotification = exports2.DidSaveNotebookDocumentNotification = exports2.DidChangeNotebookDocumentNotification = exports2.NotebookCellArrayChange = exports2.DidOpenNotebookDocumentNotification = exports2.NotebookDocumentSyncRegistrationType = exports2.NotebookDocument = exports2.NotebookCell = exports2.ExecutionSummary = exports2.NotebookCellKind = exports2.DiagnosticRefreshRequest = exports2.WorkspaceDiagnosticRequest = exports2.DocumentDiagnosticRequest = exports2.DocumentDiagnosticReportKind = exports2.DiagnosticServerCancellationData = exports2.InlayHintRefreshRequest = exports2.InlayHintResolveRequest = exports2.InlayHintRequest = exports2.InlineValueRefreshRequest = exports2.InlineValueRequest = exports2.TypeHierarchySupertypesRequest = exports2.TypeHierarchySubtypesRequest = exports2.TypeHierarchyPrepareRequest = void 0; + var messages_1 = require_messages2(); + var vscode_languageserver_types_1 = require_main2(); + var Is = require_is3(); + var protocol_implementation_1 = require_protocol_implementation(); + Object.defineProperty(exports2, "ImplementationRequest", { enumerable: true, get: function() { + return protocol_implementation_1.ImplementationRequest; + } }); + var protocol_typeDefinition_1 = require_protocol_typeDefinition(); + Object.defineProperty(exports2, "TypeDefinitionRequest", { enumerable: true, get: function() { + return protocol_typeDefinition_1.TypeDefinitionRequest; + } }); + var protocol_workspaceFolder_1 = require_protocol_workspaceFolder(); + Object.defineProperty(exports2, "WorkspaceFoldersRequest", { enumerable: true, get: function() { + return protocol_workspaceFolder_1.WorkspaceFoldersRequest; + } }); + Object.defineProperty(exports2, "DidChangeWorkspaceFoldersNotification", { enumerable: true, get: function() { + return protocol_workspaceFolder_1.DidChangeWorkspaceFoldersNotification; + } }); + var protocol_configuration_1 = require_protocol_configuration(); + Object.defineProperty(exports2, "ConfigurationRequest", { enumerable: true, get: function() { + return protocol_configuration_1.ConfigurationRequest; + } }); + var protocol_colorProvider_1 = require_protocol_colorProvider(); + Object.defineProperty(exports2, "DocumentColorRequest", { enumerable: true, get: function() { + return protocol_colorProvider_1.DocumentColorRequest; + } }); + Object.defineProperty(exports2, "ColorPresentationRequest", { enumerable: true, get: function() { + return protocol_colorProvider_1.ColorPresentationRequest; + } }); + var protocol_foldingRange_1 = require_protocol_foldingRange(); + Object.defineProperty(exports2, "FoldingRangeRequest", { enumerable: true, get: function() { + return protocol_foldingRange_1.FoldingRangeRequest; + } }); + Object.defineProperty(exports2, "FoldingRangeRefreshRequest", { enumerable: true, get: function() { + return protocol_foldingRange_1.FoldingRangeRefreshRequest; + } }); + var protocol_declaration_1 = require_protocol_declaration(); + Object.defineProperty(exports2, "DeclarationRequest", { enumerable: true, get: function() { + return protocol_declaration_1.DeclarationRequest; + } }); + var protocol_selectionRange_1 = require_protocol_selectionRange(); + Object.defineProperty(exports2, "SelectionRangeRequest", { enumerable: true, get: function() { + return protocol_selectionRange_1.SelectionRangeRequest; + } }); + var protocol_progress_1 = require_protocol_progress(); + Object.defineProperty(exports2, "WorkDoneProgress", { enumerable: true, get: function() { + return protocol_progress_1.WorkDoneProgress; + } }); + Object.defineProperty(exports2, "WorkDoneProgressCreateRequest", { enumerable: true, get: function() { + return protocol_progress_1.WorkDoneProgressCreateRequest; + } }); + Object.defineProperty(exports2, "WorkDoneProgressCancelNotification", { enumerable: true, get: function() { + return protocol_progress_1.WorkDoneProgressCancelNotification; + } }); + var protocol_callHierarchy_1 = require_protocol_callHierarchy(); + Object.defineProperty(exports2, "CallHierarchyIncomingCallsRequest", { enumerable: true, get: function() { + return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest; + } }); + Object.defineProperty(exports2, "CallHierarchyOutgoingCallsRequest", { enumerable: true, get: function() { + return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest; + } }); + Object.defineProperty(exports2, "CallHierarchyPrepareRequest", { enumerable: true, get: function() { + return protocol_callHierarchy_1.CallHierarchyPrepareRequest; + } }); + var protocol_semanticTokens_1 = require_protocol_semanticTokens(); + Object.defineProperty(exports2, "TokenFormat", { enumerable: true, get: function() { + return protocol_semanticTokens_1.TokenFormat; + } }); + Object.defineProperty(exports2, "SemanticTokensRequest", { enumerable: true, get: function() { + return protocol_semanticTokens_1.SemanticTokensRequest; + } }); + Object.defineProperty(exports2, "SemanticTokensDeltaRequest", { enumerable: true, get: function() { + return protocol_semanticTokens_1.SemanticTokensDeltaRequest; + } }); + Object.defineProperty(exports2, "SemanticTokensRangeRequest", { enumerable: true, get: function() { + return protocol_semanticTokens_1.SemanticTokensRangeRequest; + } }); + Object.defineProperty(exports2, "SemanticTokensRefreshRequest", { enumerable: true, get: function() { + return protocol_semanticTokens_1.SemanticTokensRefreshRequest; + } }); + Object.defineProperty(exports2, "SemanticTokensRegistrationType", { enumerable: true, get: function() { + return protocol_semanticTokens_1.SemanticTokensRegistrationType; + } }); + var protocol_showDocument_1 = require_protocol_showDocument(); + Object.defineProperty(exports2, "ShowDocumentRequest", { enumerable: true, get: function() { + return protocol_showDocument_1.ShowDocumentRequest; + } }); + var protocol_linkedEditingRange_1 = require_protocol_linkedEditingRange(); + Object.defineProperty(exports2, "LinkedEditingRangeRequest", { enumerable: true, get: function() { + return protocol_linkedEditingRange_1.LinkedEditingRangeRequest; + } }); + var protocol_fileOperations_1 = require_protocol_fileOperations(); + Object.defineProperty(exports2, "FileOperationPatternKind", { enumerable: true, get: function() { + return protocol_fileOperations_1.FileOperationPatternKind; + } }); + Object.defineProperty(exports2, "DidCreateFilesNotification", { enumerable: true, get: function() { + return protocol_fileOperations_1.DidCreateFilesNotification; + } }); + Object.defineProperty(exports2, "WillCreateFilesRequest", { enumerable: true, get: function() { + return protocol_fileOperations_1.WillCreateFilesRequest; + } }); + Object.defineProperty(exports2, "DidRenameFilesNotification", { enumerable: true, get: function() { + return protocol_fileOperations_1.DidRenameFilesNotification; + } }); + Object.defineProperty(exports2, "WillRenameFilesRequest", { enumerable: true, get: function() { + return protocol_fileOperations_1.WillRenameFilesRequest; + } }); + Object.defineProperty(exports2, "DidDeleteFilesNotification", { enumerable: true, get: function() { + return protocol_fileOperations_1.DidDeleteFilesNotification; + } }); + Object.defineProperty(exports2, "WillDeleteFilesRequest", { enumerable: true, get: function() { + return protocol_fileOperations_1.WillDeleteFilesRequest; + } }); + var protocol_moniker_1 = require_protocol_moniker(); + Object.defineProperty(exports2, "UniquenessLevel", { enumerable: true, get: function() { + return protocol_moniker_1.UniquenessLevel; + } }); + Object.defineProperty(exports2, "MonikerKind", { enumerable: true, get: function() { + return protocol_moniker_1.MonikerKind; + } }); + Object.defineProperty(exports2, "MonikerRequest", { enumerable: true, get: function() { + return protocol_moniker_1.MonikerRequest; + } }); + var protocol_typeHierarchy_1 = require_protocol_typeHierarchy(); + Object.defineProperty(exports2, "TypeHierarchyPrepareRequest", { enumerable: true, get: function() { + return protocol_typeHierarchy_1.TypeHierarchyPrepareRequest; + } }); + Object.defineProperty(exports2, "TypeHierarchySubtypesRequest", { enumerable: true, get: function() { + return protocol_typeHierarchy_1.TypeHierarchySubtypesRequest; + } }); + Object.defineProperty(exports2, "TypeHierarchySupertypesRequest", { enumerable: true, get: function() { + return protocol_typeHierarchy_1.TypeHierarchySupertypesRequest; + } }); + var protocol_inlineValue_1 = require_protocol_inlineValue(); + Object.defineProperty(exports2, "InlineValueRequest", { enumerable: true, get: function() { + return protocol_inlineValue_1.InlineValueRequest; + } }); + Object.defineProperty(exports2, "InlineValueRefreshRequest", { enumerable: true, get: function() { + return protocol_inlineValue_1.InlineValueRefreshRequest; + } }); + var protocol_inlayHint_1 = require_protocol_inlayHint(); + Object.defineProperty(exports2, "InlayHintRequest", { enumerable: true, get: function() { + return protocol_inlayHint_1.InlayHintRequest; + } }); + Object.defineProperty(exports2, "InlayHintResolveRequest", { enumerable: true, get: function() { + return protocol_inlayHint_1.InlayHintResolveRequest; + } }); + Object.defineProperty(exports2, "InlayHintRefreshRequest", { enumerable: true, get: function() { + return protocol_inlayHint_1.InlayHintRefreshRequest; + } }); + var protocol_diagnostic_1 = require_protocol_diagnostic(); + Object.defineProperty(exports2, "DiagnosticServerCancellationData", { enumerable: true, get: function() { + return protocol_diagnostic_1.DiagnosticServerCancellationData; + } }); + Object.defineProperty(exports2, "DocumentDiagnosticReportKind", { enumerable: true, get: function() { + return protocol_diagnostic_1.DocumentDiagnosticReportKind; + } }); + Object.defineProperty(exports2, "DocumentDiagnosticRequest", { enumerable: true, get: function() { + return protocol_diagnostic_1.DocumentDiagnosticRequest; + } }); + Object.defineProperty(exports2, "WorkspaceDiagnosticRequest", { enumerable: true, get: function() { + return protocol_diagnostic_1.WorkspaceDiagnosticRequest; + } }); + Object.defineProperty(exports2, "DiagnosticRefreshRequest", { enumerable: true, get: function() { + return protocol_diagnostic_1.DiagnosticRefreshRequest; + } }); + var protocol_notebook_1 = require_protocol_notebook(); + Object.defineProperty(exports2, "NotebookCellKind", { enumerable: true, get: function() { + return protocol_notebook_1.NotebookCellKind; + } }); + Object.defineProperty(exports2, "ExecutionSummary", { enumerable: true, get: function() { + return protocol_notebook_1.ExecutionSummary; + } }); + Object.defineProperty(exports2, "NotebookCell", { enumerable: true, get: function() { + return protocol_notebook_1.NotebookCell; + } }); + Object.defineProperty(exports2, "NotebookDocument", { enumerable: true, get: function() { + return protocol_notebook_1.NotebookDocument; + } }); + Object.defineProperty(exports2, "NotebookDocumentSyncRegistrationType", { enumerable: true, get: function() { + return protocol_notebook_1.NotebookDocumentSyncRegistrationType; + } }); + Object.defineProperty(exports2, "DidOpenNotebookDocumentNotification", { enumerable: true, get: function() { + return protocol_notebook_1.DidOpenNotebookDocumentNotification; + } }); + Object.defineProperty(exports2, "NotebookCellArrayChange", { enumerable: true, get: function() { + return protocol_notebook_1.NotebookCellArrayChange; + } }); + Object.defineProperty(exports2, "DidChangeNotebookDocumentNotification", { enumerable: true, get: function() { + return protocol_notebook_1.DidChangeNotebookDocumentNotification; + } }); + Object.defineProperty(exports2, "DidSaveNotebookDocumentNotification", { enumerable: true, get: function() { + return protocol_notebook_1.DidSaveNotebookDocumentNotification; + } }); + Object.defineProperty(exports2, "DidCloseNotebookDocumentNotification", { enumerable: true, get: function() { + return protocol_notebook_1.DidCloseNotebookDocumentNotification; + } }); + var protocol_inlineCompletion_1 = require_protocol_inlineCompletion(); + Object.defineProperty(exports2, "InlineCompletionRequest", { enumerable: true, get: function() { + return protocol_inlineCompletion_1.InlineCompletionRequest; + } }); + var TextDocumentFilter; + (function(TextDocumentFilter2) { + function is(value) { + const candidate = value; + return Is.string(candidate) || (Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern)); + } + TextDocumentFilter2.is = is; + })(TextDocumentFilter || (exports2.TextDocumentFilter = TextDocumentFilter = {})); + var NotebookDocumentFilter; + (function(NotebookDocumentFilter2) { + function is(value) { + const candidate = value; + return Is.objectLiteral(candidate) && (Is.string(candidate.notebookType) || Is.string(candidate.scheme) || Is.string(candidate.pattern)); + } + NotebookDocumentFilter2.is = is; + })(NotebookDocumentFilter || (exports2.NotebookDocumentFilter = NotebookDocumentFilter = {})); + var NotebookCellTextDocumentFilter; + (function(NotebookCellTextDocumentFilter2) { + function is(value) { + const candidate = value; + return Is.objectLiteral(candidate) && (Is.string(candidate.notebook) || NotebookDocumentFilter.is(candidate.notebook)) && (candidate.language === void 0 || Is.string(candidate.language)); + } + NotebookCellTextDocumentFilter2.is = is; + })(NotebookCellTextDocumentFilter || (exports2.NotebookCellTextDocumentFilter = NotebookCellTextDocumentFilter = {})); + var DocumentSelector; + (function(DocumentSelector2) { + function is(value) { + if (!Array.isArray(value)) { + return false; + } + for (let elem of value) { + if (!Is.string(elem) && !TextDocumentFilter.is(elem) && !NotebookCellTextDocumentFilter.is(elem)) { + return false; + } + } + return true; + } + DocumentSelector2.is = is; + })(DocumentSelector || (exports2.DocumentSelector = DocumentSelector = {})); + var RegistrationRequest; + (function(RegistrationRequest2) { + RegistrationRequest2.method = "client/registerCapability"; + RegistrationRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + RegistrationRequest2.type = new messages_1.ProtocolRequestType(RegistrationRequest2.method); + })(RegistrationRequest || (exports2.RegistrationRequest = RegistrationRequest = {})); + var UnregistrationRequest; + (function(UnregistrationRequest2) { + UnregistrationRequest2.method = "client/unregisterCapability"; + UnregistrationRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + UnregistrationRequest2.type = new messages_1.ProtocolRequestType(UnregistrationRequest2.method); + })(UnregistrationRequest || (exports2.UnregistrationRequest = UnregistrationRequest = {})); + var ResourceOperationKind; + (function(ResourceOperationKind2) { + ResourceOperationKind2.Create = "create"; + ResourceOperationKind2.Rename = "rename"; + ResourceOperationKind2.Delete = "delete"; + })(ResourceOperationKind || (exports2.ResourceOperationKind = ResourceOperationKind = {})); + var FailureHandlingKind; + (function(FailureHandlingKind2) { + FailureHandlingKind2.Abort = "abort"; + FailureHandlingKind2.Transactional = "transactional"; + FailureHandlingKind2.TextOnlyTransactional = "textOnlyTransactional"; + FailureHandlingKind2.Undo = "undo"; + })(FailureHandlingKind || (exports2.FailureHandlingKind = FailureHandlingKind = {})); + var PositionEncodingKind; + (function(PositionEncodingKind2) { + PositionEncodingKind2.UTF8 = "utf-8"; + PositionEncodingKind2.UTF16 = "utf-16"; + PositionEncodingKind2.UTF32 = "utf-32"; + })(PositionEncodingKind || (exports2.PositionEncodingKind = PositionEncodingKind = {})); + var StaticRegistrationOptions; + (function(StaticRegistrationOptions2) { + function hasId(value) { + const candidate = value; + return candidate && Is.string(candidate.id) && candidate.id.length > 0; + } + StaticRegistrationOptions2.hasId = hasId; + })(StaticRegistrationOptions || (exports2.StaticRegistrationOptions = StaticRegistrationOptions = {})); + var TextDocumentRegistrationOptions; + (function(TextDocumentRegistrationOptions2) { + function is(value) { + const candidate = value; + return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector)); + } + TextDocumentRegistrationOptions2.is = is; + })(TextDocumentRegistrationOptions || (exports2.TextDocumentRegistrationOptions = TextDocumentRegistrationOptions = {})); + var WorkDoneProgressOptions; + (function(WorkDoneProgressOptions2) { + function is(value) { + const candidate = value; + return Is.objectLiteral(candidate) && (candidate.workDoneProgress === void 0 || Is.boolean(candidate.workDoneProgress)); + } + WorkDoneProgressOptions2.is = is; + function hasWorkDoneProgress(value) { + const candidate = value; + return candidate && Is.boolean(candidate.workDoneProgress); + } + WorkDoneProgressOptions2.hasWorkDoneProgress = hasWorkDoneProgress; + })(WorkDoneProgressOptions || (exports2.WorkDoneProgressOptions = WorkDoneProgressOptions = {})); + var InitializeRequest; + (function(InitializeRequest2) { + InitializeRequest2.method = "initialize"; + InitializeRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + InitializeRequest2.type = new messages_1.ProtocolRequestType(InitializeRequest2.method); + })(InitializeRequest || (exports2.InitializeRequest = InitializeRequest = {})); + var InitializeErrorCodes; + (function(InitializeErrorCodes2) { + InitializeErrorCodes2.unknownProtocolVersion = 1; + })(InitializeErrorCodes || (exports2.InitializeErrorCodes = InitializeErrorCodes = {})); + var InitializedNotification; + (function(InitializedNotification2) { + InitializedNotification2.method = "initialized"; + InitializedNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + InitializedNotification2.type = new messages_1.ProtocolNotificationType(InitializedNotification2.method); + })(InitializedNotification || (exports2.InitializedNotification = InitializedNotification = {})); + var ShutdownRequest; + (function(ShutdownRequest2) { + ShutdownRequest2.method = "shutdown"; + ShutdownRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + ShutdownRequest2.type = new messages_1.ProtocolRequestType0(ShutdownRequest2.method); + })(ShutdownRequest || (exports2.ShutdownRequest = ShutdownRequest = {})); + var ExitNotification; + (function(ExitNotification2) { + ExitNotification2.method = "exit"; + ExitNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + ExitNotification2.type = new messages_1.ProtocolNotificationType0(ExitNotification2.method); + })(ExitNotification || (exports2.ExitNotification = ExitNotification = {})); + var DidChangeConfigurationNotification; + (function(DidChangeConfigurationNotification2) { + DidChangeConfigurationNotification2.method = "workspace/didChangeConfiguration"; + DidChangeConfigurationNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidChangeConfigurationNotification2.type = new messages_1.ProtocolNotificationType(DidChangeConfigurationNotification2.method); + })(DidChangeConfigurationNotification || (exports2.DidChangeConfigurationNotification = DidChangeConfigurationNotification = {})); + var MessageType; + (function(MessageType2) { + MessageType2.Error = 1; + MessageType2.Warning = 2; + MessageType2.Info = 3; + MessageType2.Log = 4; + MessageType2.Debug = 5; + })(MessageType || (exports2.MessageType = MessageType = {})); + var ShowMessageNotification; + (function(ShowMessageNotification2) { + ShowMessageNotification2.method = "window/showMessage"; + ShowMessageNotification2.messageDirection = messages_1.MessageDirection.serverToClient; + ShowMessageNotification2.type = new messages_1.ProtocolNotificationType(ShowMessageNotification2.method); + })(ShowMessageNotification || (exports2.ShowMessageNotification = ShowMessageNotification = {})); + var ShowMessageRequest; + (function(ShowMessageRequest2) { + ShowMessageRequest2.method = "window/showMessageRequest"; + ShowMessageRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + ShowMessageRequest2.type = new messages_1.ProtocolRequestType(ShowMessageRequest2.method); + })(ShowMessageRequest || (exports2.ShowMessageRequest = ShowMessageRequest = {})); + var LogMessageNotification; + (function(LogMessageNotification2) { + LogMessageNotification2.method = "window/logMessage"; + LogMessageNotification2.messageDirection = messages_1.MessageDirection.serverToClient; + LogMessageNotification2.type = new messages_1.ProtocolNotificationType(LogMessageNotification2.method); + })(LogMessageNotification || (exports2.LogMessageNotification = LogMessageNotification = {})); + var TelemetryEventNotification; + (function(TelemetryEventNotification2) { + TelemetryEventNotification2.method = "telemetry/event"; + TelemetryEventNotification2.messageDirection = messages_1.MessageDirection.serverToClient; + TelemetryEventNotification2.type = new messages_1.ProtocolNotificationType(TelemetryEventNotification2.method); + })(TelemetryEventNotification || (exports2.TelemetryEventNotification = TelemetryEventNotification = {})); + var TextDocumentSyncKind; + (function(TextDocumentSyncKind2) { + TextDocumentSyncKind2.None = 0; + TextDocumentSyncKind2.Full = 1; + TextDocumentSyncKind2.Incremental = 2; + })(TextDocumentSyncKind || (exports2.TextDocumentSyncKind = TextDocumentSyncKind = {})); + var DidOpenTextDocumentNotification; + (function(DidOpenTextDocumentNotification2) { + DidOpenTextDocumentNotification2.method = "textDocument/didOpen"; + DidOpenTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidOpenTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification2.method); + })(DidOpenTextDocumentNotification || (exports2.DidOpenTextDocumentNotification = DidOpenTextDocumentNotification = {})); + var TextDocumentContentChangeEvent; + (function(TextDocumentContentChangeEvent2) { + function isIncremental(event) { + let candidate = event; + return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range !== void 0 && (candidate.rangeLength === void 0 || typeof candidate.rangeLength === "number"); + } + TextDocumentContentChangeEvent2.isIncremental = isIncremental; + function isFull(event) { + let candidate = event; + return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range === void 0 && candidate.rangeLength === void 0; + } + TextDocumentContentChangeEvent2.isFull = isFull; + })(TextDocumentContentChangeEvent || (exports2.TextDocumentContentChangeEvent = TextDocumentContentChangeEvent = {})); + var DidChangeTextDocumentNotification; + (function(DidChangeTextDocumentNotification2) { + DidChangeTextDocumentNotification2.method = "textDocument/didChange"; + DidChangeTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidChangeTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification2.method); + })(DidChangeTextDocumentNotification || (exports2.DidChangeTextDocumentNotification = DidChangeTextDocumentNotification = {})); + var DidCloseTextDocumentNotification; + (function(DidCloseTextDocumentNotification2) { + DidCloseTextDocumentNotification2.method = "textDocument/didClose"; + DidCloseTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidCloseTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification2.method); + })(DidCloseTextDocumentNotification || (exports2.DidCloseTextDocumentNotification = DidCloseTextDocumentNotification = {})); + var DidSaveTextDocumentNotification; + (function(DidSaveTextDocumentNotification2) { + DidSaveTextDocumentNotification2.method = "textDocument/didSave"; + DidSaveTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification2.method); + })(DidSaveTextDocumentNotification || (exports2.DidSaveTextDocumentNotification = DidSaveTextDocumentNotification = {})); + var TextDocumentSaveReason; + (function(TextDocumentSaveReason2) { + TextDocumentSaveReason2.Manual = 1; + TextDocumentSaveReason2.AfterDelay = 2; + TextDocumentSaveReason2.FocusOut = 3; + })(TextDocumentSaveReason || (exports2.TextDocumentSaveReason = TextDocumentSaveReason = {})); + var WillSaveTextDocumentNotification; + (function(WillSaveTextDocumentNotification2) { + WillSaveTextDocumentNotification2.method = "textDocument/willSave"; + WillSaveTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + WillSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification2.method); + })(WillSaveTextDocumentNotification || (exports2.WillSaveTextDocumentNotification = WillSaveTextDocumentNotification = {})); + var WillSaveTextDocumentWaitUntilRequest; + (function(WillSaveTextDocumentWaitUntilRequest2) { + WillSaveTextDocumentWaitUntilRequest2.method = "textDocument/willSaveWaitUntil"; + WillSaveTextDocumentWaitUntilRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + WillSaveTextDocumentWaitUntilRequest2.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest2.method); + })(WillSaveTextDocumentWaitUntilRequest || (exports2.WillSaveTextDocumentWaitUntilRequest = WillSaveTextDocumentWaitUntilRequest = {})); + var DidChangeWatchedFilesNotification; + (function(DidChangeWatchedFilesNotification2) { + DidChangeWatchedFilesNotification2.method = "workspace/didChangeWatchedFiles"; + DidChangeWatchedFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer; + DidChangeWatchedFilesNotification2.type = new messages_1.ProtocolNotificationType(DidChangeWatchedFilesNotification2.method); + })(DidChangeWatchedFilesNotification || (exports2.DidChangeWatchedFilesNotification = DidChangeWatchedFilesNotification = {})); + var FileChangeType; + (function(FileChangeType2) { + FileChangeType2.Created = 1; + FileChangeType2.Changed = 2; + FileChangeType2.Deleted = 3; + })(FileChangeType || (exports2.FileChangeType = FileChangeType = {})); + var RelativePattern; + (function(RelativePattern2) { + function is(value) { + const candidate = value; + return Is.objectLiteral(candidate) && (vscode_languageserver_types_1.URI.is(candidate.baseUri) || vscode_languageserver_types_1.WorkspaceFolder.is(candidate.baseUri)) && Is.string(candidate.pattern); + } + RelativePattern2.is = is; + })(RelativePattern || (exports2.RelativePattern = RelativePattern = {})); + var WatchKind; + (function(WatchKind2) { + WatchKind2.Create = 1; + WatchKind2.Change = 2; + WatchKind2.Delete = 4; + })(WatchKind || (exports2.WatchKind = WatchKind = {})); + var PublishDiagnosticsNotification; + (function(PublishDiagnosticsNotification2) { + PublishDiagnosticsNotification2.method = "textDocument/publishDiagnostics"; + PublishDiagnosticsNotification2.messageDirection = messages_1.MessageDirection.serverToClient; + PublishDiagnosticsNotification2.type = new messages_1.ProtocolNotificationType(PublishDiagnosticsNotification2.method); + })(PublishDiagnosticsNotification || (exports2.PublishDiagnosticsNotification = PublishDiagnosticsNotification = {})); + var CompletionTriggerKind; + (function(CompletionTriggerKind2) { + CompletionTriggerKind2.Invoked = 1; + CompletionTriggerKind2.TriggerCharacter = 2; + CompletionTriggerKind2.TriggerForIncompleteCompletions = 3; + })(CompletionTriggerKind || (exports2.CompletionTriggerKind = CompletionTriggerKind = {})); + var CompletionRequest; + (function(CompletionRequest2) { + CompletionRequest2.method = "textDocument/completion"; + CompletionRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + CompletionRequest2.type = new messages_1.ProtocolRequestType(CompletionRequest2.method); + })(CompletionRequest || (exports2.CompletionRequest = CompletionRequest = {})); + var CompletionResolveRequest; + (function(CompletionResolveRequest2) { + CompletionResolveRequest2.method = "completionItem/resolve"; + CompletionResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + CompletionResolveRequest2.type = new messages_1.ProtocolRequestType(CompletionResolveRequest2.method); + })(CompletionResolveRequest || (exports2.CompletionResolveRequest = CompletionResolveRequest = {})); + var HoverRequest; + (function(HoverRequest2) { + HoverRequest2.method = "textDocument/hover"; + HoverRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + HoverRequest2.type = new messages_1.ProtocolRequestType(HoverRequest2.method); + })(HoverRequest || (exports2.HoverRequest = HoverRequest = {})); + var SignatureHelpTriggerKind; + (function(SignatureHelpTriggerKind2) { + SignatureHelpTriggerKind2.Invoked = 1; + SignatureHelpTriggerKind2.TriggerCharacter = 2; + SignatureHelpTriggerKind2.ContentChange = 3; + })(SignatureHelpTriggerKind || (exports2.SignatureHelpTriggerKind = SignatureHelpTriggerKind = {})); + var SignatureHelpRequest; + (function(SignatureHelpRequest2) { + SignatureHelpRequest2.method = "textDocument/signatureHelp"; + SignatureHelpRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + SignatureHelpRequest2.type = new messages_1.ProtocolRequestType(SignatureHelpRequest2.method); + })(SignatureHelpRequest || (exports2.SignatureHelpRequest = SignatureHelpRequest = {})); + var DefinitionRequest; + (function(DefinitionRequest2) { + DefinitionRequest2.method = "textDocument/definition"; + DefinitionRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DefinitionRequest2.type = new messages_1.ProtocolRequestType(DefinitionRequest2.method); + })(DefinitionRequest || (exports2.DefinitionRequest = DefinitionRequest = {})); + var ReferencesRequest; + (function(ReferencesRequest2) { + ReferencesRequest2.method = "textDocument/references"; + ReferencesRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + ReferencesRequest2.type = new messages_1.ProtocolRequestType(ReferencesRequest2.method); + })(ReferencesRequest || (exports2.ReferencesRequest = ReferencesRequest = {})); + var DocumentHighlightRequest; + (function(DocumentHighlightRequest2) { + DocumentHighlightRequest2.method = "textDocument/documentHighlight"; + DocumentHighlightRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DocumentHighlightRequest2.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest2.method); + })(DocumentHighlightRequest || (exports2.DocumentHighlightRequest = DocumentHighlightRequest = {})); + var DocumentSymbolRequest; + (function(DocumentSymbolRequest2) { + DocumentSymbolRequest2.method = "textDocument/documentSymbol"; + DocumentSymbolRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DocumentSymbolRequest2.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest2.method); + })(DocumentSymbolRequest || (exports2.DocumentSymbolRequest = DocumentSymbolRequest = {})); + var CodeActionRequest; + (function(CodeActionRequest2) { + CodeActionRequest2.method = "textDocument/codeAction"; + CodeActionRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + CodeActionRequest2.type = new messages_1.ProtocolRequestType(CodeActionRequest2.method); + })(CodeActionRequest || (exports2.CodeActionRequest = CodeActionRequest = {})); + var CodeActionResolveRequest; + (function(CodeActionResolveRequest2) { + CodeActionResolveRequest2.method = "codeAction/resolve"; + CodeActionResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + CodeActionResolveRequest2.type = new messages_1.ProtocolRequestType(CodeActionResolveRequest2.method); + })(CodeActionResolveRequest || (exports2.CodeActionResolveRequest = CodeActionResolveRequest = {})); + var WorkspaceSymbolRequest; + (function(WorkspaceSymbolRequest2) { + WorkspaceSymbolRequest2.method = "workspace/symbol"; + WorkspaceSymbolRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + WorkspaceSymbolRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest2.method); + })(WorkspaceSymbolRequest || (exports2.WorkspaceSymbolRequest = WorkspaceSymbolRequest = {})); + var WorkspaceSymbolResolveRequest; + (function(WorkspaceSymbolResolveRequest2) { + WorkspaceSymbolResolveRequest2.method = "workspaceSymbol/resolve"; + WorkspaceSymbolResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + WorkspaceSymbolResolveRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolResolveRequest2.method); + })(WorkspaceSymbolResolveRequest || (exports2.WorkspaceSymbolResolveRequest = WorkspaceSymbolResolveRequest = {})); + var CodeLensRequest; + (function(CodeLensRequest2) { + CodeLensRequest2.method = "textDocument/codeLens"; + CodeLensRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + CodeLensRequest2.type = new messages_1.ProtocolRequestType(CodeLensRequest2.method); + })(CodeLensRequest || (exports2.CodeLensRequest = CodeLensRequest = {})); + var CodeLensResolveRequest; + (function(CodeLensResolveRequest2) { + CodeLensResolveRequest2.method = "codeLens/resolve"; + CodeLensResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + CodeLensResolveRequest2.type = new messages_1.ProtocolRequestType(CodeLensResolveRequest2.method); + })(CodeLensResolveRequest || (exports2.CodeLensResolveRequest = CodeLensResolveRequest = {})); + var CodeLensRefreshRequest; + (function(CodeLensRefreshRequest2) { + CodeLensRefreshRequest2.method = `workspace/codeLens/refresh`; + CodeLensRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + CodeLensRefreshRequest2.type = new messages_1.ProtocolRequestType0(CodeLensRefreshRequest2.method); + })(CodeLensRefreshRequest || (exports2.CodeLensRefreshRequest = CodeLensRefreshRequest = {})); + var DocumentLinkRequest; + (function(DocumentLinkRequest2) { + DocumentLinkRequest2.method = "textDocument/documentLink"; + DocumentLinkRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DocumentLinkRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkRequest2.method); + })(DocumentLinkRequest || (exports2.DocumentLinkRequest = DocumentLinkRequest = {})); + var DocumentLinkResolveRequest; + (function(DocumentLinkResolveRequest2) { + DocumentLinkResolveRequest2.method = "documentLink/resolve"; + DocumentLinkResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DocumentLinkResolveRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkResolveRequest2.method); + })(DocumentLinkResolveRequest || (exports2.DocumentLinkResolveRequest = DocumentLinkResolveRequest = {})); + var DocumentFormattingRequest; + (function(DocumentFormattingRequest2) { + DocumentFormattingRequest2.method = "textDocument/formatting"; + DocumentFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DocumentFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest2.method); + })(DocumentFormattingRequest || (exports2.DocumentFormattingRequest = DocumentFormattingRequest = {})); + var DocumentRangeFormattingRequest; + (function(DocumentRangeFormattingRequest2) { + DocumentRangeFormattingRequest2.method = "textDocument/rangeFormatting"; + DocumentRangeFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DocumentRangeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest2.method); + })(DocumentRangeFormattingRequest || (exports2.DocumentRangeFormattingRequest = DocumentRangeFormattingRequest = {})); + var DocumentRangesFormattingRequest; + (function(DocumentRangesFormattingRequest2) { + DocumentRangesFormattingRequest2.method = "textDocument/rangesFormatting"; + DocumentRangesFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DocumentRangesFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangesFormattingRequest2.method); + })(DocumentRangesFormattingRequest || (exports2.DocumentRangesFormattingRequest = DocumentRangesFormattingRequest = {})); + var DocumentOnTypeFormattingRequest; + (function(DocumentOnTypeFormattingRequest2) { + DocumentOnTypeFormattingRequest2.method = "textDocument/onTypeFormatting"; + DocumentOnTypeFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + DocumentOnTypeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest2.method); + })(DocumentOnTypeFormattingRequest || (exports2.DocumentOnTypeFormattingRequest = DocumentOnTypeFormattingRequest = {})); + var PrepareSupportDefaultBehavior; + (function(PrepareSupportDefaultBehavior2) { + PrepareSupportDefaultBehavior2.Identifier = 1; + })(PrepareSupportDefaultBehavior || (exports2.PrepareSupportDefaultBehavior = PrepareSupportDefaultBehavior = {})); + var RenameRequest; + (function(RenameRequest2) { + RenameRequest2.method = "textDocument/rename"; + RenameRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + RenameRequest2.type = new messages_1.ProtocolRequestType(RenameRequest2.method); + })(RenameRequest || (exports2.RenameRequest = RenameRequest = {})); + var PrepareRenameRequest; + (function(PrepareRenameRequest2) { + PrepareRenameRequest2.method = "textDocument/prepareRename"; + PrepareRenameRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + PrepareRenameRequest2.type = new messages_1.ProtocolRequestType(PrepareRenameRequest2.method); + })(PrepareRenameRequest || (exports2.PrepareRenameRequest = PrepareRenameRequest = {})); + var ExecuteCommandRequest; + (function(ExecuteCommandRequest2) { + ExecuteCommandRequest2.method = "workspace/executeCommand"; + ExecuteCommandRequest2.messageDirection = messages_1.MessageDirection.clientToServer; + ExecuteCommandRequest2.type = new messages_1.ProtocolRequestType(ExecuteCommandRequest2.method); + })(ExecuteCommandRequest || (exports2.ExecuteCommandRequest = ExecuteCommandRequest = {})); + var ApplyWorkspaceEditRequest; + (function(ApplyWorkspaceEditRequest2) { + ApplyWorkspaceEditRequest2.method = "workspace/applyEdit"; + ApplyWorkspaceEditRequest2.messageDirection = messages_1.MessageDirection.serverToClient; + ApplyWorkspaceEditRequest2.type = new messages_1.ProtocolRequestType("workspace/applyEdit"); + })(ApplyWorkspaceEditRequest || (exports2.ApplyWorkspaceEditRequest = ApplyWorkspaceEditRequest = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/connection.js +var require_connection2 = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/connection.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createProtocolConnection = void 0; + var vscode_jsonrpc_1 = require_main(); + function createProtocolConnection(input, output, logger, options) { + if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) { + options = { connectionStrategy: options }; + } + return (0, vscode_jsonrpc_1.createMessageConnection)(input, output, logger, options); + } + exports2.createProtocolConnection = createProtocolConnection; + } +}); + +// node_modules/vscode-languageserver-protocol/lib/common/api.js +var require_api2 = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/common/api.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.LSPErrorCodes = exports2.createProtocolConnection = void 0; + __exportStar(require_main(), exports2); + __exportStar(require_main2(), exports2); + __exportStar(require_messages2(), exports2); + __exportStar(require_protocol(), exports2); + var connection_1 = require_connection2(); + Object.defineProperty(exports2, "createProtocolConnection", { enumerable: true, get: function() { + return connection_1.createProtocolConnection; + } }); + var LSPErrorCodes; + (function(LSPErrorCodes2) { + LSPErrorCodes2.lspReservedErrorRangeStart = -32899; + LSPErrorCodes2.RequestFailed = -32803; + LSPErrorCodes2.ServerCancelled = -32802; + LSPErrorCodes2.ContentModified = -32801; + LSPErrorCodes2.RequestCancelled = -32800; + LSPErrorCodes2.lspReservedErrorRangeEnd = -32800; + })(LSPErrorCodes || (exports2.LSPErrorCodes = LSPErrorCodes = {})); + } +}); + +// node_modules/vscode-languageserver-protocol/lib/node/main.js +var require_main3 = __commonJS({ + "node_modules/vscode-languageserver-protocol/lib/node/main.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createProtocolConnection = void 0; + var node_1 = require_node(); + __exportStar(require_node(), exports2); + __exportStar(require_api2(), exports2); + function createProtocolConnection(input, output, logger, options) { + return (0, node_1.createMessageConnection)(input, output, logger, options); + } + exports2.createProtocolConnection = createProtocolConnection; + } +}); + +// node_modules/vscode-languageclient/lib/common/utils/async.js +var require_async = __commonJS({ + "node_modules/vscode-languageclient/lib/common/utils/async.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.forEach = exports2.mapAsync = exports2.map = exports2.clearTestMode = exports2.setTestMode = exports2.Semaphore = exports2.Delayer = void 0; + var vscode_languageserver_protocol_1 = require_main3(); + var Delayer = class { + constructor(defaultDelay) { + this.defaultDelay = defaultDelay; + this.timeout = void 0; + this.completionPromise = void 0; + this.onSuccess = void 0; + this.task = void 0; + } + trigger(task, delay = this.defaultDelay) { + this.task = task; + if (delay >= 0) { + this.cancelTimeout(); + } + if (!this.completionPromise) { + this.completionPromise = new Promise((resolve) => { + this.onSuccess = resolve; + }).then(() => { + this.completionPromise = void 0; + this.onSuccess = void 0; + var result = this.task(); + this.task = void 0; + return result; + }); + } + if (delay >= 0 || this.timeout === void 0) { + this.timeout = (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(() => { + this.timeout = void 0; + this.onSuccess(void 0); + }, delay >= 0 ? delay : this.defaultDelay); + } + return this.completionPromise; + } + forceDelivery() { + if (!this.completionPromise) { + return void 0; + } + this.cancelTimeout(); + let result = this.task(); + this.completionPromise = void 0; + this.onSuccess = void 0; + this.task = void 0; + return result; + } + isTriggered() { + return this.timeout !== void 0; + } + cancel() { + this.cancelTimeout(); + this.completionPromise = void 0; + } + cancelTimeout() { + if (this.timeout !== void 0) { + this.timeout.dispose(); + this.timeout = void 0; + } + } + }; + exports2.Delayer = Delayer; + var Semaphore = class { + constructor(capacity = 1) { + if (capacity <= 0) { + throw new Error("Capacity must be greater than 0"); + } + this._capacity = capacity; + this._active = 0; + this._waiting = []; + } + lock(thunk) { + return new Promise((resolve, reject) => { + this._waiting.push({ thunk, resolve, reject }); + this.runNext(); + }); + } + get active() { + return this._active; + } + runNext() { + if (this._waiting.length === 0 || this._active === this._capacity) { + return; + } + (0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => this.doRunNext()); + } + doRunNext() { + if (this._waiting.length === 0 || this._active === this._capacity) { + return; + } + const next = this._waiting.shift(); + this._active++; + if (this._active > this._capacity) { + throw new Error(`To many thunks active`); + } + try { + const result = next.thunk(); + if (result instanceof Promise) { + result.then((value) => { + this._active--; + next.resolve(value); + this.runNext(); + }, (err) => { + this._active--; + next.reject(err); + this.runNext(); + }); + } else { + this._active--; + next.resolve(result); + this.runNext(); + } + } catch (err) { + this._active--; + next.reject(err); + this.runNext(); + } + } + }; + exports2.Semaphore = Semaphore; + var $test = false; + function setTestMode() { + $test = true; + } + exports2.setTestMode = setTestMode; + function clearTestMode() { + $test = false; + } + exports2.clearTestMode = clearTestMode; + var defaultYieldTimeout = 15; + var Timer = class { + constructor(yieldAfter = defaultYieldTimeout) { + this.yieldAfter = $test === true ? Math.max(yieldAfter, 2) : Math.max(yieldAfter, defaultYieldTimeout); + this.startTime = Date.now(); + this.counter = 0; + this.total = 0; + this.counterInterval = 1; + } + start() { + this.counter = 0; + this.total = 0; + this.counterInterval = 1; + this.startTime = Date.now(); + } + shouldYield() { + if (++this.counter >= this.counterInterval) { + const timeTaken = Date.now() - this.startTime; + const timeLeft = Math.max(0, this.yieldAfter - timeTaken); + this.total += this.counter; + this.counter = 0; + if (timeTaken >= this.yieldAfter || timeLeft <= 1) { + this.counterInterval = 1; + this.total = 0; + return true; + } else { + switch (timeTaken) { + case 0: + case 1: + this.counterInterval = this.total * 2; + break; + } + } + } + return false; + } + }; + async function map(items, func, token, options) { + if (items.length === 0) { + return []; + } + const result = new Array(items.length); + const timer = new Timer(options?.yieldAfter); + function convertBatch(start) { + timer.start(); + for (let i = start; i < items.length; i++) { + result[i] = func(items[i]); + if (timer.shouldYield()) { + options?.yieldCallback && options.yieldCallback(); + return i + 1; + } + } + return -1; + } + let index = convertBatch(0); + while (index !== -1) { + if (token !== void 0 && token.isCancellationRequested) { + break; + } + index = await new Promise((resolve) => { + (0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => { + resolve(convertBatch(index)); + }); + }); + } + return result; + } + exports2.map = map; + async function mapAsync(items, func, token, options) { + if (items.length === 0) { + return []; + } + const result = new Array(items.length); + const timer = new Timer(options?.yieldAfter); + async function convertBatch(start) { + timer.start(); + for (let i = start; i < items.length; i++) { + result[i] = await func(items[i], token); + if (timer.shouldYield()) { + options?.yieldCallback && options.yieldCallback(); + return i + 1; + } + } + return -1; + } + let index = await convertBatch(0); + while (index !== -1) { + if (token !== void 0 && token.isCancellationRequested) { + break; + } + index = await new Promise((resolve) => { + (0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => { + resolve(convertBatch(index)); + }); + }); + } + return result; + } + exports2.mapAsync = mapAsync; + async function forEach(items, func, token, options) { + if (items.length === 0) { + return; + } + const timer = new Timer(options?.yieldAfter); + function runBatch(start) { + timer.start(); + for (let i = start; i < items.length; i++) { + func(items[i]); + if (timer.shouldYield()) { + options?.yieldCallback && options.yieldCallback(); + return i + 1; + } + } + return -1; + } + let index = runBatch(0); + while (index !== -1) { + if (token !== void 0 && token.isCancellationRequested) { + break; + } + index = await new Promise((resolve) => { + (0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => { + resolve(runBatch(index)); + }); + }); + } + } + exports2.forEach = forEach; + } +}); + +// node_modules/vscode-languageclient/lib/common/protocolCompletionItem.js +var require_protocolCompletionItem = __commonJS({ + "node_modules/vscode-languageclient/lib/common/protocolCompletionItem.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var code = require("vscode"); + var ProtocolCompletionItem = class extends code.CompletionItem { + constructor(label) { + super(label); + } + }; + exports2.default = ProtocolCompletionItem; + } +}); + +// node_modules/vscode-languageclient/lib/common/protocolCodeLens.js +var require_protocolCodeLens = __commonJS({ + "node_modules/vscode-languageclient/lib/common/protocolCodeLens.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var code = require("vscode"); + var ProtocolCodeLens = class extends code.CodeLens { + constructor(range) { + super(range); + } + }; + exports2.default = ProtocolCodeLens; + } +}); + +// node_modules/vscode-languageclient/lib/common/protocolDocumentLink.js +var require_protocolDocumentLink = __commonJS({ + "node_modules/vscode-languageclient/lib/common/protocolDocumentLink.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var code = require("vscode"); + var ProtocolDocumentLink = class extends code.DocumentLink { + constructor(range, target) { + super(range, target); + } + }; + exports2.default = ProtocolDocumentLink; + } +}); + +// node_modules/vscode-languageclient/lib/common/protocolCodeAction.js +var require_protocolCodeAction = __commonJS({ + "node_modules/vscode-languageclient/lib/common/protocolCodeAction.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var vscode12 = require("vscode"); + var ProtocolCodeAction = class extends vscode12.CodeAction { + constructor(title, data) { + super(title); + this.data = data; + } + }; + exports2.default = ProtocolCodeAction; + } +}); + +// node_modules/vscode-languageclient/lib/common/protocolDiagnostic.js +var require_protocolDiagnostic = __commonJS({ + "node_modules/vscode-languageclient/lib/common/protocolDiagnostic.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ProtocolDiagnostic = exports2.DiagnosticCode = void 0; + var vscode12 = require("vscode"); + var Is = require_is(); + var DiagnosticCode; + (function(DiagnosticCode2) { + function is(value) { + const candidate = value; + return candidate !== void 0 && candidate !== null && (Is.number(candidate.value) || Is.string(candidate.value)) && Is.string(candidate.target); + } + DiagnosticCode2.is = is; + })(DiagnosticCode || (exports2.DiagnosticCode = DiagnosticCode = {})); + var ProtocolDiagnostic = class extends vscode12.Diagnostic { + constructor(range, message, severity, data) { + super(range, message, severity); + this.data = data; + this.hasDiagnosticCode = false; + } + }; + exports2.ProtocolDiagnostic = ProtocolDiagnostic; + } +}); + +// node_modules/vscode-languageclient/lib/common/protocolCallHierarchyItem.js +var require_protocolCallHierarchyItem = __commonJS({ + "node_modules/vscode-languageclient/lib/common/protocolCallHierarchyItem.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var code = require("vscode"); + var ProtocolCallHierarchyItem = class extends code.CallHierarchyItem { + constructor(kind, name, detail, uri, range, selectionRange, data) { + super(kind, name, detail, uri, range, selectionRange); + if (data !== void 0) { + this.data = data; + } + } + }; + exports2.default = ProtocolCallHierarchyItem; + } +}); + +// node_modules/vscode-languageclient/lib/common/protocolTypeHierarchyItem.js +var require_protocolTypeHierarchyItem = __commonJS({ + "node_modules/vscode-languageclient/lib/common/protocolTypeHierarchyItem.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var code = require("vscode"); + var ProtocolTypeHierarchyItem = class extends code.TypeHierarchyItem { + constructor(kind, name, detail, uri, range, selectionRange, data) { + super(kind, name, detail, uri, range, selectionRange); + if (data !== void 0) { + this.data = data; + } + } + }; + exports2.default = ProtocolTypeHierarchyItem; + } +}); + +// node_modules/vscode-languageclient/lib/common/protocolWorkspaceSymbol.js +var require_protocolWorkspaceSymbol = __commonJS({ + "node_modules/vscode-languageclient/lib/common/protocolWorkspaceSymbol.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var code = require("vscode"); + var WorkspaceSymbol = class extends code.SymbolInformation { + constructor(name, kind, containerName, locationOrUri, data) { + const hasRange = !(locationOrUri instanceof code.Uri); + super(name, kind, containerName, hasRange ? locationOrUri : new code.Location(locationOrUri, new code.Range(0, 0, 0, 0))); + this.hasRange = hasRange; + if (data !== void 0) { + this.data = data; + } + } + }; + exports2.default = WorkspaceSymbol; + } +}); + +// node_modules/vscode-languageclient/lib/common/protocolInlayHint.js +var require_protocolInlayHint = __commonJS({ + "node_modules/vscode-languageclient/lib/common/protocolInlayHint.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var code = require("vscode"); + var ProtocolInlayHint = class extends code.InlayHint { + constructor(position, label, kind) { + super(position, label, kind); + } + }; + exports2.default = ProtocolInlayHint; + } +}); + +// node_modules/vscode-languageclient/lib/common/codeConverter.js +var require_codeConverter = __commonJS({ + "node_modules/vscode-languageclient/lib/common/codeConverter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createConverter = void 0; + var code = require("vscode"); + var proto = require_main3(); + var Is = require_is(); + var async = require_async(); + var protocolCompletionItem_1 = require_protocolCompletionItem(); + var protocolCodeLens_1 = require_protocolCodeLens(); + var protocolDocumentLink_1 = require_protocolDocumentLink(); + var protocolCodeAction_1 = require_protocolCodeAction(); + var protocolDiagnostic_1 = require_protocolDiagnostic(); + var protocolCallHierarchyItem_1 = require_protocolCallHierarchyItem(); + var protocolTypeHierarchyItem_1 = require_protocolTypeHierarchyItem(); + var protocolWorkspaceSymbol_1 = require_protocolWorkspaceSymbol(); + var protocolInlayHint_1 = require_protocolInlayHint(); + var InsertReplaceRange; + (function(InsertReplaceRange2) { + function is(value) { + const candidate = value; + return candidate && !!candidate.inserting && !!candidate.replacing; + } + InsertReplaceRange2.is = is; + })(InsertReplaceRange || (InsertReplaceRange = {})); + function createConverter(uriConverter) { + const nullConverter = (value) => value.toString(); + const _uriConverter = uriConverter || nullConverter; + function asUri(value) { + return _uriConverter(value); + } + function asTextDocumentIdentifier(textDocument) { + return { + uri: _uriConverter(textDocument.uri) + }; + } + function asTextDocumentItem(textDocument) { + return { + uri: _uriConverter(textDocument.uri), + languageId: textDocument.languageId, + version: textDocument.version, + text: textDocument.getText() + }; + } + function asVersionedTextDocumentIdentifier(textDocument) { + return { + uri: _uriConverter(textDocument.uri), + version: textDocument.version + }; + } + function asOpenTextDocumentParams(textDocument) { + return { + textDocument: asTextDocumentItem(textDocument) + }; + } + function isTextDocumentChangeEvent(value) { + const candidate = value; + return !!candidate.document && !!candidate.contentChanges; + } + function isTextDocument(value) { + const candidate = value; + return !!candidate.uri && !!candidate.version; + } + function asChangeTextDocumentParams(arg0, arg1, arg2) { + if (isTextDocument(arg0)) { + const result = { + textDocument: { + uri: _uriConverter(arg0.uri), + version: arg0.version + }, + contentChanges: [{ text: arg0.getText() }] + }; + return result; + } else if (isTextDocumentChangeEvent(arg0)) { + const uri = arg1; + const version = arg2; + const result = { + textDocument: { + uri: _uriConverter(uri), + version + }, + contentChanges: arg0.contentChanges.map((change) => { + const range = change.range; + return { + range: { + start: { line: range.start.line, character: range.start.character }, + end: { line: range.end.line, character: range.end.character } + }, + rangeLength: change.rangeLength, + text: change.text + }; + }) + }; + return result; + } else { + throw Error("Unsupported text document change parameter"); + } + } + function asCloseTextDocumentParams(textDocument) { + return { + textDocument: asTextDocumentIdentifier(textDocument) + }; + } + function asSaveTextDocumentParams(textDocument, includeContent = false) { + let result = { + textDocument: asTextDocumentIdentifier(textDocument) + }; + if (includeContent) { + result.text = textDocument.getText(); + } + return result; + } + function asTextDocumentSaveReason(reason) { + switch (reason) { + case code.TextDocumentSaveReason.Manual: + return proto.TextDocumentSaveReason.Manual; + case code.TextDocumentSaveReason.AfterDelay: + return proto.TextDocumentSaveReason.AfterDelay; + case code.TextDocumentSaveReason.FocusOut: + return proto.TextDocumentSaveReason.FocusOut; + } + return proto.TextDocumentSaveReason.Manual; + } + function asWillSaveTextDocumentParams(event) { + return { + textDocument: asTextDocumentIdentifier(event.document), + reason: asTextDocumentSaveReason(event.reason) + }; + } + function asDidCreateFilesParams(event) { + return { + files: event.files.map((fileUri) => ({ + uri: _uriConverter(fileUri) + })) + }; + } + function asDidRenameFilesParams(event) { + return { + files: event.files.map((file) => ({ + oldUri: _uriConverter(file.oldUri), + newUri: _uriConverter(file.newUri) + })) + }; + } + function asDidDeleteFilesParams(event) { + return { + files: event.files.map((fileUri) => ({ + uri: _uriConverter(fileUri) + })) + }; + } + function asWillCreateFilesParams(event) { + return { + files: event.files.map((fileUri) => ({ + uri: _uriConverter(fileUri) + })) + }; + } + function asWillRenameFilesParams(event) { + return { + files: event.files.map((file) => ({ + oldUri: _uriConverter(file.oldUri), + newUri: _uriConverter(file.newUri) + })) + }; + } + function asWillDeleteFilesParams(event) { + return { + files: event.files.map((fileUri) => ({ + uri: _uriConverter(fileUri) + })) + }; + } + function asTextDocumentPositionParams(textDocument, position) { + return { + textDocument: asTextDocumentIdentifier(textDocument), + position: asWorkerPosition(position) + }; + } + function asCompletionTriggerKind(triggerKind) { + switch (triggerKind) { + case code.CompletionTriggerKind.TriggerCharacter: + return proto.CompletionTriggerKind.TriggerCharacter; + case code.CompletionTriggerKind.TriggerForIncompleteCompletions: + return proto.CompletionTriggerKind.TriggerForIncompleteCompletions; + default: + return proto.CompletionTriggerKind.Invoked; + } + } + function asCompletionParams(textDocument, position, context) { + return { + textDocument: asTextDocumentIdentifier(textDocument), + position: asWorkerPosition(position), + context: { + triggerKind: asCompletionTriggerKind(context.triggerKind), + triggerCharacter: context.triggerCharacter + } + }; + } + function asSignatureHelpTriggerKind(triggerKind) { + switch (triggerKind) { + case code.SignatureHelpTriggerKind.Invoke: + return proto.SignatureHelpTriggerKind.Invoked; + case code.SignatureHelpTriggerKind.TriggerCharacter: + return proto.SignatureHelpTriggerKind.TriggerCharacter; + case code.SignatureHelpTriggerKind.ContentChange: + return proto.SignatureHelpTriggerKind.ContentChange; + } + } + function asParameterInformation(value) { + return { + label: value.label + }; + } + function asParameterInformations(values) { + return values.map(asParameterInformation); + } + function asSignatureInformation(value) { + return { + label: value.label, + parameters: asParameterInformations(value.parameters) + }; + } + function asSignatureInformations(values) { + return values.map(asSignatureInformation); + } + function asSignatureHelp(value) { + if (value === void 0) { + return value; + } + return { + signatures: asSignatureInformations(value.signatures), + activeSignature: value.activeSignature, + activeParameter: value.activeParameter + }; + } + function asSignatureHelpParams(textDocument, position, context) { + return { + textDocument: asTextDocumentIdentifier(textDocument), + position: asWorkerPosition(position), + context: { + isRetrigger: context.isRetrigger, + triggerCharacter: context.triggerCharacter, + triggerKind: asSignatureHelpTriggerKind(context.triggerKind), + activeSignatureHelp: asSignatureHelp(context.activeSignatureHelp) + } + }; + } + function asWorkerPosition(position) { + return { line: position.line, character: position.character }; + } + function asPosition(value) { + if (value === void 0 || value === null) { + return value; + } + return { line: value.line > proto.uinteger.MAX_VALUE ? proto.uinteger.MAX_VALUE : value.line, character: value.character > proto.uinteger.MAX_VALUE ? proto.uinteger.MAX_VALUE : value.character }; + } + function asPositions(values, token) { + return async.map(values, asPosition, token); + } + function asPositionsSync(values) { + return values.map(asPosition); + } + function asRange(value) { + if (value === void 0 || value === null) { + return value; + } + return { start: asPosition(value.start), end: asPosition(value.end) }; + } + function asRanges(values) { + return values.map(asRange); + } + function asLocation(value) { + if (value === void 0 || value === null) { + return value; + } + return proto.Location.create(asUri(value.uri), asRange(value.range)); + } + function asDiagnosticSeverity(value) { + switch (value) { + case code.DiagnosticSeverity.Error: + return proto.DiagnosticSeverity.Error; + case code.DiagnosticSeverity.Warning: + return proto.DiagnosticSeverity.Warning; + case code.DiagnosticSeverity.Information: + return proto.DiagnosticSeverity.Information; + case code.DiagnosticSeverity.Hint: + return proto.DiagnosticSeverity.Hint; + } + } + function asDiagnosticTags(tags) { + if (!tags) { + return void 0; + } + let result = []; + for (let tag of tags) { + let converted = asDiagnosticTag(tag); + if (converted !== void 0) { + result.push(converted); + } + } + return result.length > 0 ? result : void 0; + } + function asDiagnosticTag(tag) { + switch (tag) { + case code.DiagnosticTag.Unnecessary: + return proto.DiagnosticTag.Unnecessary; + case code.DiagnosticTag.Deprecated: + return proto.DiagnosticTag.Deprecated; + default: + return void 0; + } + } + function asRelatedInformation(item) { + return { + message: item.message, + location: asLocation(item.location) + }; + } + function asRelatedInformations(items) { + return items.map(asRelatedInformation); + } + function asDiagnosticCode(value) { + if (value === void 0 || value === null) { + return void 0; + } + if (Is.number(value) || Is.string(value)) { + return value; + } + return { value: value.value, target: asUri(value.target) }; + } + function asDiagnostic(item) { + const result = proto.Diagnostic.create(asRange(item.range), item.message); + const protocolDiagnostic = item instanceof protocolDiagnostic_1.ProtocolDiagnostic ? item : void 0; + if (protocolDiagnostic !== void 0 && protocolDiagnostic.data !== void 0) { + result.data = protocolDiagnostic.data; + } + const code2 = asDiagnosticCode(item.code); + if (protocolDiagnostic_1.DiagnosticCode.is(code2)) { + if (protocolDiagnostic !== void 0 && protocolDiagnostic.hasDiagnosticCode) { + result.code = code2; + } else { + result.code = code2.value; + result.codeDescription = { href: code2.target }; + } + } else { + result.code = code2; + } + if (Is.number(item.severity)) { + result.severity = asDiagnosticSeverity(item.severity); + } + if (Array.isArray(item.tags)) { + result.tags = asDiagnosticTags(item.tags); + } + if (item.relatedInformation) { + result.relatedInformation = asRelatedInformations(item.relatedInformation); + } + if (item.source) { + result.source = item.source; + } + return result; + } + function asDiagnostics(items, token) { + if (items === void 0 || items === null) { + return items; + } + return async.map(items, asDiagnostic, token); + } + function asDiagnosticsSync(items) { + if (items === void 0 || items === null) { + return items; + } + return items.map(asDiagnostic); + } + function asDocumentation(format, documentation) { + switch (format) { + case "$string": + return documentation; + case proto.MarkupKind.PlainText: + return { kind: format, value: documentation }; + case proto.MarkupKind.Markdown: + return { kind: format, value: documentation.value }; + default: + return `Unsupported Markup content received. Kind is: ${format}`; + } + } + function asCompletionItemTag(tag) { + switch (tag) { + case code.CompletionItemTag.Deprecated: + return proto.CompletionItemTag.Deprecated; + } + return void 0; + } + function asCompletionItemTags(tags) { + if (tags === void 0) { + return tags; + } + const result = []; + for (let tag of tags) { + const converted = asCompletionItemTag(tag); + if (converted !== void 0) { + result.push(converted); + } + } + return result; + } + function asCompletionItemKind(value, original) { + if (original !== void 0) { + return original; + } + return value + 1; + } + function asCompletionItem(item, labelDetailsSupport = false) { + let label; + let labelDetails; + if (Is.string(item.label)) { + label = item.label; + } else { + label = item.label.label; + if (labelDetailsSupport && (item.label.detail !== void 0 || item.label.description !== void 0)) { + labelDetails = { detail: item.label.detail, description: item.label.description }; + } + } + let result = { label }; + if (labelDetails !== void 0) { + result.labelDetails = labelDetails; + } + let protocolItem = item instanceof protocolCompletionItem_1.default ? item : void 0; + if (item.detail) { + result.detail = item.detail; + } + if (item.documentation) { + if (!protocolItem || protocolItem.documentationFormat === "$string") { + result.documentation = item.documentation; + } else { + result.documentation = asDocumentation(protocolItem.documentationFormat, item.documentation); + } + } + if (item.filterText) { + result.filterText = item.filterText; + } + fillPrimaryInsertText(result, item); + if (Is.number(item.kind)) { + result.kind = asCompletionItemKind(item.kind, protocolItem && protocolItem.originalItemKind); + } + if (item.sortText) { + result.sortText = item.sortText; + } + if (item.additionalTextEdits) { + result.additionalTextEdits = asTextEdits(item.additionalTextEdits); + } + if (item.commitCharacters) { + result.commitCharacters = item.commitCharacters.slice(); + } + if (item.command) { + result.command = asCommand(item.command); + } + if (item.preselect === true || item.preselect === false) { + result.preselect = item.preselect; + } + const tags = asCompletionItemTags(item.tags); + if (protocolItem) { + if (protocolItem.data !== void 0) { + result.data = protocolItem.data; + } + if (protocolItem.deprecated === true || protocolItem.deprecated === false) { + if (protocolItem.deprecated === true && tags !== void 0 && tags.length > 0) { + const index = tags.indexOf(code.CompletionItemTag.Deprecated); + if (index !== -1) { + tags.splice(index, 1); + } + } + result.deprecated = protocolItem.deprecated; + } + if (protocolItem.insertTextMode !== void 0) { + result.insertTextMode = protocolItem.insertTextMode; + } + } + if (tags !== void 0 && tags.length > 0) { + result.tags = tags; + } + if (result.insertTextMode === void 0 && item.keepWhitespace === true) { + result.insertTextMode = proto.InsertTextMode.adjustIndentation; + } + return result; + } + function fillPrimaryInsertText(target, source) { + let format = proto.InsertTextFormat.PlainText; + let text = void 0; + let range = void 0; + if (source.textEdit) { + text = source.textEdit.newText; + range = source.textEdit.range; + } else if (source.insertText instanceof code.SnippetString) { + format = proto.InsertTextFormat.Snippet; + text = source.insertText.value; + } else { + text = source.insertText; + } + if (source.range) { + range = source.range; + } + target.insertTextFormat = format; + if (source.fromEdit && text !== void 0 && range !== void 0) { + target.textEdit = asCompletionTextEdit(text, range); + } else { + target.insertText = text; + } + } + function asCompletionTextEdit(newText, range) { + if (InsertReplaceRange.is(range)) { + return proto.InsertReplaceEdit.create(newText, asRange(range.inserting), asRange(range.replacing)); + } else { + return { newText, range: asRange(range) }; + } + } + function asTextEdit(edit) { + return { range: asRange(edit.range), newText: edit.newText }; + } + function asTextEdits(edits) { + if (edits === void 0 || edits === null) { + return edits; + } + return edits.map(asTextEdit); + } + function asSymbolKind(item) { + if (item <= code.SymbolKind.TypeParameter) { + return item + 1; + } + return proto.SymbolKind.Property; + } + function asSymbolTag(item) { + return item; + } + function asSymbolTags(items) { + return items.map(asSymbolTag); + } + function asReferenceParams(textDocument, position, options) { + return { + textDocument: asTextDocumentIdentifier(textDocument), + position: asWorkerPosition(position), + context: { includeDeclaration: options.includeDeclaration } + }; + } + async function asCodeAction(item, token) { + let result = proto.CodeAction.create(item.title); + if (item instanceof protocolCodeAction_1.default && item.data !== void 0) { + result.data = item.data; + } + if (item.kind !== void 0) { + result.kind = asCodeActionKind(item.kind); + } + if (item.diagnostics !== void 0) { + result.diagnostics = await asDiagnostics(item.diagnostics, token); + } + if (item.edit !== void 0) { + throw new Error(`VS Code code actions can only be converted to a protocol code action without an edit.`); + } + if (item.command !== void 0) { + result.command = asCommand(item.command); + } + if (item.isPreferred !== void 0) { + result.isPreferred = item.isPreferred; + } + if (item.disabled !== void 0) { + result.disabled = { reason: item.disabled.reason }; + } + return result; + } + function asCodeActionSync(item) { + let result = proto.CodeAction.create(item.title); + if (item instanceof protocolCodeAction_1.default && item.data !== void 0) { + result.data = item.data; + } + if (item.kind !== void 0) { + result.kind = asCodeActionKind(item.kind); + } + if (item.diagnostics !== void 0) { + result.diagnostics = asDiagnosticsSync(item.diagnostics); + } + if (item.edit !== void 0) { + throw new Error(`VS Code code actions can only be converted to a protocol code action without an edit.`); + } + if (item.command !== void 0) { + result.command = asCommand(item.command); + } + if (item.isPreferred !== void 0) { + result.isPreferred = item.isPreferred; + } + if (item.disabled !== void 0) { + result.disabled = { reason: item.disabled.reason }; + } + return result; + } + async function asCodeActionContext(context, token) { + if (context === void 0 || context === null) { + return context; + } + let only; + if (context.only && Is.string(context.only.value)) { + only = [context.only.value]; + } + return proto.CodeActionContext.create(await asDiagnostics(context.diagnostics, token), only, asCodeActionTriggerKind(context.triggerKind)); + } + function asCodeActionContextSync(context) { + if (context === void 0 || context === null) { + return context; + } + let only; + if (context.only && Is.string(context.only.value)) { + only = [context.only.value]; + } + return proto.CodeActionContext.create(asDiagnosticsSync(context.diagnostics), only, asCodeActionTriggerKind(context.triggerKind)); + } + function asCodeActionTriggerKind(kind) { + switch (kind) { + case code.CodeActionTriggerKind.Invoke: + return proto.CodeActionTriggerKind.Invoked; + case code.CodeActionTriggerKind.Automatic: + return proto.CodeActionTriggerKind.Automatic; + default: + return void 0; + } + } + function asCodeActionKind(item) { + if (item === void 0 || item === null) { + return void 0; + } + return item.value; + } + function asInlineValueContext(context) { + if (context === void 0 || context === null) { + return context; + } + return proto.InlineValueContext.create(context.frameId, asRange(context.stoppedLocation)); + } + function asInlineCompletionParams(document, position, context) { + return { + context: proto.InlineCompletionContext.create(context.triggerKind, context.selectedCompletionInfo), + textDocument: asTextDocumentIdentifier(document), + position: asPosition(position) + }; + } + function asCommand(item) { + let result = proto.Command.create(item.title, item.command); + if (item.arguments) { + result.arguments = item.arguments; + } + return result; + } + function asCodeLens(item) { + let result = proto.CodeLens.create(asRange(item.range)); + if (item.command) { + result.command = asCommand(item.command); + } + if (item instanceof protocolCodeLens_1.default) { + if (item.data) { + result.data = item.data; + } + } + return result; + } + function asFormattingOptions(options, fileOptions) { + const result = { tabSize: options.tabSize, insertSpaces: options.insertSpaces }; + if (fileOptions.trimTrailingWhitespace) { + result.trimTrailingWhitespace = true; + } + if (fileOptions.trimFinalNewlines) { + result.trimFinalNewlines = true; + } + if (fileOptions.insertFinalNewline) { + result.insertFinalNewline = true; + } + return result; + } + function asDocumentSymbolParams(textDocument) { + return { + textDocument: asTextDocumentIdentifier(textDocument) + }; + } + function asCodeLensParams(textDocument) { + return { + textDocument: asTextDocumentIdentifier(textDocument) + }; + } + function asDocumentLink(item) { + let result = proto.DocumentLink.create(asRange(item.range)); + if (item.target) { + result.target = asUri(item.target); + } + if (item.tooltip !== void 0) { + result.tooltip = item.tooltip; + } + let protocolItem = item instanceof protocolDocumentLink_1.default ? item : void 0; + if (protocolItem && protocolItem.data) { + result.data = protocolItem.data; + } + return result; + } + function asDocumentLinkParams(textDocument) { + return { + textDocument: asTextDocumentIdentifier(textDocument) + }; + } + function asCallHierarchyItem(value) { + const result = { + name: value.name, + kind: asSymbolKind(value.kind), + uri: asUri(value.uri), + range: asRange(value.range), + selectionRange: asRange(value.selectionRange) + }; + if (value.detail !== void 0 && value.detail.length > 0) { + result.detail = value.detail; + } + if (value.tags !== void 0) { + result.tags = asSymbolTags(value.tags); + } + if (value instanceof protocolCallHierarchyItem_1.default && value.data !== void 0) { + result.data = value.data; + } + return result; + } + function asTypeHierarchyItem(value) { + const result = { + name: value.name, + kind: asSymbolKind(value.kind), + uri: asUri(value.uri), + range: asRange(value.range), + selectionRange: asRange(value.selectionRange) + }; + if (value.detail !== void 0 && value.detail.length > 0) { + result.detail = value.detail; + } + if (value.tags !== void 0) { + result.tags = asSymbolTags(value.tags); + } + if (value instanceof protocolTypeHierarchyItem_1.default && value.data !== void 0) { + result.data = value.data; + } + return result; + } + function asWorkspaceSymbol(item) { + const result = item instanceof protocolWorkspaceSymbol_1.default ? { name: item.name, kind: asSymbolKind(item.kind), location: item.hasRange ? asLocation(item.location) : { uri: _uriConverter(item.location.uri) }, data: item.data } : { name: item.name, kind: asSymbolKind(item.kind), location: asLocation(item.location) }; + if (item.tags !== void 0) { + result.tags = asSymbolTags(item.tags); + } + if (item.containerName !== "") { + result.containerName = item.containerName; + } + return result; + } + function asInlayHint(item) { + const label = typeof item.label === "string" ? item.label : item.label.map(asInlayHintLabelPart); + const result = proto.InlayHint.create(asPosition(item.position), label); + if (item.kind !== void 0) { + result.kind = item.kind; + } + if (item.textEdits !== void 0) { + result.textEdits = asTextEdits(item.textEdits); + } + if (item.tooltip !== void 0) { + result.tooltip = asTooltip(item.tooltip); + } + if (item.paddingLeft !== void 0) { + result.paddingLeft = item.paddingLeft; + } + if (item.paddingRight !== void 0) { + result.paddingRight = item.paddingRight; + } + if (item instanceof protocolInlayHint_1.default && item.data !== void 0) { + result.data = item.data; + } + return result; + } + function asInlayHintLabelPart(item) { + const result = proto.InlayHintLabelPart.create(item.value); + if (item.location !== void 0) { + result.location = asLocation(item.location); + } + if (item.command !== void 0) { + result.command = asCommand(item.command); + } + if (item.tooltip !== void 0) { + result.tooltip = asTooltip(item.tooltip); + } + return result; + } + function asTooltip(value) { + if (typeof value === "string") { + return value; + } + const result = { + kind: proto.MarkupKind.Markdown, + value: value.value + }; + return result; + } + return { + asUri, + asTextDocumentIdentifier, + asTextDocumentItem, + asVersionedTextDocumentIdentifier, + asOpenTextDocumentParams, + asChangeTextDocumentParams, + asCloseTextDocumentParams, + asSaveTextDocumentParams, + asWillSaveTextDocumentParams, + asDidCreateFilesParams, + asDidRenameFilesParams, + asDidDeleteFilesParams, + asWillCreateFilesParams, + asWillRenameFilesParams, + asWillDeleteFilesParams, + asTextDocumentPositionParams, + asCompletionParams, + asSignatureHelpParams, + asWorkerPosition, + asRange, + asRanges, + asPosition, + asPositions, + asPositionsSync, + asLocation, + asDiagnosticSeverity, + asDiagnosticTag, + asDiagnostic, + asDiagnostics, + asDiagnosticsSync, + asCompletionItem, + asTextEdit, + asSymbolKind, + asSymbolTag, + asSymbolTags, + asReferenceParams, + asCodeAction, + asCodeActionSync, + asCodeActionContext, + asCodeActionContextSync, + asInlineValueContext, + asCommand, + asCodeLens, + asFormattingOptions, + asDocumentSymbolParams, + asCodeLensParams, + asDocumentLink, + asDocumentLinkParams, + asCallHierarchyItem, + asTypeHierarchyItem, + asInlayHint, + asWorkspaceSymbol, + asInlineCompletionParams + }; + } + exports2.createConverter = createConverter; + } +}); + +// node_modules/vscode-languageclient/lib/common/protocolConverter.js +var require_protocolConverter = __commonJS({ + "node_modules/vscode-languageclient/lib/common/protocolConverter.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createConverter = void 0; + var code = require("vscode"); + var ls = require_main3(); + var Is = require_is(); + var async = require_async(); + var protocolCompletionItem_1 = require_protocolCompletionItem(); + var protocolCodeLens_1 = require_protocolCodeLens(); + var protocolDocumentLink_1 = require_protocolDocumentLink(); + var protocolCodeAction_1 = require_protocolCodeAction(); + var protocolDiagnostic_1 = require_protocolDiagnostic(); + var protocolCallHierarchyItem_1 = require_protocolCallHierarchyItem(); + var protocolTypeHierarchyItem_1 = require_protocolTypeHierarchyItem(); + var protocolWorkspaceSymbol_1 = require_protocolWorkspaceSymbol(); + var protocolInlayHint_1 = require_protocolInlayHint(); + var vscode_languageserver_protocol_1 = require_main3(); + var CodeBlock; + (function(CodeBlock2) { + function is(value) { + let candidate = value; + return candidate && Is.string(candidate.language) && Is.string(candidate.value); + } + CodeBlock2.is = is; + })(CodeBlock || (CodeBlock = {})); + function createConverter(uriConverter, trustMarkdown, supportHtml) { + const nullConverter = (value) => code.Uri.parse(value); + const _uriConverter = uriConverter || nullConverter; + function asUri(value) { + return _uriConverter(value); + } + function asDocumentSelector(selector) { + const result = []; + for (const filter of selector) { + if (typeof filter === "string") { + result.push(filter); + } else if (vscode_languageserver_protocol_1.NotebookCellTextDocumentFilter.is(filter)) { + if (typeof filter.notebook === "string") { + result.push({ notebookType: filter.notebook, language: filter.language }); + } else { + const notebookType = filter.notebook.notebookType ?? "*"; + result.push({ notebookType, scheme: filter.notebook.scheme, pattern: filter.notebook.pattern, language: filter.language }); + } + } else if (vscode_languageserver_protocol_1.TextDocumentFilter.is(filter)) { + result.push({ language: filter.language, scheme: filter.scheme, pattern: filter.pattern }); + } + } + return result; + } + async function asDiagnostics(diagnostics, token) { + return async.map(diagnostics, asDiagnostic, token); + } + function asDiagnosticsSync(diagnostics) { + const result = new Array(diagnostics.length); + for (let i = 0; i < diagnostics.length; i++) { + result[i] = asDiagnostic(diagnostics[i]); + } + return result; + } + function asDiagnostic(diagnostic) { + let result = new protocolDiagnostic_1.ProtocolDiagnostic(asRange(diagnostic.range), diagnostic.message, asDiagnosticSeverity(diagnostic.severity), diagnostic.data); + if (diagnostic.code !== void 0) { + if (typeof diagnostic.code === "string" || typeof diagnostic.code === "number") { + if (ls.CodeDescription.is(diagnostic.codeDescription)) { + result.code = { + value: diagnostic.code, + target: asUri(diagnostic.codeDescription.href) + }; + } else { + result.code = diagnostic.code; + } + } else if (protocolDiagnostic_1.DiagnosticCode.is(diagnostic.code)) { + result.hasDiagnosticCode = true; + const diagnosticCode = diagnostic.code; + result.code = { + value: diagnosticCode.value, + target: asUri(diagnosticCode.target) + }; + } + } + if (diagnostic.source) { + result.source = diagnostic.source; + } + if (diagnostic.relatedInformation) { + result.relatedInformation = asRelatedInformation(diagnostic.relatedInformation); + } + if (Array.isArray(diagnostic.tags)) { + result.tags = asDiagnosticTags(diagnostic.tags); + } + return result; + } + function asRelatedInformation(relatedInformation) { + const result = new Array(relatedInformation.length); + for (let i = 0; i < relatedInformation.length; i++) { + const info = relatedInformation[i]; + result[i] = new code.DiagnosticRelatedInformation(asLocation(info.location), info.message); + } + return result; + } + function asDiagnosticTags(tags) { + if (!tags) { + return void 0; + } + let result = []; + for (let tag of tags) { + let converted = asDiagnosticTag(tag); + if (converted !== void 0) { + result.push(converted); + } + } + return result.length > 0 ? result : void 0; + } + function asDiagnosticTag(tag) { + switch (tag) { + case ls.DiagnosticTag.Unnecessary: + return code.DiagnosticTag.Unnecessary; + case ls.DiagnosticTag.Deprecated: + return code.DiagnosticTag.Deprecated; + default: + return void 0; + } + } + function asPosition(value) { + return value ? new code.Position(value.line, value.character) : void 0; + } + function asRange(value) { + return value ? new code.Range(value.start.line, value.start.character, value.end.line, value.end.character) : void 0; + } + async function asRanges(items, token) { + return async.map(items, (range) => { + return new code.Range(range.start.line, range.start.character, range.end.line, range.end.character); + }, token); + } + function asDiagnosticSeverity(value) { + if (value === void 0 || value === null) { + return code.DiagnosticSeverity.Error; + } + switch (value) { + case ls.DiagnosticSeverity.Error: + return code.DiagnosticSeverity.Error; + case ls.DiagnosticSeverity.Warning: + return code.DiagnosticSeverity.Warning; + case ls.DiagnosticSeverity.Information: + return code.DiagnosticSeverity.Information; + case ls.DiagnosticSeverity.Hint: + return code.DiagnosticSeverity.Hint; + } + return code.DiagnosticSeverity.Error; + } + function asHoverContent(value) { + if (Is.string(value)) { + return asMarkdownString(value); + } else if (CodeBlock.is(value)) { + let result = asMarkdownString(); + return result.appendCodeblock(value.value, value.language); + } else if (Array.isArray(value)) { + let result = []; + for (let element of value) { + let item = asMarkdownString(); + if (CodeBlock.is(element)) { + item.appendCodeblock(element.value, element.language); + } else { + item.appendMarkdown(element); + } + result.push(item); + } + return result; + } else { + return asMarkdownString(value); + } + } + function asDocumentation(value) { + if (Is.string(value)) { + return value; + } else { + switch (value.kind) { + case ls.MarkupKind.Markdown: + return asMarkdownString(value.value); + case ls.MarkupKind.PlainText: + return value.value; + default: + return `Unsupported Markup content received. Kind is: ${value.kind}`; + } + } + } + function asMarkdownString(value) { + let result; + if (value === void 0 || typeof value === "string") { + result = new code.MarkdownString(value); + } else { + switch (value.kind) { + case ls.MarkupKind.Markdown: + result = new code.MarkdownString(value.value); + break; + case ls.MarkupKind.PlainText: + result = new code.MarkdownString(); + result.appendText(value.value); + break; + default: + result = new code.MarkdownString(); + result.appendText(`Unsupported Markup content received. Kind is: ${value.kind}`); + break; + } + } + result.isTrusted = trustMarkdown; + result.supportHtml = supportHtml; + return result; + } + function asHover(hover) { + if (!hover) { + return void 0; + } + return new code.Hover(asHoverContent(hover.contents), asRange(hover.range)); + } + async function asCompletionResult(value, allCommitCharacters, token) { + if (!value) { + return void 0; + } + if (Array.isArray(value)) { + return async.map(value, (item) => asCompletionItem(item, allCommitCharacters), token); + } + const list = value; + const { defaultRange, commitCharacters } = getCompletionItemDefaults(list, allCommitCharacters); + const converted = await async.map(list.items, (item) => { + return asCompletionItem(item, commitCharacters, defaultRange, list.itemDefaults?.insertTextMode, list.itemDefaults?.insertTextFormat, list.itemDefaults?.data); + }, token); + return new code.CompletionList(converted, list.isIncomplete); + } + function getCompletionItemDefaults(list, allCommitCharacters) { + const rangeDefaults = list.itemDefaults?.editRange; + const commitCharacters = list.itemDefaults?.commitCharacters ?? allCommitCharacters; + return ls.Range.is(rangeDefaults) ? { defaultRange: asRange(rangeDefaults), commitCharacters } : rangeDefaults !== void 0 ? { defaultRange: { inserting: asRange(rangeDefaults.insert), replacing: asRange(rangeDefaults.replace) }, commitCharacters } : { defaultRange: void 0, commitCharacters }; + } + function asCompletionItemKind(value) { + if (ls.CompletionItemKind.Text <= value && value <= ls.CompletionItemKind.TypeParameter) { + return [value - 1, void 0]; + } + return [code.CompletionItemKind.Text, value]; + } + function asCompletionItemTag(tag) { + switch (tag) { + case ls.CompletionItemTag.Deprecated: + return code.CompletionItemTag.Deprecated; + } + return void 0; + } + function asCompletionItemTags(tags) { + if (tags === void 0 || tags === null) { + return []; + } + const result = []; + for (const tag of tags) { + const converted = asCompletionItemTag(tag); + if (converted !== void 0) { + result.push(converted); + } + } + return result; + } + function asCompletionItem(item, defaultCommitCharacters, defaultRange, defaultInsertTextMode, defaultInsertTextFormat, defaultData) { + const tags = asCompletionItemTags(item.tags); + const label = asCompletionItemLabel(item); + const result = new protocolCompletionItem_1.default(label); + if (item.detail) { + result.detail = item.detail; + } + if (item.documentation) { + result.documentation = asDocumentation(item.documentation); + result.documentationFormat = Is.string(item.documentation) ? "$string" : item.documentation.kind; + } + if (item.filterText) { + result.filterText = item.filterText; + } + const insertText = asCompletionInsertText(item, defaultRange, defaultInsertTextFormat); + if (insertText) { + result.insertText = insertText.text; + result.range = insertText.range; + result.fromEdit = insertText.fromEdit; + } + if (Is.number(item.kind)) { + let [itemKind, original] = asCompletionItemKind(item.kind); + result.kind = itemKind; + if (original) { + result.originalItemKind = original; + } + } + if (item.sortText) { + result.sortText = item.sortText; + } + if (item.additionalTextEdits) { + result.additionalTextEdits = asTextEditsSync(item.additionalTextEdits); + } + const commitCharacters = item.commitCharacters !== void 0 ? Is.stringArray(item.commitCharacters) ? item.commitCharacters : void 0 : defaultCommitCharacters; + if (commitCharacters) { + result.commitCharacters = commitCharacters.slice(); + } + if (item.command) { + result.command = asCommand(item.command); + } + if (item.deprecated === true || item.deprecated === false) { + result.deprecated = item.deprecated; + if (item.deprecated === true) { + tags.push(code.CompletionItemTag.Deprecated); + } + } + if (item.preselect === true || item.preselect === false) { + result.preselect = item.preselect; + } + const data = item.data ?? defaultData; + if (data !== void 0) { + result.data = data; + } + if (tags.length > 0) { + result.tags = tags; + } + const insertTextMode = item.insertTextMode ?? defaultInsertTextMode; + if (insertTextMode !== void 0) { + result.insertTextMode = insertTextMode; + if (insertTextMode === ls.InsertTextMode.asIs) { + result.keepWhitespace = true; + } + } + return result; + } + function asCompletionItemLabel(item) { + if (ls.CompletionItemLabelDetails.is(item.labelDetails)) { + return { + label: item.label, + detail: item.labelDetails.detail, + description: item.labelDetails.description + }; + } else { + return item.label; + } + } + function asCompletionInsertText(item, defaultRange, defaultInsertTextFormat) { + const insertTextFormat = item.insertTextFormat ?? defaultInsertTextFormat; + if (item.textEdit !== void 0 || defaultRange !== void 0) { + const [range, newText] = item.textEdit !== void 0 ? getCompletionRangeAndText(item.textEdit) : [defaultRange, item.textEditText ?? item.label]; + if (insertTextFormat === ls.InsertTextFormat.Snippet) { + return { text: new code.SnippetString(newText), range, fromEdit: true }; + } else { + return { text: newText, range, fromEdit: true }; + } + } else if (item.insertText) { + if (insertTextFormat === ls.InsertTextFormat.Snippet) { + return { text: new code.SnippetString(item.insertText), fromEdit: false }; + } else { + return { text: item.insertText, fromEdit: false }; + } + } else { + return void 0; + } + } + function getCompletionRangeAndText(value) { + if (ls.InsertReplaceEdit.is(value)) { + return [{ inserting: asRange(value.insert), replacing: asRange(value.replace) }, value.newText]; + } else { + return [asRange(value.range), value.newText]; + } + } + function asTextEdit(edit) { + if (!edit) { + return void 0; + } + return new code.TextEdit(asRange(edit.range), edit.newText); + } + async function asTextEdits(items, token) { + if (!items) { + return void 0; + } + return async.map(items, asTextEdit, token); + } + function asTextEditsSync(items) { + if (!items) { + return void 0; + } + const result = new Array(items.length); + for (let i = 0; i < items.length; i++) { + result[i] = asTextEdit(items[i]); + } + return result; + } + async function asSignatureHelp(item, token) { + if (!item) { + return void 0; + } + let result = new code.SignatureHelp(); + if (Is.number(item.activeSignature)) { + result.activeSignature = item.activeSignature; + } else { + result.activeSignature = 0; + } + if (Is.number(item.activeParameter)) { + result.activeParameter = item.activeParameter; + } else { + result.activeParameter = 0; + } + if (item.signatures) { + result.signatures = await asSignatureInformations(item.signatures, token); + } + return result; + } + async function asSignatureInformations(items, token) { + return async.mapAsync(items, asSignatureInformation, token); + } + async function asSignatureInformation(item, token) { + let result = new code.SignatureInformation(item.label); + if (item.documentation !== void 0) { + result.documentation = asDocumentation(item.documentation); + } + if (item.parameters !== void 0) { + result.parameters = await asParameterInformations(item.parameters, token); + } + if (item.activeParameter !== void 0) { + result.activeParameter = item.activeParameter; + } + { + return result; + } + } + function asParameterInformations(items, token) { + return async.map(items, asParameterInformation, token); + } + function asParameterInformation(item) { + let result = new code.ParameterInformation(item.label); + if (item.documentation) { + result.documentation = asDocumentation(item.documentation); + } + return result; + } + function asLocation(item) { + return item ? new code.Location(_uriConverter(item.uri), asRange(item.range)) : void 0; + } + async function asDeclarationResult(item, token) { + if (!item) { + return void 0; + } + return asLocationResult(item, token); + } + async function asDefinitionResult(item, token) { + if (!item) { + return void 0; + } + return asLocationResult(item, token); + } + function asLocationLink(item) { + if (!item) { + return void 0; + } + let result = { + targetUri: _uriConverter(item.targetUri), + targetRange: asRange(item.targetRange), + originSelectionRange: asRange(item.originSelectionRange), + targetSelectionRange: asRange(item.targetSelectionRange) + }; + if (!result.targetSelectionRange) { + throw new Error(`targetSelectionRange must not be undefined or null`); + } + return result; + } + async function asLocationResult(item, token) { + if (!item) { + return void 0; + } + if (Is.array(item)) { + if (item.length === 0) { + return []; + } else if (ls.LocationLink.is(item[0])) { + const links = item; + return async.map(links, asLocationLink, token); + } else { + const locations = item; + return async.map(locations, asLocation, token); + } + } else if (ls.LocationLink.is(item)) { + return [asLocationLink(item)]; + } else { + return asLocation(item); + } + } + async function asReferences(values, token) { + if (!values) { + return void 0; + } + return async.map(values, asLocation, token); + } + async function asDocumentHighlights(values, token) { + if (!values) { + return void 0; + } + return async.map(values, asDocumentHighlight, token); + } + function asDocumentHighlight(item) { + let result = new code.DocumentHighlight(asRange(item.range)); + if (Is.number(item.kind)) { + result.kind = asDocumentHighlightKind(item.kind); + } + return result; + } + function asDocumentHighlightKind(item) { + switch (item) { + case ls.DocumentHighlightKind.Text: + return code.DocumentHighlightKind.Text; + case ls.DocumentHighlightKind.Read: + return code.DocumentHighlightKind.Read; + case ls.DocumentHighlightKind.Write: + return code.DocumentHighlightKind.Write; + } + return code.DocumentHighlightKind.Text; + } + async function asSymbolInformations(values, token) { + if (!values) { + return void 0; + } + return async.map(values, asSymbolInformation, token); + } + function asSymbolKind(item) { + if (item <= ls.SymbolKind.TypeParameter) { + return item - 1; + } + return code.SymbolKind.Property; + } + function asSymbolTag(value) { + switch (value) { + case ls.SymbolTag.Deprecated: + return code.SymbolTag.Deprecated; + default: + return void 0; + } + } + function asSymbolTags(items) { + if (items === void 0 || items === null) { + return void 0; + } + const result = []; + for (const item of items) { + const converted = asSymbolTag(item); + if (converted !== void 0) { + result.push(converted); + } + } + return result.length === 0 ? void 0 : result; + } + function asSymbolInformation(item) { + const data = item.data; + const location = item.location; + const result = location.range === void 0 || data !== void 0 ? new protocolWorkspaceSymbol_1.default(item.name, asSymbolKind(item.kind), item.containerName ?? "", location.range === void 0 ? _uriConverter(location.uri) : new code.Location(_uriConverter(item.location.uri), asRange(location.range)), data) : new code.SymbolInformation(item.name, asSymbolKind(item.kind), item.containerName ?? "", new code.Location(_uriConverter(item.location.uri), asRange(location.range))); + fillTags(result, item); + return result; + } + async function asDocumentSymbols(values, token) { + if (values === void 0 || values === null) { + return void 0; + } + return async.map(values, asDocumentSymbol, token); + } + function asDocumentSymbol(value) { + let result = new code.DocumentSymbol(value.name, value.detail || "", asSymbolKind(value.kind), asRange(value.range), asRange(value.selectionRange)); + fillTags(result, value); + if (value.children !== void 0 && value.children.length > 0) { + let children = []; + for (let child of value.children) { + children.push(asDocumentSymbol(child)); + } + result.children = children; + } + return result; + } + function fillTags(result, value) { + result.tags = asSymbolTags(value.tags); + if (value.deprecated) { + if (!result.tags) { + result.tags = [code.SymbolTag.Deprecated]; + } else { + if (!result.tags.includes(code.SymbolTag.Deprecated)) { + result.tags = result.tags.concat(code.SymbolTag.Deprecated); + } + } + } + } + function asCommand(item) { + let result = { title: item.title, command: item.command }; + if (item.arguments) { + result.arguments = item.arguments; + } + return result; + } + async function asCommands(items, token) { + if (!items) { + return void 0; + } + return async.map(items, asCommand, token); + } + const kindMapping = /* @__PURE__ */ new Map(); + kindMapping.set(ls.CodeActionKind.Empty, code.CodeActionKind.Empty); + kindMapping.set(ls.CodeActionKind.QuickFix, code.CodeActionKind.QuickFix); + kindMapping.set(ls.CodeActionKind.Refactor, code.CodeActionKind.Refactor); + kindMapping.set(ls.CodeActionKind.RefactorExtract, code.CodeActionKind.RefactorExtract); + kindMapping.set(ls.CodeActionKind.RefactorInline, code.CodeActionKind.RefactorInline); + kindMapping.set(ls.CodeActionKind.RefactorRewrite, code.CodeActionKind.RefactorRewrite); + kindMapping.set(ls.CodeActionKind.Source, code.CodeActionKind.Source); + kindMapping.set(ls.CodeActionKind.SourceOrganizeImports, code.CodeActionKind.SourceOrganizeImports); + function asCodeActionKind(item) { + if (item === void 0 || item === null) { + return void 0; + } + let result = kindMapping.get(item); + if (result) { + return result; + } + let parts = item.split("."); + result = code.CodeActionKind.Empty; + for (let part of parts) { + result = result.append(part); + } + return result; + } + function asCodeActionKinds(items) { + if (items === void 0 || items === null) { + return void 0; + } + return items.map((kind) => asCodeActionKind(kind)); + } + async function asCodeAction(item, token) { + if (item === void 0 || item === null) { + return void 0; + } + let result = new protocolCodeAction_1.default(item.title, item.data); + if (item.kind !== void 0) { + result.kind = asCodeActionKind(item.kind); + } + if (item.diagnostics !== void 0) { + result.diagnostics = asDiagnosticsSync(item.diagnostics); + } + if (item.edit !== void 0) { + result.edit = await asWorkspaceEdit(item.edit, token); + } + if (item.command !== void 0) { + result.command = asCommand(item.command); + } + if (item.isPreferred !== void 0) { + result.isPreferred = item.isPreferred; + } + if (item.disabled !== void 0) { + result.disabled = { reason: item.disabled.reason }; + } + return result; + } + function asCodeActionResult(items, token) { + return async.mapAsync(items, async (item) => { + if (ls.Command.is(item)) { + return asCommand(item); + } else { + return asCodeAction(item, token); + } + }, token); + } + function asCodeLens(item) { + if (!item) { + return void 0; + } + let result = new protocolCodeLens_1.default(asRange(item.range)); + if (item.command) { + result.command = asCommand(item.command); + } + if (item.data !== void 0 && item.data !== null) { + result.data = item.data; + } + return result; + } + async function asCodeLenses(items, token) { + if (!items) { + return void 0; + } + return async.map(items, asCodeLens, token); + } + async function asWorkspaceEdit(item, token) { + if (!item) { + return void 0; + } + const sharedMetadata = /* @__PURE__ */ new Map(); + if (item.changeAnnotations !== void 0) { + const changeAnnotations = item.changeAnnotations; + await async.forEach(Object.keys(changeAnnotations), (key) => { + const metaData = asWorkspaceEditEntryMetadata(changeAnnotations[key]); + sharedMetadata.set(key, metaData); + }, token); + } + const asMetadata = (annotation) => { + if (annotation === void 0) { + return void 0; + } else { + return sharedMetadata.get(annotation); + } + }; + const result = new code.WorkspaceEdit(); + if (item.documentChanges) { + const documentChanges = item.documentChanges; + await async.forEach(documentChanges, (change) => { + if (ls.CreateFile.is(change)) { + result.createFile(_uriConverter(change.uri), change.options, asMetadata(change.annotationId)); + } else if (ls.RenameFile.is(change)) { + result.renameFile(_uriConverter(change.oldUri), _uriConverter(change.newUri), change.options, asMetadata(change.annotationId)); + } else if (ls.DeleteFile.is(change)) { + result.deleteFile(_uriConverter(change.uri), change.options, asMetadata(change.annotationId)); + } else if (ls.TextDocumentEdit.is(change)) { + const uri = _uriConverter(change.textDocument.uri); + for (const edit of change.edits) { + if (ls.AnnotatedTextEdit.is(edit)) { + result.replace(uri, asRange(edit.range), edit.newText, asMetadata(edit.annotationId)); + } else { + result.replace(uri, asRange(edit.range), edit.newText); + } + } + } else { + throw new Error(`Unknown workspace edit change received: +${JSON.stringify(change, void 0, 4)}`); + } + }, token); + } else if (item.changes) { + const changes = item.changes; + await async.forEach(Object.keys(changes), (key) => { + result.set(_uriConverter(key), asTextEditsSync(changes[key])); + }, token); + } + return result; + } + function asWorkspaceEditEntryMetadata(annotation) { + if (annotation === void 0) { + return void 0; + } + return { label: annotation.label, needsConfirmation: !!annotation.needsConfirmation, description: annotation.description }; + } + function asDocumentLink(item) { + let range = asRange(item.range); + let target = item.target ? asUri(item.target) : void 0; + let link = new protocolDocumentLink_1.default(range, target); + if (item.tooltip !== void 0) { + link.tooltip = item.tooltip; + } + if (item.data !== void 0 && item.data !== null) { + link.data = item.data; + } + return link; + } + async function asDocumentLinks(items, token) { + if (!items) { + return void 0; + } + return async.map(items, asDocumentLink, token); + } + function asColor(color) { + return new code.Color(color.red, color.green, color.blue, color.alpha); + } + function asColorInformation(ci) { + return new code.ColorInformation(asRange(ci.range), asColor(ci.color)); + } + async function asColorInformations(colorInformation, token) { + if (!colorInformation) { + return void 0; + } + return async.map(colorInformation, asColorInformation, token); + } + function asColorPresentation(cp2) { + let presentation = new code.ColorPresentation(cp2.label); + presentation.additionalTextEdits = asTextEditsSync(cp2.additionalTextEdits); + if (cp2.textEdit) { + presentation.textEdit = asTextEdit(cp2.textEdit); + } + return presentation; + } + async function asColorPresentations(colorPresentations, token) { + if (!colorPresentations) { + return void 0; + } + return async.map(colorPresentations, asColorPresentation, token); + } + function asFoldingRangeKind(kind) { + if (kind) { + switch (kind) { + case ls.FoldingRangeKind.Comment: + return code.FoldingRangeKind.Comment; + case ls.FoldingRangeKind.Imports: + return code.FoldingRangeKind.Imports; + case ls.FoldingRangeKind.Region: + return code.FoldingRangeKind.Region; + } + } + return void 0; + } + function asFoldingRange(r) { + return new code.FoldingRange(r.startLine, r.endLine, asFoldingRangeKind(r.kind)); + } + async function asFoldingRanges(foldingRanges, token) { + if (!foldingRanges) { + return void 0; + } + return async.map(foldingRanges, asFoldingRange, token); + } + function asSelectionRange(selectionRange) { + return new code.SelectionRange(asRange(selectionRange.range), selectionRange.parent ? asSelectionRange(selectionRange.parent) : void 0); + } + async function asSelectionRanges(selectionRanges, token) { + if (!Array.isArray(selectionRanges)) { + return []; + } + return async.map(selectionRanges, asSelectionRange, token); + } + function asInlineValue(inlineValue) { + if (ls.InlineValueText.is(inlineValue)) { + return new code.InlineValueText(asRange(inlineValue.range), inlineValue.text); + } else if (ls.InlineValueVariableLookup.is(inlineValue)) { + return new code.InlineValueVariableLookup(asRange(inlineValue.range), inlineValue.variableName, inlineValue.caseSensitiveLookup); + } else { + return new code.InlineValueEvaluatableExpression(asRange(inlineValue.range), inlineValue.expression); + } + } + async function asInlineValues(inlineValues, token) { + if (!Array.isArray(inlineValues)) { + return []; + } + return async.map(inlineValues, asInlineValue, token); + } + async function asInlayHint(value, token) { + const label = typeof value.label === "string" ? value.label : await async.map(value.label, asInlayHintLabelPart, token); + const result = new protocolInlayHint_1.default(asPosition(value.position), label); + if (value.kind !== void 0) { + result.kind = value.kind; + } + if (value.textEdits !== void 0) { + result.textEdits = await asTextEdits(value.textEdits, token); + } + if (value.tooltip !== void 0) { + result.tooltip = asTooltip(value.tooltip); + } + if (value.paddingLeft !== void 0) { + result.paddingLeft = value.paddingLeft; + } + if (value.paddingRight !== void 0) { + result.paddingRight = value.paddingRight; + } + if (value.data !== void 0) { + result.data = value.data; + } + return result; + } + function asInlayHintLabelPart(part) { + const result = new code.InlayHintLabelPart(part.value); + if (part.location !== void 0) { + result.location = asLocation(part.location); + } + if (part.tooltip !== void 0) { + result.tooltip = asTooltip(part.tooltip); + } + if (part.command !== void 0) { + result.command = asCommand(part.command); + } + return result; + } + function asTooltip(value) { + if (typeof value === "string") { + return value; + } + return asMarkdownString(value); + } + async function asInlayHints(values, token) { + if (!Array.isArray(values)) { + return void 0; + } + return async.mapAsync(values, asInlayHint, token); + } + function asCallHierarchyItem(item) { + if (item === null) { + return void 0; + } + const result = new protocolCallHierarchyItem_1.default(asSymbolKind(item.kind), item.name, item.detail || "", asUri(item.uri), asRange(item.range), asRange(item.selectionRange), item.data); + if (item.tags !== void 0) { + result.tags = asSymbolTags(item.tags); + } + return result; + } + async function asCallHierarchyItems(items, token) { + if (items === null) { + return void 0; + } + return async.map(items, asCallHierarchyItem, token); + } + async function asCallHierarchyIncomingCall(item, token) { + return new code.CallHierarchyIncomingCall(asCallHierarchyItem(item.from), await asRanges(item.fromRanges, token)); + } + async function asCallHierarchyIncomingCalls(items, token) { + if (items === null) { + return void 0; + } + return async.mapAsync(items, asCallHierarchyIncomingCall, token); + } + async function asCallHierarchyOutgoingCall(item, token) { + return new code.CallHierarchyOutgoingCall(asCallHierarchyItem(item.to), await asRanges(item.fromRanges, token)); + } + async function asCallHierarchyOutgoingCalls(items, token) { + if (items === null) { + return void 0; + } + return async.mapAsync(items, asCallHierarchyOutgoingCall, token); + } + async function asSemanticTokens(value, _token) { + if (value === void 0 || value === null) { + return void 0; + } + return new code.SemanticTokens(new Uint32Array(value.data), value.resultId); + } + function asSemanticTokensEdit(value) { + return new code.SemanticTokensEdit(value.start, value.deleteCount, value.data !== void 0 ? new Uint32Array(value.data) : void 0); + } + async function asSemanticTokensEdits(value, _token) { + if (value === void 0 || value === null) { + return void 0; + } + return new code.SemanticTokensEdits(value.edits.map(asSemanticTokensEdit), value.resultId); + } + function asSemanticTokensLegend(value) { + return value; + } + async function asLinkedEditingRanges(value, token) { + if (value === null || value === void 0) { + return void 0; + } + return new code.LinkedEditingRanges(await asRanges(value.ranges, token), asRegularExpression(value.wordPattern)); + } + function asRegularExpression(value) { + if (value === null || value === void 0) { + return void 0; + } + return new RegExp(value); + } + function asTypeHierarchyItem(item) { + if (item === null) { + return void 0; + } + let result = new protocolTypeHierarchyItem_1.default(asSymbolKind(item.kind), item.name, item.detail || "", asUri(item.uri), asRange(item.range), asRange(item.selectionRange), item.data); + if (item.tags !== void 0) { + result.tags = asSymbolTags(item.tags); + } + return result; + } + async function asTypeHierarchyItems(items, token) { + if (items === null) { + return void 0; + } + return async.map(items, asTypeHierarchyItem, token); + } + function asGlobPattern(pattern) { + if (Is.string(pattern)) { + return pattern; + } + if (ls.RelativePattern.is(pattern)) { + if (ls.URI.is(pattern.baseUri)) { + return new code.RelativePattern(asUri(pattern.baseUri), pattern.pattern); + } else if (ls.WorkspaceFolder.is(pattern.baseUri)) { + const workspaceFolder = code.workspace.getWorkspaceFolder(asUri(pattern.baseUri.uri)); + return workspaceFolder !== void 0 ? new code.RelativePattern(workspaceFolder, pattern.pattern) : void 0; + } + } + return void 0; + } + async function asInlineCompletionResult(value, token) { + if (!value) { + return void 0; + } + if (Array.isArray(value)) { + return async.map(value, (item) => asInlineCompletionItem(item), token); + } + const list = value; + const converted = await async.map(list.items, (item) => { + return asInlineCompletionItem(item); + }, token); + return new code.InlineCompletionList(converted); + } + function asInlineCompletionItem(item) { + let insertText; + if (typeof item.insertText === "string") { + insertText = item.insertText; + } else { + insertText = new code.SnippetString(item.insertText.value); + } + let command = void 0; + if (item.command) { + command = asCommand(item.command); + } + const inlineCompletionItem = new code.InlineCompletionItem(insertText, asRange(item.range), command); + if (item.filterText) { + inlineCompletionItem.filterText = item.filterText; + } + return inlineCompletionItem; + } + return { + asUri, + asDocumentSelector, + asDiagnostics, + asDiagnostic, + asRange, + asRanges, + asPosition, + asDiagnosticSeverity, + asDiagnosticTag, + asHover, + asCompletionResult, + asCompletionItem, + asTextEdit, + asTextEdits, + asSignatureHelp, + asSignatureInformations, + asSignatureInformation, + asParameterInformations, + asParameterInformation, + asDeclarationResult, + asDefinitionResult, + asLocation, + asReferences, + asDocumentHighlights, + asDocumentHighlight, + asDocumentHighlightKind, + asSymbolKind, + asSymbolTag, + asSymbolTags, + asSymbolInformations, + asSymbolInformation, + asDocumentSymbols, + asDocumentSymbol, + asCommand, + asCommands, + asCodeAction, + asCodeActionKind, + asCodeActionKinds, + asCodeActionResult, + asCodeLens, + asCodeLenses, + asWorkspaceEdit, + asDocumentLink, + asDocumentLinks, + asFoldingRangeKind, + asFoldingRange, + asFoldingRanges, + asColor, + asColorInformation, + asColorInformations, + asColorPresentation, + asColorPresentations, + asSelectionRange, + asSelectionRanges, + asInlineValue, + asInlineValues, + asInlayHint, + asInlayHints, + asSemanticTokensLegend, + asSemanticTokens, + asSemanticTokensEdit, + asSemanticTokensEdits, + asCallHierarchyItem, + asCallHierarchyItems, + asCallHierarchyIncomingCall, + asCallHierarchyIncomingCalls, + asCallHierarchyOutgoingCall, + asCallHierarchyOutgoingCalls, + asLinkedEditingRanges, + asTypeHierarchyItem, + asTypeHierarchyItems, + asGlobPattern, + asInlineCompletionResult, + asInlineCompletionItem + }; + } + exports2.createConverter = createConverter; + } +}); + +// node_modules/vscode-languageclient/lib/common/utils/uuid.js +var require_uuid = __commonJS({ + "node_modules/vscode-languageclient/lib/common/utils/uuid.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.generateUuid = exports2.parse = exports2.isUUID = exports2.v4 = exports2.empty = void 0; + var ValueUUID = class { + constructor(_value) { + this._value = _value; + } + asHex() { + return this._value; + } + equals(other) { + return this.asHex() === other.asHex(); + } + }; + var V4UUID = class _V4UUID extends ValueUUID { + static _oneOf(array) { + return array[Math.floor(array.length * Math.random())]; + } + static _randomHex() { + return _V4UUID._oneOf(_V4UUID._chars); + } + constructor() { + super([ + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + "-", + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + "-", + "4", + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + "-", + _V4UUID._oneOf(_V4UUID._timeHighBits), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + "-", + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex(), + _V4UUID._randomHex() + ].join("")); + } + }; + V4UUID._chars = ["0", "1", "2", "3", "4", "5", "6", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + V4UUID._timeHighBits = ["8", "9", "a", "b"]; + exports2.empty = new ValueUUID("00000000-0000-0000-0000-000000000000"); + function v4() { + return new V4UUID(); + } + exports2.v4 = v4; + var _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + function isUUID(value) { + return _UUIDPattern.test(value); + } + exports2.isUUID = isUUID; + function parse(value) { + if (!isUUID(value)) { + throw new Error("invalid uuid"); + } + return new ValueUUID(value); + } + exports2.parse = parse; + function generateUuid() { + return v4().asHex(); + } + exports2.generateUuid = generateUuid; + } +}); + +// node_modules/vscode-languageclient/lib/common/progressPart.js +var require_progressPart = __commonJS({ + "node_modules/vscode-languageclient/lib/common/progressPart.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ProgressPart = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var Is = require_is(); + var ProgressPart = class { + constructor(_client, _token, done) { + this._client = _client; + this._token = _token; + this._reported = 0; + this._infinite = false; + this._lspProgressDisposable = this._client.onProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, (value) => { + switch (value.kind) { + case "begin": + this.begin(value); + break; + case "report": + this.report(value); + break; + case "end": + this.done(); + done && done(this); + break; + } + }); + } + begin(params) { + this._infinite = params.percentage === void 0; + if (this._lspProgressDisposable === void 0) { + return; + } + void vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Window, cancellable: params.cancellable, title: params.title }, async (progress, cancellationToken) => { + if (this._lspProgressDisposable === void 0) { + return; + } + this._progress = progress; + this._cancellationToken = cancellationToken; + this._tokenDisposable = this._cancellationToken.onCancellationRequested(() => { + this._client.sendNotification(vscode_languageserver_protocol_1.WorkDoneProgressCancelNotification.type, { token: this._token }); + }); + this.report(params); + return new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + }); + } + report(params) { + if (this._infinite && Is.string(params.message)) { + this._progress !== void 0 && this._progress.report({ message: params.message }); + } else if (Is.number(params.percentage)) { + const percentage = Math.max(0, Math.min(params.percentage, 100)); + const delta = Math.max(0, percentage - this._reported); + this._reported += delta; + this._progress !== void 0 && this._progress.report({ message: params.message, increment: delta }); + } + } + cancel() { + this.cleanup(); + if (this._reject !== void 0) { + this._reject(); + this._resolve = void 0; + this._reject = void 0; + } + } + done() { + this.cleanup(); + if (this._resolve !== void 0) { + this._resolve(); + this._resolve = void 0; + this._reject = void 0; + } + } + cleanup() { + if (this._lspProgressDisposable !== void 0) { + this._lspProgressDisposable.dispose(); + this._lspProgressDisposable = void 0; + } + if (this._tokenDisposable !== void 0) { + this._tokenDisposable.dispose(); + this._tokenDisposable = void 0; + } + this._progress = void 0; + this._cancellationToken = void 0; + } + }; + exports2.ProgressPart = ProgressPart; + } +}); + +// node_modules/vscode-languageclient/lib/common/features.js +var require_features = __commonJS({ + "node_modules/vscode-languageclient/lib/common/features.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WorkspaceFeature = exports2.TextDocumentLanguageFeature = exports2.TextDocumentEventFeature = exports2.DynamicDocumentFeature = exports2.DynamicFeature = exports2.StaticFeature = exports2.ensure = exports2.LSPCancellationError = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var Is = require_is(); + var UUID = require_uuid(); + var LSPCancellationError = class extends vscode_1.CancellationError { + constructor(data) { + super(); + this.data = data; + } + }; + exports2.LSPCancellationError = LSPCancellationError; + function ensure(target, key) { + if (target[key] === void 0) { + target[key] = {}; + } + return target[key]; + } + exports2.ensure = ensure; + var StaticFeature; + (function(StaticFeature2) { + function is(value) { + const candidate = value; + return candidate !== void 0 && candidate !== null && Is.func(candidate.fillClientCapabilities) && Is.func(candidate.initialize) && Is.func(candidate.getState) && Is.func(candidate.clear) && (candidate.fillInitializeParams === void 0 || Is.func(candidate.fillInitializeParams)); + } + StaticFeature2.is = is; + })(StaticFeature || (exports2.StaticFeature = StaticFeature = {})); + var DynamicFeature; + (function(DynamicFeature2) { + function is(value) { + const candidate = value; + return candidate !== void 0 && candidate !== null && Is.func(candidate.fillClientCapabilities) && Is.func(candidate.initialize) && Is.func(candidate.getState) && Is.func(candidate.clear) && (candidate.fillInitializeParams === void 0 || Is.func(candidate.fillInitializeParams)) && Is.func(candidate.register) && Is.func(candidate.unregister) && candidate.registrationType !== void 0; + } + DynamicFeature2.is = is; + })(DynamicFeature || (exports2.DynamicFeature = DynamicFeature = {})); + var DynamicDocumentFeature = class { + constructor(client2) { + this._client = client2; + } + /** + * Returns the state the feature is in. + */ + getState() { + const selectors = this.getDocumentSelectors(); + let count = 0; + for (const selector of selectors) { + count++; + for (const document of vscode_1.workspace.textDocuments) { + if (vscode_1.languages.match(selector, document) > 0) { + return { kind: "document", id: this.registrationType.method, registrations: true, matches: true }; + } + } + } + const registrations = count > 0; + return { kind: "document", id: this.registrationType.method, registrations, matches: false }; + } + }; + exports2.DynamicDocumentFeature = DynamicDocumentFeature; + var TextDocumentEventFeature = class extends DynamicDocumentFeature { + static textDocumentFilter(selectors, textDocument) { + for (const selector of selectors) { + if (vscode_1.languages.match(selector, textDocument) > 0) { + return true; + } + } + return false; + } + constructor(client2, event, type, middleware, createParams, textDocument, selectorFilter) { + super(client2); + this._event = event; + this._type = type; + this._middleware = middleware; + this._createParams = createParams; + this._textDocument = textDocument; + this._selectorFilter = selectorFilter; + this._selectors = /* @__PURE__ */ new Map(); + this._onNotificationSent = new vscode_1.EventEmitter(); + } + getStateInfo() { + return [this._selectors.values(), false]; + } + getDocumentSelectors() { + return this._selectors.values(); + } + register(data) { + if (!data.registerOptions.documentSelector) { + return; + } + if (!this._listener) { + this._listener = this._event((data2) => { + this.callback(data2).catch((error) => { + this._client.error(`Sending document notification ${this._type.method} failed.`, error); + }); + }); + } + this._selectors.set(data.id, this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector)); + } + async callback(data) { + const doSend = async (data2) => { + const params = this._createParams(data2); + await this._client.sendNotification(this._type, params); + this.notificationSent(this.getTextDocument(data2), this._type, params); + }; + if (this.matches(data)) { + const middleware = this._middleware(); + return middleware ? middleware(data, (data2) => doSend(data2)) : doSend(data); + } + } + matches(data) { + if (this._client.hasDedicatedTextSynchronizationFeature(this._textDocument(data))) { + return false; + } + return !this._selectorFilter || this._selectorFilter(this._selectors.values(), data); + } + get onNotificationSent() { + return this._onNotificationSent.event; + } + notificationSent(textDocument, type, params) { + this._onNotificationSent.fire({ textDocument, type, params }); + } + unregister(id) { + this._selectors.delete(id); + if (this._selectors.size === 0 && this._listener) { + this._listener.dispose(); + this._listener = void 0; + } + } + clear() { + this._selectors.clear(); + this._onNotificationSent.dispose(); + if (this._listener) { + this._listener.dispose(); + this._listener = void 0; + } + } + getProvider(document) { + for (const selector of this._selectors.values()) { + if (vscode_1.languages.match(selector, document) > 0) { + return { + send: (data) => { + return this.callback(data); + } + }; + } + } + return void 0; + } + }; + exports2.TextDocumentEventFeature = TextDocumentEventFeature; + var TextDocumentLanguageFeature = class extends DynamicDocumentFeature { + constructor(client2, registrationType) { + super(client2); + this._registrationType = registrationType; + this._registrations = /* @__PURE__ */ new Map(); + } + *getDocumentSelectors() { + for (const registration of this._registrations.values()) { + const selector = registration.data.registerOptions.documentSelector; + if (selector === null) { + continue; + } + yield this._client.protocol2CodeConverter.asDocumentSelector(selector); + } + } + get registrationType() { + return this._registrationType; + } + register(data) { + if (!data.registerOptions.documentSelector) { + return; + } + let registration = this.registerLanguageProvider(data.registerOptions, data.id); + this._registrations.set(data.id, { disposable: registration[0], data, provider: registration[1] }); + } + unregister(id) { + let registration = this._registrations.get(id); + if (registration !== void 0) { + registration.disposable.dispose(); + } + } + clear() { + this._registrations.forEach((value) => { + value.disposable.dispose(); + }); + this._registrations.clear(); + } + getRegistration(documentSelector, capability) { + if (!capability) { + return [void 0, void 0]; + } else if (vscode_languageserver_protocol_1.TextDocumentRegistrationOptions.is(capability)) { + const id = vscode_languageserver_protocol_1.StaticRegistrationOptions.hasId(capability) ? capability.id : UUID.generateUuid(); + const selector = capability.documentSelector ?? documentSelector; + if (selector) { + return [id, Object.assign({}, capability, { documentSelector: selector })]; + } + } else if (Is.boolean(capability) && capability === true || vscode_languageserver_protocol_1.WorkDoneProgressOptions.is(capability)) { + if (!documentSelector) { + return [void 0, void 0]; + } + const options = Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector }); + return [UUID.generateUuid(), options]; + } + return [void 0, void 0]; + } + getRegistrationOptions(documentSelector, capability) { + if (!documentSelector || !capability) { + return void 0; + } + return Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector }); + } + getProvider(textDocument) { + for (const registration of this._registrations.values()) { + let selector = registration.data.registerOptions.documentSelector; + if (selector !== null && vscode_1.languages.match(this._client.protocol2CodeConverter.asDocumentSelector(selector), textDocument) > 0) { + return registration.provider; + } + } + return void 0; + } + getAllProviders() { + const result = []; + for (const item of this._registrations.values()) { + result.push(item.provider); + } + return result; + } + }; + exports2.TextDocumentLanguageFeature = TextDocumentLanguageFeature; + var WorkspaceFeature = class { + constructor(client2, registrationType) { + this._client = client2; + this._registrationType = registrationType; + this._registrations = /* @__PURE__ */ new Map(); + } + getState() { + const registrations = this._registrations.size > 0; + return { kind: "workspace", id: this._registrationType.method, registrations }; + } + get registrationType() { + return this._registrationType; + } + register(data) { + const registration = this.registerLanguageProvider(data.registerOptions); + this._registrations.set(data.id, { disposable: registration[0], provider: registration[1] }); + } + unregister(id) { + let registration = this._registrations.get(id); + if (registration !== void 0) { + registration.disposable.dispose(); + } + } + clear() { + this._registrations.forEach((registration) => { + registration.disposable.dispose(); + }); + this._registrations.clear(); + } + getProviders() { + const result = []; + for (const registration of this._registrations.values()) { + result.push(registration.provider); + } + return result; + } + }; + exports2.WorkspaceFeature = WorkspaceFeature; + } +}); + +// node_modules/vscode-languageclient/node_modules/minimatch/lib/path.js +var require_path = __commonJS({ + "node_modules/vscode-languageclient/node_modules/minimatch/lib/path.js"(exports2, module2) { + var isWindows = typeof process === "object" && process && process.platform === "win32"; + module2.exports = isWindows ? { sep: "\\" } : { sep: "/" }; + } +}); + +// node_modules/vscode-languageclient/node_modules/balanced-match/index.js +var require_balanced_match = __commonJS({ + "node_modules/vscode-languageclient/node_modules/balanced-match/index.js"(exports2, module2) { + "use strict"; + module2.exports = balanced; + function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + var r = range(a, b, str); + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; + } + function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; + } + balanced.range = range; + function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + if (ai >= 0 && bi > 0) { + if (a === b) { + return [ai, bi]; + } + begs = []; + left = str.length; + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [begs.pop(), bi]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + bi = str.indexOf(b, i + 1); + } + i = ai < bi && ai >= 0 ? ai : bi; + } + if (begs.length) { + result = [left, right]; + } + } + return result; + } + } +}); + +// node_modules/vscode-languageclient/node_modules/brace-expansion/index.js +var require_brace_expansion = __commonJS({ + "node_modules/vscode-languageclient/node_modules/brace-expansion/index.js"(exports2, module2) { + var balanced = require_balanced_match(); + module2.exports = expandTop; + var escSlash = "\0SLASH" + Math.random() + "\0"; + var escOpen = "\0OPEN" + Math.random() + "\0"; + var escClose = "\0CLOSE" + Math.random() + "\0"; + var escComma = "\0COMMA" + Math.random() + "\0"; + var escPeriod = "\0PERIOD" + Math.random() + "\0"; + function numeric(str) { + return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); + } + function escapeBraces(str) { + return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod); + } + function unescapeBraces(str) { + return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join("."); + } + function parseCommaParts(str) { + if (!str) + return [""]; + var parts = []; + var m = balanced("{", "}", str); + if (!m) + return str.split(","); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(","); + p[p.length - 1] += "{" + body + "}"; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; + } + function expandTop(str, options) { + if (!str) + return []; + options = options || {}; + var max = options.max == null ? Infinity : options.max; + if (str.substr(0, 2) === "{}") { + str = "\\{\\}" + str.substr(2); + } + return expand(escapeBraces(str), max, true).map(unescapeBraces); + } + function embrace(str) { + return "{" + str + "}"; + } + function isPadded(el) { + return /^-?0\d/.test(el); + } + function lte(i, y) { + return i <= y; + } + function gte(i, y) { + return i >= y; + } + function expand(str, max, isTop) { + var expansions = []; + var m = balanced("{", "}", str); + if (!m) return [str]; + var pre = m.pre; + var post = m.post.length ? expand(m.post, max, false) : [""]; + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length && k < max; k++) { + var expansion = pre + "{" + m.body + "}" + post[k]; + expansions.push(expansion); + } + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(",") >= 0; + if (!isSequence && !isOptions) { + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + "{" + m.body + escClose + m.post; + return expand(str, max, true); + } + return [str]; + } + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + n = expand(n[0], max, false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + var N; + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length); + var incr = n.length == 3 ? Math.max(Math.abs(numeric(n[2])), 1) : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + N = []; + for (var i = x; test(i, y) && N.length < max; i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === "\\") + c = ""; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join("0"); + if (i < 0) + c = "-" + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand(n[j], max, false)); + } + } + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length && expansions.length < max; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + } + return expansions; + } + } +}); + +// node_modules/vscode-languageclient/node_modules/minimatch/minimatch.js +var require_minimatch = __commonJS({ + "node_modules/vscode-languageclient/node_modules/minimatch/minimatch.js"(exports2, module2) { + var minimatch = module2.exports = (p, pattern, options = {}) => { + assertValidPattern(pattern); + if (!options.nocomment && pattern.charAt(0) === "#") { + return false; + } + return new Minimatch(pattern, options).match(p); + }; + module2.exports = minimatch; + var path8 = require_path(); + minimatch.sep = path8.sep; + var GLOBSTAR = /* @__PURE__ */ Symbol("globstar **"); + minimatch.GLOBSTAR = GLOBSTAR; + var expand = require_brace_expansion(); + var plTypes = { + "!": { open: "(?:(?!(?:", close: "))[^/]*?)" }, + "?": { open: "(?:", close: ")?" }, + "+": { open: "(?:", close: ")+" }, + "*": { open: "(?:", close: ")*" }, + "@": { open: "(?:", close: ")" } + }; + var qmark = "[^/]"; + var star = qmark + "*?"; + var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?"; + var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?"; + var charSet = (s) => s.split("").reduce((set, c) => { + set[c] = true; + return set; + }, {}); + var reSpecials = charSet("().*{}+?[]^$\\!"); + var addPatternStartSet = charSet("[.("); + var slashSplit = /\/+/; + minimatch.filter = (pattern, options = {}) => (p, i, list) => minimatch(p, pattern, options); + var ext = (a, b = {}) => { + const t = {}; + Object.keys(a).forEach((k) => t[k] = a[k]); + Object.keys(b).forEach((k) => t[k] = b[k]); + return t; + }; + minimatch.defaults = (def) => { + if (!def || typeof def !== "object" || !Object.keys(def).length) { + return minimatch; + } + const orig = minimatch; + const m = (p, pattern, options) => orig(p, pattern, ext(def, options)); + m.Minimatch = class Minimatch extends orig.Minimatch { + constructor(pattern, options) { + super(pattern, ext(def, options)); + } + }; + m.Minimatch.defaults = (options) => orig.defaults(ext(def, options)).Minimatch; + m.filter = (pattern, options) => orig.filter(pattern, ext(def, options)); + m.defaults = (options) => orig.defaults(ext(def, options)); + m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options)); + m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options)); + m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options)); + return m; + }; + minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options); + var braceExpand = (pattern, options = {}) => { + assertValidPattern(pattern); + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + return [pattern]; + } + return expand(pattern); + }; + var MAX_PATTERN_LENGTH = 1024 * 64; + var assertValidPattern = (pattern) => { + if (typeof pattern !== "string") { + throw new TypeError("invalid pattern"); + } + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError("pattern is too long"); + } + }; + var SUBPARSE = /* @__PURE__ */ Symbol("subparse"); + minimatch.makeRe = (pattern, options) => new Minimatch(pattern, options || {}).makeRe(); + minimatch.match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options); + list = list.filter((f) => mm.match(f)); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list; + }; + var globUnescape = (s) => s.replace(/\\(.)/g, "$1"); + var charUnescape = (s) => s.replace(/\\([^-\]])/g, "$1"); + var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + var braExpEscape = (s) => s.replace(/[[\]\\]/g, "\\$&"); + var Minimatch = class { + constructor(pattern, options) { + assertValidPattern(pattern); + if (!options) options = {}; + this.options = options; + this.maxGlobstarRecursion = options.maxGlobstarRecursion !== void 0 ? options.maxGlobstarRecursion : 200; + this.set = []; + this.pattern = pattern; + this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, "/"); + } + this.regexp = null; + this.negate = false; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + this.make(); + } + debug() { + } + make() { + const pattern = this.pattern; + const options = this.options; + if (!options.nocomment && pattern.charAt(0) === "#") { + this.comment = true; + return; + } + if (!pattern) { + this.empty = true; + return; + } + this.parseNegate(); + let set = this.globSet = this.braceExpand(); + if (options.debug) this.debug = (...args) => console.error(...args); + this.debug(this.pattern, set); + set = this.globParts = set.map((s) => s.split(slashSplit)); + this.debug(this.pattern, set); + set = set.map((s, si, set2) => s.map(this.parse, this)); + this.debug(this.pattern, set); + set = set.filter((s) => s.indexOf(false) === -1); + this.debug(this.pattern, set); + this.set = set; + } + parseNegate() { + if (this.options.nonegate) return; + const pattern = this.pattern; + let negate = false; + let negateOffset = 0; + for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) { + negate = !negate; + negateOffset++; + } + if (negateOffset) this.pattern = pattern.slice(negateOffset); + this.negate = negate; + } + // set partial to true to test if, for example, + // "/a/b" matches the start of "/*/b/*/d" + // Partial means, if you run out of file before you run + // out of pattern, then that's fine, as long as all + // the parts match. + matchOne(file, pattern, partial) { + if (pattern.indexOf(GLOBSTAR) !== -1) { + return this._matchGlobstar(file, pattern, partial, 0, 0); + } + return this._matchOne(file, pattern, partial, 0, 0); + } + _matchGlobstar(file, pattern, partial, fileIndex, patternIndex) { + let firstgs = -1; + for (let i = patternIndex; i < pattern.length; i++) { + if (pattern[i] === GLOBSTAR) { + firstgs = i; + break; + } + } + let lastgs = -1; + for (let i = pattern.length - 1; i >= 0; i--) { + if (pattern[i] === GLOBSTAR) { + lastgs = i; + break; + } + } + const head = pattern.slice(patternIndex, firstgs); + const body = partial ? pattern.slice(firstgs + 1) : pattern.slice(firstgs + 1, lastgs); + const tail = partial ? [] : pattern.slice(lastgs + 1); + if (head.length) { + const fileHead = file.slice(fileIndex, fileIndex + head.length); + if (!this._matchOne(fileHead, head, partial, 0, 0)) { + return false; + } + fileIndex += head.length; + } + let fileTailMatch = 0; + if (tail.length) { + if (tail.length + fileIndex > file.length) return false; + const tailStart = file.length - tail.length; + if (this._matchOne(file, tail, partial, tailStart, 0)) { + fileTailMatch = tail.length; + } else { + if (file[file.length - 1] !== "" || fileIndex + tail.length === file.length) { + return false; + } + if (!this._matchOne(file, tail, partial, tailStart - 1, 0)) { + return false; + } + fileTailMatch = tail.length + 1; + } + } + if (!body.length) { + let sawSome = !!fileTailMatch; + for (let i = fileIndex; i < file.length - fileTailMatch; i++) { + const f = String(file[i]); + sawSome = true; + if (f === "." || f === ".." || !this.options.dot && f.charAt(0) === ".") { + return false; + } + } + return partial || sawSome; + } + const bodySegments = [[[], 0]]; + let currentBody = bodySegments[0]; + let nonGsParts = 0; + const nonGsPartsSums = [0]; + for (const b of body) { + if (b === GLOBSTAR) { + nonGsPartsSums.push(nonGsParts); + currentBody = [[], 0]; + bodySegments.push(currentBody); + } else { + currentBody[0].push(b); + nonGsParts++; + } + } + let idx = bodySegments.length - 1; + const fileLength = file.length - fileTailMatch; + for (const b of bodySegments) { + b[1] = fileLength - (nonGsPartsSums[idx--] + b[0].length); + } + return !!this._matchGlobStarBodySections( + file, + bodySegments, + fileIndex, + 0, + partial, + 0, + !!fileTailMatch + ); + } + // return false for "nope, not matching" + // return null for "not matching, cannot keep trying" + _matchGlobStarBodySections(file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) { + const bs = bodySegments[bodyIndex]; + if (!bs) { + for (let i = fileIndex; i < file.length; i++) { + sawTail = true; + const f = file[i]; + if (f === "." || f === ".." || !this.options.dot && f.charAt(0) === ".") { + return false; + } + } + return sawTail; + } + const [body, after] = bs; + while (fileIndex <= after) { + const m = this._matchOne( + file.slice(0, fileIndex + body.length), + body, + partial, + fileIndex, + 0 + ); + if (m && globStarDepth < this.maxGlobstarRecursion) { + const sub = this._matchGlobStarBodySections( + file, + bodySegments, + fileIndex + body.length, + bodyIndex + 1, + partial, + globStarDepth + 1, + sawTail + ); + if (sub !== false) { + return sub; + } + } + const f = file[fileIndex]; + if (f === "." || f === ".." || !this.options.dot && f.charAt(0) === ".") { + return false; + } + fileIndex++; + } + return partial || null; + } + _matchOne(file, pattern, partial, fileIndex, patternIndex) { + let fi, pi, fl, pl; + for (fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { + this.debug("matchOne loop"); + const p = pattern[pi]; + const f = file[fi]; + this.debug(pattern, p, f); + if (p === false || p === GLOBSTAR) return false; + let hit; + if (typeof p === "string") { + hit = f === p; + this.debug("string match", p, f, hit); + } else { + hit = f.match(p); + this.debug("pattern match", p, f, hit); + } + if (!hit) return false; + } + if (fi === fl && pi === pl) { + return true; + } else if (fi === fl) { + return partial; + } else if (pi === pl) { + return fi === fl - 1 && file[fi] === ""; + } + throw new Error("wtf?"); + } + braceExpand() { + return braceExpand(this.pattern, this.options); + } + parse(pattern, isSub) { + assertValidPattern(pattern); + const options = this.options; + if (pattern === "**") { + if (!options.noglobstar) + return GLOBSTAR; + else + pattern = "*"; + } + if (pattern === "") return ""; + let re = ""; + let hasMagic = false; + let escaping = false; + const patternListStack = []; + const negativeLists = []; + let stateChar; + let inClass = false; + let reClassStart = -1; + let classStart = -1; + let cs; + let pl; + let sp; + let dotTravAllowed = pattern.charAt(0) === "."; + let dotFileAllowed = options.dot || dotTravAllowed; + const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)"; + const subPatternStart = (p) => p.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)"; + const clearStateChar = () => { + if (stateChar) { + switch (stateChar) { + case "*": + re += star; + hasMagic = true; + break; + case "?": + re += qmark; + hasMagic = true; + break; + default: + re += "\\" + stateChar; + break; + } + this.debug("clearStateChar %j %j", stateChar, re); + stateChar = false; + } + }; + for (let i = 0, c; i < pattern.length && (c = pattern.charAt(i)); i++) { + this.debug("%s %s %s %j", pattern, i, re, c); + if (escaping) { + if (c === "/") { + return false; + } + if (reSpecials[c]) { + re += "\\"; + } + re += c; + escaping = false; + continue; + } + switch (c) { + /* istanbul ignore next */ + case "/": { + return false; + } + case "\\": + if (inClass && pattern.charAt(i + 1) === "-") { + re += c; + continue; + } + clearStateChar(); + escaping = true; + continue; + // the various stateChar values + // for the "extglob" stuff. + case "?": + case "*": + case "+": + case "@": + case "!": + this.debug("%s %s %s %j <-- stateChar", pattern, i, re, c); + if (inClass) { + this.debug(" in class"); + if (c === "!" && i === classStart + 1) c = "^"; + re += c; + continue; + } + if (c === "*" && stateChar === "*") continue; + this.debug("call clearStateChar %j", stateChar); + clearStateChar(); + stateChar = c; + if (options.noext) clearStateChar(); + continue; + case "(": { + if (inClass) { + re += "("; + continue; + } + if (!stateChar) { + re += "\\("; + continue; + } + const plEntry = { + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }; + this.debug(this.pattern, " ", plEntry); + patternListStack.push(plEntry); + re += plEntry.open; + if (plEntry.start === 0 && plEntry.type !== "!") { + dotTravAllowed = true; + re += subPatternStart(pattern.slice(i + 1)); + } + this.debug("plType %j %j", stateChar, re); + stateChar = false; + continue; + } + case ")": { + const plEntry = patternListStack[patternListStack.length - 1]; + if (inClass || !plEntry) { + re += "\\)"; + continue; + } + patternListStack.pop(); + clearStateChar(); + hasMagic = true; + pl = plEntry; + re += pl.close; + if (pl.type === "!") { + negativeLists.push(Object.assign(pl, { reEnd: re.length })); + } + continue; + } + case "|": { + const plEntry = patternListStack[patternListStack.length - 1]; + if (inClass || !plEntry) { + re += "\\|"; + continue; + } + clearStateChar(); + re += "|"; + if (plEntry.start === 0 && plEntry.type !== "!") { + dotTravAllowed = true; + re += subPatternStart(pattern.slice(i + 1)); + } + continue; + } + // these are mostly the same in regexp and glob + case "[": + clearStateChar(); + if (inClass) { + re += "\\" + c; + continue; + } + inClass = true; + classStart = i; + reClassStart = re.length; + re += c; + continue; + case "]": + if (i === classStart + 1 || !inClass) { + re += "\\" + c; + continue; + } + cs = pattern.substring(classStart + 1, i); + try { + RegExp("[" + braExpEscape(charUnescape(cs)) + "]"); + re += c; + } catch (er) { + re = re.substring(0, reClassStart) + "(?:$.)"; + } + hasMagic = true; + inClass = false; + continue; + default: + clearStateChar(); + if (reSpecials[c] && !(c === "^" && inClass)) { + re += "\\"; + } + re += c; + break; + } + } + if (inClass) { + cs = pattern.slice(classStart + 1); + sp = this.parse(cs, SUBPARSE); + re = re.substring(0, reClassStart) + "\\[" + sp[0]; + hasMagic = hasMagic || sp[1]; + } + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + let tail; + tail = re.slice(pl.reStart + pl.open.length); + this.debug("setting tail", re, pl); + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { + if (!$2) { + $2 = "\\"; + } + return $1 + $1 + $2 + "|"; + }); + this.debug("tail=%j\n %s", tail, tail, pl, re); + const t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type; + hasMagic = true; + re = re.slice(0, pl.reStart) + t + "\\(" + tail; + } + clearStateChar(); + if (escaping) { + re += "\\\\"; + } + const addPatternStart = addPatternStartSet[re.charAt(0)]; + for (let n = negativeLists.length - 1; n > -1; n--) { + const nl = negativeLists[n]; + const nlBefore = re.slice(0, nl.reStart); + const nlFirst = re.slice(nl.reStart, nl.reEnd - 8); + let nlAfter = re.slice(nl.reEnd); + const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter; + const closeParensBefore = nlBefore.split(")").length; + const openParensBefore = nlBefore.split("(").length - closeParensBefore; + let cleanAfter = nlAfter; + for (let i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, ""); + } + nlAfter = cleanAfter; + const dollar = nlAfter === "" && isSub !== SUBPARSE ? "(?:$|\\/)" : ""; + re = nlBefore + nlFirst + nlAfter + dollar + nlLast; + } + if (re !== "" && hasMagic) { + re = "(?=.)" + re; + } + if (addPatternStart) { + re = patternStart() + re; + } + if (isSub === SUBPARSE) { + return [re, hasMagic]; + } + if (options.nocase && !hasMagic) { + hasMagic = pattern.toUpperCase() !== pattern.toLowerCase(); + } + if (!hasMagic) { + return globUnescape(pattern); + } + const flags = options.nocase ? "i" : ""; + try { + return Object.assign(new RegExp("^" + re + "$", flags), { + _glob: pattern, + _src: re + }); + } catch (er) { + return new RegExp("$."); + } + } + makeRe() { + if (this.regexp || this.regexp === false) return this.regexp; + const set = this.set; + if (!set.length) { + this.regexp = false; + return this.regexp; + } + const options = this.options; + const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot; + const flags = options.nocase ? "i" : ""; + let re = set.map((pattern) => { + pattern = pattern.map( + (p) => typeof p === "string" ? regExpEscape(p) : p === GLOBSTAR ? GLOBSTAR : p._src + ).reduce((set2, p) => { + if (!(set2[set2.length - 1] === GLOBSTAR && p === GLOBSTAR)) { + set2.push(p); + } + return set2; + }, []); + pattern.forEach((p, i) => { + if (p !== GLOBSTAR || pattern[i - 1] === GLOBSTAR) { + return; + } + if (i === 0) { + if (pattern.length > 1) { + pattern[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i + 1]; + } else { + pattern[i] = twoStar; + } + } else if (i === pattern.length - 1) { + pattern[i - 1] += "(?:\\/|" + twoStar + ")?"; + } else { + pattern[i - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i + 1]; + pattern[i + 1] = GLOBSTAR; + } + }); + return pattern.filter((p) => p !== GLOBSTAR).join("/"); + }).join("|"); + re = "^(?:" + re + ")$"; + if (this.negate) re = "^(?!" + re + ").*$"; + try { + this.regexp = new RegExp(re, flags); + } catch (ex) { + this.regexp = false; + } + return this.regexp; + } + match(f, partial = this.partial) { + this.debug("match", f, this.pattern); + if (this.comment) return false; + if (this.empty) return f === ""; + if (f === "/" && partial) return true; + const options = this.options; + if (path8.sep !== "/") { + f = f.split(path8.sep).join("/"); + } + f = f.split(slashSplit); + this.debug(this.pattern, "split", f); + const set = this.set; + this.debug(this.pattern, "set", set); + let filename; + for (let i = f.length - 1; i >= 0; i--) { + filename = f[i]; + if (filename) break; + } + for (let i = 0; i < set.length; i++) { + const pattern = set[i]; + let file = f; + if (options.matchBase && pattern.length === 1) { + file = [filename]; + } + const hit = this.matchOne(file, pattern, partial); + if (hit) { + if (options.flipNegate) return true; + return !this.negate; + } + } + if (options.flipNegate) return false; + return this.negate; + } + static defaults(def) { + return minimatch.defaults(def).Minimatch; + } + }; + minimatch.Minimatch = Minimatch; + } +}); + +// node_modules/vscode-languageclient/lib/common/diagnostic.js +var require_diagnostic = __commonJS({ + "node_modules/vscode-languageclient/lib/common/diagnostic.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DiagnosticFeature = exports2.DiagnosticPullMode = exports2.vsdiag = void 0; + var minimatch = require_minimatch(); + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var uuid_1 = require_uuid(); + var features_1 = require_features(); + function ensure(target, key) { + if (target[key] === void 0) { + target[key] = {}; + } + return target[key]; + } + var vsdiag; + (function(vsdiag2) { + let DocumentDiagnosticReportKind; + (function(DocumentDiagnosticReportKind2) { + DocumentDiagnosticReportKind2["full"] = "full"; + DocumentDiagnosticReportKind2["unChanged"] = "unChanged"; + })(DocumentDiagnosticReportKind = vsdiag2.DocumentDiagnosticReportKind || (vsdiag2.DocumentDiagnosticReportKind = {})); + })(vsdiag || (exports2.vsdiag = vsdiag = {})); + var DiagnosticPullMode; + (function(DiagnosticPullMode2) { + DiagnosticPullMode2["onType"] = "onType"; + DiagnosticPullMode2["onSave"] = "onSave"; + })(DiagnosticPullMode || (exports2.DiagnosticPullMode = DiagnosticPullMode = {})); + var RequestStateKind; + (function(RequestStateKind2) { + RequestStateKind2["active"] = "open"; + RequestStateKind2["reschedule"] = "reschedule"; + RequestStateKind2["outDated"] = "drop"; + })(RequestStateKind || (RequestStateKind = {})); + var Tabs = class _Tabs { + constructor() { + this.open = /* @__PURE__ */ new Set(); + this._onOpen = new vscode_1.EventEmitter(); + this._onClose = new vscode_1.EventEmitter(); + _Tabs.fillTabResources(this.open); + const openTabsHandler = (event) => { + if (event.closed.length === 0 && event.opened.length === 0) { + return; + } + const oldTabs = this.open; + const currentTabs = /* @__PURE__ */ new Set(); + _Tabs.fillTabResources(currentTabs); + const closed = /* @__PURE__ */ new Set(); + const opened = new Set(currentTabs); + for (const tab of oldTabs.values()) { + if (currentTabs.has(tab)) { + opened.delete(tab); + } else { + closed.add(tab); + } + } + this.open = currentTabs; + if (closed.size > 0) { + const toFire = /* @__PURE__ */ new Set(); + for (const item of closed) { + toFire.add(vscode_1.Uri.parse(item)); + } + this._onClose.fire(toFire); + } + if (opened.size > 0) { + const toFire = /* @__PURE__ */ new Set(); + for (const item of opened) { + toFire.add(vscode_1.Uri.parse(item)); + } + this._onOpen.fire(toFire); + } + }; + if (vscode_1.window.tabGroups.onDidChangeTabs !== void 0) { + this.disposable = vscode_1.window.tabGroups.onDidChangeTabs(openTabsHandler); + } else { + this.disposable = { dispose: () => { + } }; + } + } + get onClose() { + return this._onClose.event; + } + get onOpen() { + return this._onOpen.event; + } + dispose() { + this.disposable.dispose(); + } + isActive(document) { + return document instanceof vscode_1.Uri ? vscode_1.window.activeTextEditor?.document.uri === document : vscode_1.window.activeTextEditor?.document === document; + } + isVisible(document) { + const uri = document instanceof vscode_1.Uri ? document : document.uri; + return this.open.has(uri.toString()); + } + getTabResources() { + const result = /* @__PURE__ */ new Set(); + _Tabs.fillTabResources(/* @__PURE__ */ new Set(), result); + return result; + } + static fillTabResources(strings, uris) { + const seen = strings ?? /* @__PURE__ */ new Set(); + for (const group of vscode_1.window.tabGroups.all) { + for (const tab of group.tabs) { + const input = tab.input; + let uri; + if (input instanceof vscode_1.TabInputText) { + uri = input.uri; + } else if (input instanceof vscode_1.TabInputTextDiff) { + uri = input.modified; + } else if (input instanceof vscode_1.TabInputCustom) { + uri = input.uri; + } + if (uri !== void 0 && !seen.has(uri.toString())) { + seen.add(uri.toString()); + uris !== void 0 && uris.add(uri); + } + } + } + } + }; + var PullState; + (function(PullState2) { + PullState2[PullState2["document"] = 1] = "document"; + PullState2[PullState2["workspace"] = 2] = "workspace"; + })(PullState || (PullState = {})); + var DocumentOrUri; + (function(DocumentOrUri2) { + function asKey(document) { + return document instanceof vscode_1.Uri ? document.toString() : document.uri.toString(); + } + DocumentOrUri2.asKey = asKey; + })(DocumentOrUri || (DocumentOrUri = {})); + var DocumentPullStateTracker = class { + constructor() { + this.documentPullStates = /* @__PURE__ */ new Map(); + this.workspacePullStates = /* @__PURE__ */ new Map(); + } + track(kind, document, arg1) { + const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates; + const [key, uri, version] = document instanceof vscode_1.Uri ? [document.toString(), document, arg1] : [document.uri.toString(), document.uri, document.version]; + let state = states.get(key); + if (state === void 0) { + state = { document: uri, pulledVersion: version, resultId: void 0 }; + states.set(key, state); + } + return state; + } + update(kind, document, arg1, arg2) { + const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates; + const [key, uri, version, resultId] = document instanceof vscode_1.Uri ? [document.toString(), document, arg1, arg2] : [document.uri.toString(), document.uri, document.version, arg1]; + let state = states.get(key); + if (state === void 0) { + state = { document: uri, pulledVersion: version, resultId }; + states.set(key, state); + } else { + state.pulledVersion = version; + state.resultId = resultId; + } + } + unTrack(kind, document) { + const key = DocumentOrUri.asKey(document); + const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates; + states.delete(key); + } + tracks(kind, document) { + const key = DocumentOrUri.asKey(document); + const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates; + return states.has(key); + } + getResultId(kind, document) { + const key = DocumentOrUri.asKey(document); + const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates; + return states.get(key)?.resultId; + } + getAllResultIds() { + const result = []; + for (let [uri, value] of this.workspacePullStates) { + if (this.documentPullStates.has(uri)) { + value = this.documentPullStates.get(uri); + } + if (value.resultId !== void 0) { + result.push({ uri, value: value.resultId }); + } + } + return result; + } + }; + var DiagnosticRequestor = class { + constructor(client2, tabs, options) { + this.client = client2; + this.tabs = tabs; + this.options = options; + this.isDisposed = false; + this.onDidChangeDiagnosticsEmitter = new vscode_1.EventEmitter(); + this.provider = this.createProvider(); + this.diagnostics = vscode_1.languages.createDiagnosticCollection(options.identifier); + this.openRequests = /* @__PURE__ */ new Map(); + this.documentStates = new DocumentPullStateTracker(); + this.workspaceErrorCounter = 0; + } + knows(kind, document) { + const uri = document instanceof vscode_1.Uri ? document : document.uri; + return this.documentStates.tracks(kind, document) || this.openRequests.has(uri.toString()); + } + forget(kind, document) { + this.documentStates.unTrack(kind, document); + } + pull(document, cb) { + if (this.isDisposed) { + return; + } + const uri = document instanceof vscode_1.Uri ? document : document.uri; + this.pullAsync(document).then(() => { + if (cb) { + cb(); + } + }, (error) => { + this.client.error(`Document pull failed for text document ${uri.toString()}`, error, false); + }); + } + async pullAsync(document, version) { + if (this.isDisposed) { + return; + } + const isUri = document instanceof vscode_1.Uri; + const uri = isUri ? document : document.uri; + const key = uri.toString(); + version = isUri ? version : document.version; + const currentRequestState = this.openRequests.get(key); + const documentState = isUri ? this.documentStates.track(PullState.document, document, version) : this.documentStates.track(PullState.document, document); + if (currentRequestState === void 0) { + const tokenSource = new vscode_1.CancellationTokenSource(); + this.openRequests.set(key, { state: RequestStateKind.active, document, version, tokenSource }); + let report; + let afterState; + try { + report = await this.provider.provideDiagnostics(document, documentState.resultId, tokenSource.token) ?? { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] }; + } catch (error) { + if (error instanceof features_1.LSPCancellationError && vscode_languageserver_protocol_1.DiagnosticServerCancellationData.is(error.data) && error.data.retriggerRequest === false) { + afterState = { state: RequestStateKind.outDated, document }; + } + if (afterState === void 0 && error instanceof vscode_1.CancellationError) { + afterState = { state: RequestStateKind.reschedule, document }; + } else { + throw error; + } + } + afterState = afterState ?? this.openRequests.get(key); + if (afterState === void 0) { + this.client.error(`Lost request state in diagnostic pull model. Clearing diagnostics for ${key}`); + this.diagnostics.delete(uri); + return; + } + this.openRequests.delete(key); + if (!this.tabs.isVisible(document)) { + this.documentStates.unTrack(PullState.document, document); + return; + } + if (afterState.state === RequestStateKind.outDated) { + return; + } + if (report !== void 0) { + if (report.kind === vsdiag.DocumentDiagnosticReportKind.full) { + this.diagnostics.set(uri, report.items); + } + documentState.pulledVersion = version; + documentState.resultId = report.resultId; + } + if (afterState.state === RequestStateKind.reschedule) { + this.pull(document); + } + } else { + if (currentRequestState.state === RequestStateKind.active) { + currentRequestState.tokenSource.cancel(); + this.openRequests.set(key, { state: RequestStateKind.reschedule, document: currentRequestState.document }); + } else if (currentRequestState.state === RequestStateKind.outDated) { + this.openRequests.set(key, { state: RequestStateKind.reschedule, document: currentRequestState.document }); + } + } + } + forgetDocument(document) { + const uri = document instanceof vscode_1.Uri ? document : document.uri; + const key = uri.toString(); + const request = this.openRequests.get(key); + if (this.options.workspaceDiagnostics) { + if (request !== void 0) { + this.openRequests.set(key, { state: RequestStateKind.reschedule, document }); + } else { + this.pull(document, () => { + this.forget(PullState.document, document); + }); + } + } else { + if (request !== void 0) { + if (request.state === RequestStateKind.active) { + request.tokenSource.cancel(); + } + this.openRequests.set(key, { state: RequestStateKind.outDated, document }); + } + this.diagnostics.delete(uri); + this.forget(PullState.document, document); + } + } + pullWorkspace() { + if (this.isDisposed) { + return; + } + this.pullWorkspaceAsync().then(() => { + this.workspaceTimeout = (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(() => { + this.pullWorkspace(); + }, 2e3); + }, (error) => { + if (!(error instanceof features_1.LSPCancellationError) && !vscode_languageserver_protocol_1.DiagnosticServerCancellationData.is(error.data)) { + this.client.error(`Workspace diagnostic pull failed.`, error, false); + this.workspaceErrorCounter++; + } + if (this.workspaceErrorCounter <= 5) { + this.workspaceTimeout = (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(() => { + this.pullWorkspace(); + }, 2e3); + } + }); + } + async pullWorkspaceAsync() { + if (!this.provider.provideWorkspaceDiagnostics || this.isDisposed) { + return; + } + if (this.workspaceCancellation !== void 0) { + this.workspaceCancellation.cancel(); + this.workspaceCancellation = void 0; + } + this.workspaceCancellation = new vscode_1.CancellationTokenSource(); + const previousResultIds = this.documentStates.getAllResultIds().map((item) => { + return { + uri: this.client.protocol2CodeConverter.asUri(item.uri), + value: item.value + }; + }); + await this.provider.provideWorkspaceDiagnostics(previousResultIds, this.workspaceCancellation.token, (chunk) => { + if (!chunk || this.isDisposed) { + return; + } + for (const item of chunk.items) { + if (item.kind === vsdiag.DocumentDiagnosticReportKind.full) { + if (!this.documentStates.tracks(PullState.document, item.uri)) { + this.diagnostics.set(item.uri, item.items); + } + } + this.documentStates.update(PullState.workspace, item.uri, item.version ?? void 0, item.resultId); + } + }); + } + createProvider() { + const result = { + onDidChangeDiagnostics: this.onDidChangeDiagnosticsEmitter.event, + provideDiagnostics: (document, previousResultId, token) => { + const provideDiagnostics = (document2, previousResultId2, token2) => { + const params = { + identifier: this.options.identifier, + textDocument: { uri: this.client.code2ProtocolConverter.asUri(document2 instanceof vscode_1.Uri ? document2 : document2.uri) }, + previousResultId: previousResultId2 + }; + if (this.isDisposed === true || !this.client.isRunning()) { + return { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] }; + } + return this.client.sendRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, params, token2).then(async (result2) => { + if (result2 === void 0 || result2 === null || this.isDisposed || token2.isCancellationRequested) { + return { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] }; + } + if (result2.kind === vscode_languageserver_protocol_1.DocumentDiagnosticReportKind.Full) { + return { kind: vsdiag.DocumentDiagnosticReportKind.full, resultId: result2.resultId, items: await this.client.protocol2CodeConverter.asDiagnostics(result2.items, token2) }; + } else { + return { kind: vsdiag.DocumentDiagnosticReportKind.unChanged, resultId: result2.resultId }; + } + }, (error) => { + return this.client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, token2, error, { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] }); + }); + }; + const middleware = this.client.middleware; + return middleware.provideDiagnostics ? middleware.provideDiagnostics(document, previousResultId, token, provideDiagnostics) : provideDiagnostics(document, previousResultId, token); + } + }; + if (this.options.workspaceDiagnostics) { + result.provideWorkspaceDiagnostics = (resultIds, token, resultReporter) => { + const convertReport = async (report) => { + if (report.kind === vscode_languageserver_protocol_1.DocumentDiagnosticReportKind.Full) { + return { + kind: vsdiag.DocumentDiagnosticReportKind.full, + uri: this.client.protocol2CodeConverter.asUri(report.uri), + resultId: report.resultId, + version: report.version, + items: await this.client.protocol2CodeConverter.asDiagnostics(report.items, token) + }; + } else { + return { + kind: vsdiag.DocumentDiagnosticReportKind.unChanged, + uri: this.client.protocol2CodeConverter.asUri(report.uri), + resultId: report.resultId, + version: report.version + }; + } + }; + const convertPreviousResultIds = (resultIds2) => { + const converted = []; + for (const item of resultIds2) { + converted.push({ uri: this.client.code2ProtocolConverter.asUri(item.uri), value: item.value }); + } + return converted; + }; + const provideDiagnostics = (resultIds2, token2) => { + const partialResultToken = (0, uuid_1.generateUuid)(); + const disposable = this.client.onProgress(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.partialResult, partialResultToken, async (partialResult) => { + if (partialResult === void 0 || partialResult === null) { + resultReporter(null); + return; + } + const converted = { + items: [] + }; + for (const item of partialResult.items) { + try { + converted.items.push(await convertReport(item)); + } catch (error) { + this.client.error(`Converting workspace diagnostics failed.`, error); + } + } + resultReporter(converted); + }); + const params = { + identifier: this.options.identifier, + previousResultIds: convertPreviousResultIds(resultIds2), + partialResultToken + }; + if (this.isDisposed === true || !this.client.isRunning()) { + return { items: [] }; + } + return this.client.sendRequest(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.type, params, token2).then(async (result2) => { + if (token2.isCancellationRequested) { + return { items: [] }; + } + const converted = { + items: [] + }; + for (const item of result2.items) { + converted.items.push(await convertReport(item)); + } + disposable.dispose(); + resultReporter(converted); + return { items: [] }; + }, (error) => { + disposable.dispose(); + return this.client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, token2, error, { items: [] }); + }); + }; + const middleware = this.client.middleware; + return middleware.provideWorkspaceDiagnostics ? middleware.provideWorkspaceDiagnostics(resultIds, token, resultReporter, provideDiagnostics) : provideDiagnostics(resultIds, token, resultReporter); + }; + } + return result; + } + dispose() { + this.isDisposed = true; + this.workspaceCancellation?.cancel(); + this.workspaceTimeout?.dispose(); + for (const [key, request] of this.openRequests) { + if (request.state === RequestStateKind.active) { + request.tokenSource.cancel(); + } + this.openRequests.set(key, { state: RequestStateKind.outDated, document: request.document }); + } + this.diagnostics.dispose(); + } + }; + var BackgroundScheduler = class { + constructor(diagnosticRequestor) { + this.diagnosticRequestor = diagnosticRequestor; + this.documents = new vscode_languageserver_protocol_1.LinkedMap(); + this.isDisposed = false; + } + add(document) { + if (this.isDisposed === true) { + return; + } + const key = DocumentOrUri.asKey(document); + if (this.documents.has(key)) { + return; + } + this.documents.set(key, document, vscode_languageserver_protocol_1.Touch.Last); + this.trigger(); + } + remove(document) { + const key = DocumentOrUri.asKey(document); + this.documents.delete(key); + if (this.documents.size === 0) { + this.stop(); + } else if (key === this.endDocumentKey()) { + this.endDocument = this.documents.last; + } + } + trigger() { + if (this.isDisposed === true) { + return; + } + if (this.intervalHandle !== void 0) { + this.endDocument = this.documents.last; + return; + } + this.endDocument = this.documents.last; + this.intervalHandle = (0, vscode_languageserver_protocol_1.RAL)().timer.setInterval(() => { + const document = this.documents.first; + if (document !== void 0) { + const key = DocumentOrUri.asKey(document); + this.diagnosticRequestor.pull(document); + this.documents.set(key, document, vscode_languageserver_protocol_1.Touch.Last); + if (key === this.endDocumentKey()) { + this.stop(); + } + } + }, 200); + } + dispose() { + this.isDisposed = true; + this.stop(); + this.documents.clear(); + } + stop() { + this.intervalHandle?.dispose(); + this.intervalHandle = void 0; + this.endDocument = void 0; + } + endDocumentKey() { + return this.endDocument !== void 0 ? DocumentOrUri.asKey(this.endDocument) : void 0; + } + }; + var DiagnosticFeatureProviderImpl = class { + constructor(client2, tabs, options) { + const diagnosticPullOptions = client2.clientOptions.diagnosticPullOptions ?? { onChange: true, onSave: false }; + const documentSelector = client2.protocol2CodeConverter.asDocumentSelector(options.documentSelector); + const disposables = []; + const matchResource = (resource) => { + const selector = options.documentSelector; + if (diagnosticPullOptions.match !== void 0) { + return diagnosticPullOptions.match(selector, resource); + } + for (const filter of selector) { + if (!vscode_languageserver_protocol_1.TextDocumentFilter.is(filter)) { + continue; + } + if (typeof filter === "string") { + return false; + } + if (filter.language !== void 0 && filter.language !== "*") { + return false; + } + if (filter.scheme !== void 0 && filter.scheme !== "*" && filter.scheme !== resource.scheme) { + return false; + } + if (filter.pattern !== void 0) { + const matcher = new minimatch.Minimatch(filter.pattern, { noext: true }); + if (!matcher.makeRe()) { + return false; + } + if (!matcher.match(resource.fsPath)) { + return false; + } + } + } + return true; + }; + const matches = (document) => { + return document instanceof vscode_1.Uri ? matchResource(document) : vscode_1.languages.match(documentSelector, document) > 0 && tabs.isVisible(document); + }; + const isActiveDocument = (document) => { + return document instanceof vscode_1.Uri ? this.activeTextDocument?.uri.toString() === document.toString() : this.activeTextDocument === document; + }; + this.diagnosticRequestor = new DiagnosticRequestor(client2, tabs, options); + this.backgroundScheduler = new BackgroundScheduler(this.diagnosticRequestor); + const addToBackgroundIfNeeded = (document) => { + if (!matches(document) || !options.interFileDependencies || isActiveDocument(document)) { + return; + } + this.backgroundScheduler.add(document); + }; + this.activeTextDocument = vscode_1.window.activeTextEditor?.document; + vscode_1.window.onDidChangeActiveTextEditor((editor) => { + const oldActive = this.activeTextDocument; + this.activeTextDocument = editor?.document; + if (oldActive !== void 0) { + addToBackgroundIfNeeded(oldActive); + } + if (this.activeTextDocument !== void 0) { + this.backgroundScheduler.remove(this.activeTextDocument); + } + }); + const openFeature = client2.getFeature(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.method); + disposables.push(openFeature.onNotificationSent((event) => { + const textDocument = event.textDocument; + if (this.diagnosticRequestor.knows(PullState.document, textDocument)) { + return; + } + if (matches(textDocument)) { + this.diagnosticRequestor.pull(textDocument, () => { + addToBackgroundIfNeeded(textDocument); + }); + } + })); + disposables.push(tabs.onOpen((opened) => { + for (const resource of opened) { + if (this.diagnosticRequestor.knows(PullState.document, resource)) { + continue; + } + const uriStr = resource.toString(); + let textDocument; + for (const item of vscode_1.workspace.textDocuments) { + if (uriStr === item.uri.toString()) { + textDocument = item; + break; + } + } + if (textDocument !== void 0 && matches(textDocument)) { + this.diagnosticRequestor.pull(textDocument, () => { + addToBackgroundIfNeeded(textDocument); + }); + } + } + })); + const pulledTextDocuments = /* @__PURE__ */ new Set(); + for (const textDocument of vscode_1.workspace.textDocuments) { + if (matches(textDocument)) { + this.diagnosticRequestor.pull(textDocument, () => { + addToBackgroundIfNeeded(textDocument); + }); + pulledTextDocuments.add(textDocument.uri.toString()); + } + } + if (diagnosticPullOptions.onTabs === true) { + for (const resource of tabs.getTabResources()) { + if (!pulledTextDocuments.has(resource.toString()) && matches(resource)) { + this.diagnosticRequestor.pull(resource, () => { + addToBackgroundIfNeeded(resource); + }); + } + } + } + if (diagnosticPullOptions.onChange === true) { + const changeFeature = client2.getFeature(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.method); + disposables.push(changeFeature.onNotificationSent(async (event) => { + const textDocument = event.textDocument; + if ((diagnosticPullOptions.filter === void 0 || !diagnosticPullOptions.filter(textDocument, DiagnosticPullMode.onType)) && this.diagnosticRequestor.knows(PullState.document, textDocument)) { + this.diagnosticRequestor.pull(textDocument, () => { + this.backgroundScheduler.trigger(); + }); + } + })); + } + if (diagnosticPullOptions.onSave === true) { + const saveFeature = client2.getFeature(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.method); + disposables.push(saveFeature.onNotificationSent((event) => { + const textDocument = event.textDocument; + if ((diagnosticPullOptions.filter === void 0 || !diagnosticPullOptions.filter(textDocument, DiagnosticPullMode.onSave)) && this.diagnosticRequestor.knows(PullState.document, textDocument)) { + this.diagnosticRequestor.pull(event.textDocument, () => { + this.backgroundScheduler.trigger(); + }); + } + })); + } + const closeFeature = client2.getFeature(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.method); + disposables.push(closeFeature.onNotificationSent((event) => { + this.cleanUpDocument(event.textDocument); + })); + tabs.onClose((closed) => { + for (const document of closed) { + this.cleanUpDocument(document); + } + }); + this.diagnosticRequestor.onDidChangeDiagnosticsEmitter.event(() => { + for (const textDocument of vscode_1.workspace.textDocuments) { + if (matches(textDocument)) { + this.diagnosticRequestor.pull(textDocument); + } + } + }); + if (options.workspaceDiagnostics === true && options.identifier !== "da348dc5-c30a-4515-9d98-31ff3be38d14") { + this.diagnosticRequestor.pullWorkspace(); + } + this.disposable = vscode_1.Disposable.from(...disposables, this.backgroundScheduler, this.diagnosticRequestor); + } + get onDidChangeDiagnosticsEmitter() { + return this.diagnosticRequestor.onDidChangeDiagnosticsEmitter; + } + get diagnostics() { + return this.diagnosticRequestor.provider; + } + cleanUpDocument(document) { + if (this.diagnosticRequestor.knows(PullState.document, document)) { + this.diagnosticRequestor.forgetDocument(document); + this.backgroundScheduler.remove(document); + } + } + }; + var DiagnosticFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type); + } + fillClientCapabilities(capabilities) { + let capability = ensure(ensure(capabilities, "textDocument"), "diagnostic"); + capability.dynamicRegistration = true; + capability.relatedDocumentSupport = false; + ensure(ensure(capabilities, "workspace"), "diagnostics").refreshSupport = true; + } + initialize(capabilities, documentSelector) { + const client2 = this._client; + client2.onRequest(vscode_languageserver_protocol_1.DiagnosticRefreshRequest.type, async () => { + for (const provider of this.getAllProviders()) { + provider.onDidChangeDiagnosticsEmitter.fire(); + } + }); + let [id, options] = this.getRegistration(documentSelector, capabilities.diagnosticProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + clear() { + if (this.tabs !== void 0) { + this.tabs.dispose(); + this.tabs = void 0; + } + super.clear(); + } + registerLanguageProvider(options) { + if (this.tabs === void 0) { + this.tabs = new Tabs(); + } + const provider = new DiagnosticFeatureProviderImpl(this._client, this.tabs, options); + return [provider.disposable, provider]; + } + }; + exports2.DiagnosticFeature = DiagnosticFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/notebook.js +var require_notebook = __commonJS({ + "node_modules/vscode-languageclient/lib/common/notebook.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NotebookDocumentSyncFeature = void 0; + var vscode12 = require("vscode"); + var minimatch = require_minimatch(); + var proto = require_main3(); + var UUID = require_uuid(); + var Is = require_is(); + function ensure(target, key) { + if (target[key] === void 0) { + target[key] = {}; + } + return target[key]; + } + var Converter; + (function(Converter2) { + let c2p; + (function(c2p2) { + function asVersionedNotebookDocumentIdentifier(notebookDocument, base) { + return { + version: notebookDocument.version, + uri: base.asUri(notebookDocument.uri) + }; + } + c2p2.asVersionedNotebookDocumentIdentifier = asVersionedNotebookDocumentIdentifier; + function asNotebookDocument(notebookDocument, cells, base) { + const result = proto.NotebookDocument.create(base.asUri(notebookDocument.uri), notebookDocument.notebookType, notebookDocument.version, asNotebookCells(cells, base)); + if (Object.keys(notebookDocument.metadata).length > 0) { + result.metadata = asMetadata(notebookDocument.metadata); + } + return result; + } + c2p2.asNotebookDocument = asNotebookDocument; + function asNotebookCells(cells, base) { + return cells.map((cell) => asNotebookCell(cell, base)); + } + c2p2.asNotebookCells = asNotebookCells; + function asMetadata(metadata) { + const seen = /* @__PURE__ */ new Set(); + return deepCopy(seen, metadata); + } + c2p2.asMetadata = asMetadata; + function asNotebookCell(cell, base) { + const result = proto.NotebookCell.create(asNotebookCellKind(cell.kind), base.asUri(cell.document.uri)); + if (Object.keys(cell.metadata).length > 0) { + result.metadata = asMetadata(cell.metadata); + } + if (cell.executionSummary !== void 0 && (Is.number(cell.executionSummary.executionOrder) && Is.boolean(cell.executionSummary.success))) { + result.executionSummary = { + executionOrder: cell.executionSummary.executionOrder, + success: cell.executionSummary.success + }; + } + return result; + } + c2p2.asNotebookCell = asNotebookCell; + function asNotebookCellKind(kind) { + switch (kind) { + case vscode12.NotebookCellKind.Markup: + return proto.NotebookCellKind.Markup; + case vscode12.NotebookCellKind.Code: + return proto.NotebookCellKind.Code; + } + } + function deepCopy(seen, value) { + if (seen.has(value)) { + throw new Error(`Can't deep copy cyclic structures.`); + } + if (Array.isArray(value)) { + const result = []; + for (const elem of value) { + if (elem !== null && typeof elem === "object" || Array.isArray(elem)) { + result.push(deepCopy(seen, elem)); + } else { + if (elem instanceof RegExp) { + throw new Error(`Can't transfer regular expressions to the server`); + } + result.push(elem); + } + } + return result; + } else { + const props = Object.keys(value); + const result = /* @__PURE__ */ Object.create(null); + for (const prop of props) { + const elem = value[prop]; + if (elem !== null && typeof elem === "object" || Array.isArray(elem)) { + result[prop] = deepCopy(seen, elem); + } else { + if (elem instanceof RegExp) { + throw new Error(`Can't transfer regular expressions to the server`); + } + result[prop] = elem; + } + } + return result; + } + } + function asTextContentChange(event, base) { + const params = base.asChangeTextDocumentParams(event, event.document.uri, event.document.version); + return { document: params.textDocument, changes: params.contentChanges }; + } + c2p2.asTextContentChange = asTextContentChange; + function asNotebookDocumentChangeEvent(event, base) { + const result = /* @__PURE__ */ Object.create(null); + if (event.metadata) { + result.metadata = Converter2.c2p.asMetadata(event.metadata); + } + if (event.cells !== void 0) { + const cells = /* @__PURE__ */ Object.create(null); + const changedCells = event.cells; + if (changedCells.structure) { + cells.structure = { + array: { + start: changedCells.structure.array.start, + deleteCount: changedCells.structure.array.deleteCount, + cells: changedCells.structure.array.cells !== void 0 ? changedCells.structure.array.cells.map((cell) => Converter2.c2p.asNotebookCell(cell, base)) : void 0 + }, + didOpen: changedCells.structure.didOpen !== void 0 ? changedCells.structure.didOpen.map((cell) => base.asOpenTextDocumentParams(cell.document).textDocument) : void 0, + didClose: changedCells.structure.didClose !== void 0 ? changedCells.structure.didClose.map((cell) => base.asCloseTextDocumentParams(cell.document).textDocument) : void 0 + }; + } + if (changedCells.data !== void 0) { + cells.data = changedCells.data.map((cell) => Converter2.c2p.asNotebookCell(cell, base)); + } + if (changedCells.textContent !== void 0) { + cells.textContent = changedCells.textContent.map((event2) => Converter2.c2p.asTextContentChange(event2, base)); + } + if (Object.keys(cells).length > 0) { + result.cells = cells; + } + } + return result; + } + c2p2.asNotebookDocumentChangeEvent = asNotebookDocumentChangeEvent; + })(c2p = Converter2.c2p || (Converter2.c2p = {})); + })(Converter || (Converter = {})); + var $NotebookCell; + (function($NotebookCell2) { + function computeDiff(originalCells, modifiedCells, compareMetadata) { + const originalLength = originalCells.length; + const modifiedLength = modifiedCells.length; + let startIndex = 0; + while (startIndex < modifiedLength && startIndex < originalLength && equals(originalCells[startIndex], modifiedCells[startIndex], compareMetadata)) { + startIndex++; + } + if (startIndex < modifiedLength && startIndex < originalLength) { + let originalEndIndex = originalLength - 1; + let modifiedEndIndex = modifiedLength - 1; + while (originalEndIndex >= 0 && modifiedEndIndex >= 0 && equals(originalCells[originalEndIndex], modifiedCells[modifiedEndIndex], compareMetadata)) { + originalEndIndex--; + modifiedEndIndex--; + } + const deleteCount = originalEndIndex + 1 - startIndex; + const newCells = startIndex === modifiedEndIndex + 1 ? void 0 : modifiedCells.slice(startIndex, modifiedEndIndex + 1); + return newCells !== void 0 ? { start: startIndex, deleteCount, cells: newCells } : { start: startIndex, deleteCount }; + } else if (startIndex < modifiedLength) { + return { start: startIndex, deleteCount: 0, cells: modifiedCells.slice(startIndex) }; + } else if (startIndex < originalLength) { + return { start: startIndex, deleteCount: originalLength - startIndex }; + } else { + return void 0; + } + } + $NotebookCell2.computeDiff = computeDiff; + function equals(one, other, compareMetaData = true) { + if (one.kind !== other.kind || one.document.uri.toString() !== other.document.uri.toString() || one.document.languageId !== other.document.languageId || !equalsExecution(one.executionSummary, other.executionSummary)) { + return false; + } + return !compareMetaData || compareMetaData && equalsMetadata(one.metadata, other.metadata); + } + function equalsExecution(one, other) { + if (one === other) { + return true; + } + if (one === void 0 || other === void 0) { + return false; + } + return one.executionOrder === other.executionOrder && one.success === other.success && equalsTiming(one.timing, other.timing); + } + function equalsTiming(one, other) { + if (one === other) { + return true; + } + if (one === void 0 || other === void 0) { + return false; + } + return one.startTime === other.startTime && one.endTime === other.endTime; + } + function equalsMetadata(one, other) { + if (one === other) { + return true; + } + if (one === null || one === void 0 || other === null || other === void 0) { + return false; + } + if (typeof one !== typeof other) { + return false; + } + if (typeof one !== "object") { + return false; + } + const oneArray = Array.isArray(one); + const otherArray = Array.isArray(other); + if (oneArray !== otherArray) { + return false; + } + if (oneArray && otherArray) { + if (one.length !== other.length) { + return false; + } + for (let i = 0; i < one.length; i++) { + if (!equalsMetadata(one[i], other[i])) { + return false; + } + } + } + if (isObjectLiteral(one) && isObjectLiteral(other)) { + const oneKeys = Object.keys(one); + const otherKeys = Object.keys(other); + if (oneKeys.length !== otherKeys.length) { + return false; + } + oneKeys.sort(); + otherKeys.sort(); + if (!equalsMetadata(oneKeys, otherKeys)) { + return false; + } + for (let i = 0; i < oneKeys.length; i++) { + const prop = oneKeys[i]; + if (!equalsMetadata(one[prop], other[prop])) { + return false; + } + } + return true; + } + return false; + } + function isObjectLiteral(value) { + return value !== null && typeof value === "object"; + } + $NotebookCell2.isObjectLiteral = isObjectLiteral; + })($NotebookCell || ($NotebookCell = {})); + var $NotebookDocumentFilter; + (function($NotebookDocumentFilter2) { + function matchNotebook(filter, notebookDocument) { + if (typeof filter === "string") { + return filter === "*" || notebookDocument.notebookType === filter; + } + if (filter.notebookType !== void 0 && filter.notebookType !== "*" && notebookDocument.notebookType !== filter.notebookType) { + return false; + } + const uri = notebookDocument.uri; + if (filter.scheme !== void 0 && filter.scheme !== "*" && uri.scheme !== filter.scheme) { + return false; + } + if (filter.pattern !== void 0) { + const matcher = new minimatch.Minimatch(filter.pattern, { noext: true }); + if (!matcher.makeRe()) { + return false; + } + if (!matcher.match(uri.fsPath)) { + return false; + } + } + return true; + } + $NotebookDocumentFilter2.matchNotebook = matchNotebook; + })($NotebookDocumentFilter || ($NotebookDocumentFilter = {})); + var $NotebookDocumentSyncOptions; + (function($NotebookDocumentSyncOptions2) { + function asDocumentSelector(options) { + const selector = options.notebookSelector; + const result = []; + for (const element of selector) { + const notebookType = (typeof element.notebook === "string" ? element.notebook : element.notebook?.notebookType) ?? "*"; + const scheme = typeof element.notebook === "string" ? void 0 : element.notebook?.scheme; + const pattern = typeof element.notebook === "string" ? void 0 : element.notebook?.pattern; + if (element.cells !== void 0) { + for (const cell of element.cells) { + result.push(asDocumentFilter(notebookType, scheme, pattern, cell.language)); + } + } else { + result.push(asDocumentFilter(notebookType, scheme, pattern, void 0)); + } + } + return result; + } + $NotebookDocumentSyncOptions2.asDocumentSelector = asDocumentSelector; + function asDocumentFilter(notebookType, scheme, pattern, language) { + return scheme === void 0 && pattern === void 0 ? { notebook: notebookType, language } : { notebook: { notebookType, scheme, pattern }, language }; + } + })($NotebookDocumentSyncOptions || ($NotebookDocumentSyncOptions = {})); + var SyncInfo; + (function(SyncInfo2) { + function create(cells) { + return { + cells, + uris: new Set(cells.map((cell) => cell.document.uri.toString())) + }; + } + SyncInfo2.create = create; + })(SyncInfo || (SyncInfo = {})); + var NotebookDocumentSyncFeatureProvider = class { + constructor(client2, options) { + this.client = client2; + this.options = options; + this.notebookSyncInfo = /* @__PURE__ */ new Map(); + this.notebookDidOpen = /* @__PURE__ */ new Set(); + this.disposables = []; + this.selector = client2.protocol2CodeConverter.asDocumentSelector($NotebookDocumentSyncOptions.asDocumentSelector(options)); + vscode12.workspace.onDidOpenNotebookDocument((notebookDocument) => { + this.notebookDidOpen.add(notebookDocument.uri.toString()); + this.didOpen(notebookDocument); + }, void 0, this.disposables); + for (const notebookDocument of vscode12.workspace.notebookDocuments) { + this.notebookDidOpen.add(notebookDocument.uri.toString()); + this.didOpen(notebookDocument); + } + vscode12.workspace.onDidChangeNotebookDocument((event) => this.didChangeNotebookDocument(event), void 0, this.disposables); + if (this.options.save === true) { + vscode12.workspace.onDidSaveNotebookDocument((notebookDocument) => this.didSave(notebookDocument), void 0, this.disposables); + } + vscode12.workspace.onDidCloseNotebookDocument((notebookDocument) => { + this.didClose(notebookDocument); + this.notebookDidOpen.delete(notebookDocument.uri.toString()); + }, void 0, this.disposables); + } + getState() { + for (const notebook of vscode12.workspace.notebookDocuments) { + const matchingCells = this.getMatchingCells(notebook); + if (matchingCells !== void 0) { + return { kind: "document", id: "$internal", registrations: true, matches: true }; + } + } + return { kind: "document", id: "$internal", registrations: true, matches: false }; + } + get mode() { + return "notebook"; + } + handles(textDocument) { + return vscode12.languages.match(this.selector, textDocument) > 0; + } + didOpenNotebookCellTextDocument(notebookDocument, cell) { + if (vscode12.languages.match(this.selector, cell.document) === 0) { + return; + } + if (!this.notebookDidOpen.has(notebookDocument.uri.toString())) { + return; + } + const syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString()); + const cellMatches = this.cellMatches(notebookDocument, cell); + if (syncInfo !== void 0) { + const cellIsSynced = syncInfo.uris.has(cell.document.uri.toString()); + if (cellMatches && cellIsSynced || !cellMatches && !cellIsSynced) { + return; + } + if (cellMatches) { + const matchingCells = this.getMatchingCells(notebookDocument); + if (matchingCells !== void 0) { + const event = this.asNotebookDocumentChangeEvent(notebookDocument, void 0, syncInfo, matchingCells); + if (event !== void 0) { + this.doSendChange(event, matchingCells).catch(() => { + }); + } + } + } + } else { + if (cellMatches) { + this.doSendOpen(notebookDocument, [cell]).catch(() => { + }); + } + } + } + didChangeNotebookCellTextDocument(notebookDocument, event) { + if (vscode12.languages.match(this.selector, event.document) === 0) { + return; + } + this.doSendChange({ + notebook: notebookDocument, + cells: { textContent: [event] } + }, void 0).catch(() => { + }); + } + didCloseNotebookCellTextDocument(notebookDocument, cell) { + const syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString()); + if (syncInfo === void 0) { + return; + } + const cellUri = cell.document.uri; + const index = syncInfo.cells.findIndex((item) => item.document.uri.toString() === cellUri.toString()); + if (index === -1) { + return; + } + if (index === 0 && syncInfo.cells.length === 1) { + this.doSendClose(notebookDocument, syncInfo.cells).catch(() => { + }); + } else { + const newCells = syncInfo.cells.slice(); + const deleted = newCells.splice(index, 1); + this.doSendChange({ + notebook: notebookDocument, + cells: { + structure: { + array: { start: index, deleteCount: 1 }, + didClose: deleted + } + } + }, newCells).catch(() => { + }); + } + } + dispose() { + for (const disposable of this.disposables) { + disposable.dispose(); + } + } + didOpen(notebookDocument, matchingCells = this.getMatchingCells(notebookDocument), syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString())) { + if (syncInfo !== void 0) { + if (matchingCells !== void 0) { + const event = this.asNotebookDocumentChangeEvent(notebookDocument, void 0, syncInfo, matchingCells); + if (event !== void 0) { + this.doSendChange(event, matchingCells).catch(() => { + }); + } + } else { + this.doSendClose(notebookDocument, []).catch(() => { + }); + } + } else { + if (matchingCells === void 0) { + return; + } + this.doSendOpen(notebookDocument, matchingCells).catch(() => { + }); + } + } + didChangeNotebookDocument(event) { + const notebookDocument = event.notebook; + const syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString()); + if (syncInfo === void 0) { + if (event.contentChanges.length === 0) { + return; + } + const cells = this.getMatchingCells(notebookDocument); + if (cells === void 0) { + return; + } + this.didOpen(notebookDocument, cells, syncInfo); + } else { + const cells = this.getMatchingCells(notebookDocument); + if (cells === void 0) { + this.didClose(notebookDocument, syncInfo); + return; + } + const newEvent = this.asNotebookDocumentChangeEvent(event.notebook, event, syncInfo, cells); + if (newEvent !== void 0) { + this.doSendChange(newEvent, cells).catch(() => { + }); + } + } + } + didSave(notebookDocument) { + const syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString()); + if (syncInfo === void 0) { + return; + } + this.doSendSave(notebookDocument).catch(() => { + }); + } + didClose(notebookDocument, syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString())) { + if (syncInfo === void 0) { + return; + } + const syncedCells = notebookDocument.getCells().filter((cell) => syncInfo.uris.has(cell.document.uri.toString())); + this.doSendClose(notebookDocument, syncedCells).catch(() => { + }); + } + async sendDidOpenNotebookDocument(notebookDocument) { + const cells = this.getMatchingCells(notebookDocument); + if (cells === void 0) { + return; + } + return this.doSendOpen(notebookDocument, cells); + } + async doSendOpen(notebookDocument, cells) { + const send = async (notebookDocument2, cells2) => { + const nb = Converter.c2p.asNotebookDocument(notebookDocument2, cells2, this.client.code2ProtocolConverter); + const cellDocuments = cells2.map((cell) => this.client.code2ProtocolConverter.asTextDocumentItem(cell.document)); + try { + await this.client.sendNotification(proto.DidOpenNotebookDocumentNotification.type, { + notebookDocument: nb, + cellTextDocuments: cellDocuments + }); + } catch (error) { + this.client.error("Sending DidOpenNotebookDocumentNotification failed", error); + throw error; + } + }; + const middleware = this.client.middleware?.notebooks; + this.notebookSyncInfo.set(notebookDocument.uri.toString(), SyncInfo.create(cells)); + return middleware?.didOpen !== void 0 ? middleware.didOpen(notebookDocument, cells, send) : send(notebookDocument, cells); + } + async sendDidChangeNotebookDocument(event) { + return this.doSendChange(event, void 0); + } + async doSendChange(event, cells = this.getMatchingCells(event.notebook)) { + const send = async (event2) => { + try { + await this.client.sendNotification(proto.DidChangeNotebookDocumentNotification.type, { + notebookDocument: Converter.c2p.asVersionedNotebookDocumentIdentifier(event2.notebook, this.client.code2ProtocolConverter), + change: Converter.c2p.asNotebookDocumentChangeEvent(event2, this.client.code2ProtocolConverter) + }); + } catch (error) { + this.client.error("Sending DidChangeNotebookDocumentNotification failed", error); + throw error; + } + }; + const middleware = this.client.middleware?.notebooks; + if (event.cells?.structure !== void 0) { + this.notebookSyncInfo.set(event.notebook.uri.toString(), SyncInfo.create(cells ?? [])); + } + return middleware?.didChange !== void 0 ? middleware?.didChange(event, send) : send(event); + } + async sendDidSaveNotebookDocument(notebookDocument) { + return this.doSendSave(notebookDocument); + } + async doSendSave(notebookDocument) { + const send = async (notebookDocument2) => { + try { + await this.client.sendNotification(proto.DidSaveNotebookDocumentNotification.type, { + notebookDocument: { uri: this.client.code2ProtocolConverter.asUri(notebookDocument2.uri) } + }); + } catch (error) { + this.client.error("Sending DidSaveNotebookDocumentNotification failed", error); + throw error; + } + }; + const middleware = this.client.middleware?.notebooks; + return middleware?.didSave !== void 0 ? middleware.didSave(notebookDocument, send) : send(notebookDocument); + } + async sendDidCloseNotebookDocument(notebookDocument) { + return this.doSendClose(notebookDocument, this.getMatchingCells(notebookDocument) ?? []); + } + async doSendClose(notebookDocument, cells) { + const send = async (notebookDocument2, cells2) => { + try { + await this.client.sendNotification(proto.DidCloseNotebookDocumentNotification.type, { + notebookDocument: { uri: this.client.code2ProtocolConverter.asUri(notebookDocument2.uri) }, + cellTextDocuments: cells2.map((cell) => this.client.code2ProtocolConverter.asTextDocumentIdentifier(cell.document)) + }); + } catch (error) { + this.client.error("Sending DidCloseNotebookDocumentNotification failed", error); + throw error; + } + }; + const middleware = this.client.middleware?.notebooks; + this.notebookSyncInfo.delete(notebookDocument.uri.toString()); + return middleware?.didClose !== void 0 ? middleware.didClose(notebookDocument, cells, send) : send(notebookDocument, cells); + } + asNotebookDocumentChangeEvent(notebook, event, syncInfo, matchingCells) { + if (event !== void 0 && event.notebook !== notebook) { + throw new Error("Notebook must be identical"); + } + const result = { + notebook + }; + if (event?.metadata !== void 0) { + result.metadata = Converter.c2p.asMetadata(event.metadata); + } + let matchingCellsSet; + if (event?.cellChanges !== void 0 && event.cellChanges.length > 0) { + const data = []; + matchingCellsSet = new Set(matchingCells.map((cell) => cell.document.uri.toString())); + for (const cellChange of event.cellChanges) { + if (matchingCellsSet.has(cellChange.cell.document.uri.toString()) && (cellChange.executionSummary !== void 0 || cellChange.metadata !== void 0)) { + data.push(cellChange.cell); + } + } + if (data.length > 0) { + result.cells = result.cells ?? {}; + result.cells.data = data; + } + } + if ((event?.contentChanges !== void 0 && event.contentChanges.length > 0 || event === void 0) && syncInfo !== void 0 && matchingCells !== void 0) { + const oldCells = syncInfo.cells; + const newCells = matchingCells; + const diff = $NotebookCell.computeDiff(oldCells, newCells, false); + let addedCells; + let removedCells; + if (diff !== void 0) { + addedCells = diff.cells === void 0 ? /* @__PURE__ */ new Map() : new Map(diff.cells.map((cell) => [cell.document.uri.toString(), cell])); + removedCells = diff.deleteCount === 0 ? /* @__PURE__ */ new Map() : new Map(oldCells.slice(diff.start, diff.start + diff.deleteCount).map((cell) => [cell.document.uri.toString(), cell])); + for (const key of Array.from(removedCells.keys())) { + if (addedCells.has(key)) { + removedCells.delete(key); + addedCells.delete(key); + } + } + result.cells = result.cells ?? {}; + const didOpen = []; + const didClose = []; + if (addedCells.size > 0 || removedCells.size > 0) { + for (const cell of addedCells.values()) { + didOpen.push(cell); + } + for (const cell of removedCells.values()) { + didClose.push(cell); + } + } + result.cells.structure = { + array: diff, + didOpen, + didClose + }; + } + } + return Object.keys(result).length > 1 ? result : void 0; + } + getMatchingCells(notebookDocument, cells = notebookDocument.getCells()) { + if (this.options.notebookSelector === void 0) { + return void 0; + } + for (const item of this.options.notebookSelector) { + if (item.notebook === void 0 || $NotebookDocumentFilter.matchNotebook(item.notebook, notebookDocument)) { + const filtered = this.filterCells(notebookDocument, cells, item.cells); + return filtered.length === 0 ? void 0 : filtered; + } + } + return void 0; + } + cellMatches(notebookDocument, cell) { + const cells = this.getMatchingCells(notebookDocument, [cell]); + return cells !== void 0 && cells[0] === cell; + } + filterCells(notebookDocument, cells, cellSelector) { + const filtered = cellSelector !== void 0 ? cells.filter((cell) => { + const cellLanguage = cell.document.languageId; + return cellSelector.some(((filter) => filter.language === "*" || cellLanguage === filter.language)); + }) : cells; + return typeof this.client.clientOptions.notebookDocumentOptions?.filterCells === "function" ? this.client.clientOptions.notebookDocumentOptions.filterCells(notebookDocument, filtered) : filtered; + } + }; + var NotebookDocumentSyncFeature = class _NotebookDocumentSyncFeature { + constructor(client2) { + this.client = client2; + this.registrations = /* @__PURE__ */ new Map(); + this.registrationType = proto.NotebookDocumentSyncRegistrationType.type; + vscode12.workspace.onDidOpenTextDocument((textDocument) => { + if (textDocument.uri.scheme !== _NotebookDocumentSyncFeature.CellScheme) { + return; + } + const [notebookDocument, notebookCell] = this.findNotebookDocumentAndCell(textDocument); + if (notebookDocument === void 0 || notebookCell === void 0) { + return; + } + for (const provider of this.registrations.values()) { + if (provider instanceof NotebookDocumentSyncFeatureProvider) { + provider.didOpenNotebookCellTextDocument(notebookDocument, notebookCell); + } + } + }); + vscode12.workspace.onDidChangeTextDocument((event) => { + if (event.contentChanges.length === 0) { + return; + } + const textDocument = event.document; + if (textDocument.uri.scheme !== _NotebookDocumentSyncFeature.CellScheme) { + return; + } + const [notebookDocument] = this.findNotebookDocumentAndCell(textDocument); + if (notebookDocument === void 0) { + return; + } + for (const provider of this.registrations.values()) { + if (provider instanceof NotebookDocumentSyncFeatureProvider) { + provider.didChangeNotebookCellTextDocument(notebookDocument, event); + } + } + }); + vscode12.workspace.onDidCloseTextDocument((textDocument) => { + if (textDocument.uri.scheme !== _NotebookDocumentSyncFeature.CellScheme) { + return; + } + const [notebookDocument, notebookCell] = this.findNotebookDocumentAndCell(textDocument); + if (notebookDocument === void 0 || notebookCell === void 0) { + return; + } + for (const provider of this.registrations.values()) { + if (provider instanceof NotebookDocumentSyncFeatureProvider) { + provider.didCloseNotebookCellTextDocument(notebookDocument, notebookCell); + } + } + }); + } + getState() { + if (this.registrations.size === 0) { + return { kind: "document", id: this.registrationType.method, registrations: false, matches: false }; + } + for (const provider of this.registrations.values()) { + const state = provider.getState(); + if (state.kind === "document" && state.registrations === true && state.matches === true) { + return { kind: "document", id: this.registrationType.method, registrations: true, matches: true }; + } + } + return { kind: "document", id: this.registrationType.method, registrations: true, matches: false }; + } + fillClientCapabilities(capabilities) { + const synchronization = ensure(ensure(capabilities, "notebookDocument"), "synchronization"); + synchronization.dynamicRegistration = true; + synchronization.executionSummarySupport = true; + } + preInitialize(capabilities) { + const options = capabilities.notebookDocumentSync; + if (options === void 0) { + return; + } + this.dedicatedChannel = this.client.protocol2CodeConverter.asDocumentSelector($NotebookDocumentSyncOptions.asDocumentSelector(options)); + } + initialize(capabilities) { + const options = capabilities.notebookDocumentSync; + if (options === void 0) { + return; + } + const id = options.id ?? UUID.generateUuid(); + this.register({ id, registerOptions: options }); + } + register(data) { + const provider = new NotebookDocumentSyncFeatureProvider(this.client, data.registerOptions); + this.registrations.set(data.id, provider); + } + unregister(id) { + const provider = this.registrations.get(id); + provider && provider.dispose(); + } + clear() { + for (const provider of this.registrations.values()) { + provider.dispose(); + } + this.registrations.clear(); + } + handles(textDocument) { + if (textDocument.uri.scheme !== _NotebookDocumentSyncFeature.CellScheme) { + return false; + } + if (this.dedicatedChannel !== void 0 && vscode12.languages.match(this.dedicatedChannel, textDocument) > 0) { + return true; + } + for (const provider of this.registrations.values()) { + if (provider.handles(textDocument)) { + return true; + } + } + return false; + } + getProvider(notebookCell) { + for (const provider of this.registrations.values()) { + if (provider.handles(notebookCell.document)) { + return provider; + } + } + return void 0; + } + findNotebookDocumentAndCell(textDocument) { + const uri = textDocument.uri.toString(); + for (const notebookDocument of vscode12.workspace.notebookDocuments) { + for (const cell of notebookDocument.getCells()) { + if (cell.document.uri.toString() === uri) { + return [notebookDocument, cell]; + } + } + } + return [void 0, void 0]; + } + }; + exports2.NotebookDocumentSyncFeature = NotebookDocumentSyncFeature; + NotebookDocumentSyncFeature.CellScheme = "vscode-notebook-cell"; + } +}); + +// node_modules/vscode-languageclient/lib/common/configuration.js +var require_configuration = __commonJS({ + "node_modules/vscode-languageclient/lib/common/configuration.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SyncConfigurationFeature = exports2.toJSONObject = exports2.ConfigurationFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var Is = require_is(); + var UUID = require_uuid(); + var features_1 = require_features(); + var ConfigurationFeature = class { + constructor(client2) { + this._client = client2; + } + getState() { + return { kind: "static" }; + } + fillClientCapabilities(capabilities) { + capabilities.workspace = capabilities.workspace || {}; + capabilities.workspace.configuration = true; + } + initialize() { + let client2 = this._client; + client2.onRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, (params, token) => { + let configuration = (params2) => { + let result = []; + for (let item of params2.items) { + let resource = item.scopeUri !== void 0 && item.scopeUri !== null ? this._client.protocol2CodeConverter.asUri(item.scopeUri) : void 0; + result.push(this.getConfiguration(resource, item.section !== null ? item.section : void 0)); + } + return result; + }; + let middleware = client2.middleware.workspace; + return middleware && middleware.configuration ? middleware.configuration(params, token, configuration) : configuration(params, token); + }); + } + getConfiguration(resource, section) { + let result = null; + if (section) { + let index = section.lastIndexOf("."); + if (index === -1) { + result = toJSONObject(vscode_1.workspace.getConfiguration(void 0, resource).get(section)); + } else { + let config = vscode_1.workspace.getConfiguration(section.substr(0, index), resource); + if (config) { + result = toJSONObject(config.get(section.substr(index + 1))); + } + } + } else { + let config = vscode_1.workspace.getConfiguration(void 0, resource); + result = {}; + for (let key of Object.keys(config)) { + if (config.has(key)) { + result[key] = toJSONObject(config.get(key)); + } + } + } + if (result === void 0) { + result = null; + } + return result; + } + clear() { + } + }; + exports2.ConfigurationFeature = ConfigurationFeature; + function toJSONObject(obj) { + if (obj) { + if (Array.isArray(obj)) { + return obj.map(toJSONObject); + } else if (typeof obj === "object") { + const res = /* @__PURE__ */ Object.create(null); + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + res[key] = toJSONObject(obj[key]); + } + } + return res; + } + } + return obj; + } + exports2.toJSONObject = toJSONObject; + var SyncConfigurationFeature = class { + constructor(_client) { + this._client = _client; + this.isCleared = false; + this._listeners = /* @__PURE__ */ new Map(); + } + getState() { + return { kind: "workspace", id: this.registrationType.method, registrations: this._listeners.size > 0 }; + } + get registrationType() { + return vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type; + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "didChangeConfiguration").dynamicRegistration = true; + } + initialize() { + this.isCleared = false; + let section = this._client.clientOptions.synchronize?.configurationSection; + if (section !== void 0) { + this.register({ + id: UUID.generateUuid(), + registerOptions: { + section + } + }); + } + } + register(data) { + let disposable = vscode_1.workspace.onDidChangeConfiguration((event) => { + this.onDidChangeConfiguration(data.registerOptions.section, event); + }); + this._listeners.set(data.id, disposable); + if (data.registerOptions.section !== void 0) { + this.onDidChangeConfiguration(data.registerOptions.section, void 0); + } + } + unregister(id) { + let disposable = this._listeners.get(id); + if (disposable) { + this._listeners.delete(id); + disposable.dispose(); + } + } + clear() { + for (const disposable of this._listeners.values()) { + disposable.dispose(); + } + this._listeners.clear(); + this.isCleared = true; + } + onDidChangeConfiguration(configurationSection, event) { + if (this.isCleared) { + return; + } + let sections; + if (Is.string(configurationSection)) { + sections = [configurationSection]; + } else { + sections = configurationSection; + } + if (sections !== void 0 && event !== void 0) { + let affected = sections.some((section) => event.affectsConfiguration(section)); + if (!affected) { + return; + } + } + const didChangeConfiguration = async (sections2) => { + if (sections2 === void 0) { + return this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: null }); + } else { + return this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: this.extractSettingsInformation(sections2) }); + } + }; + let middleware = this._client.middleware.workspace?.didChangeConfiguration; + (middleware ? middleware(sections, didChangeConfiguration) : didChangeConfiguration(sections)).catch((error) => { + this._client.error(`Sending notification ${vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type.method} failed`, error); + }); + } + extractSettingsInformation(keys) { + function ensurePath(config, path8) { + let current = config; + for (let i = 0; i < path8.length - 1; i++) { + let obj = current[path8[i]]; + if (!obj) { + obj = /* @__PURE__ */ Object.create(null); + current[path8[i]] = obj; + } + current = obj; + } + return current; + } + let resource = this._client.clientOptions.workspaceFolder ? this._client.clientOptions.workspaceFolder.uri : void 0; + let result = /* @__PURE__ */ Object.create(null); + for (let i = 0; i < keys.length; i++) { + let key = keys[i]; + let index = key.indexOf("."); + let config = null; + if (index >= 0) { + config = vscode_1.workspace.getConfiguration(key.substr(0, index), resource).get(key.substr(index + 1)); + } else { + config = vscode_1.workspace.getConfiguration(void 0, resource).get(key); + } + if (config) { + let path8 = keys[i].split("."); + ensurePath(result, path8)[path8[path8.length - 1]] = toJSONObject(config); + } + } + return result; + } + }; + exports2.SyncConfigurationFeature = SyncConfigurationFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/textSynchronization.js +var require_textSynchronization = __commonJS({ + "node_modules/vscode-languageclient/lib/common/textSynchronization.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DidSaveTextDocumentFeature = exports2.WillSaveWaitUntilFeature = exports2.WillSaveFeature = exports2.DidChangeTextDocumentFeature = exports2.DidCloseTextDocumentFeature = exports2.DidOpenTextDocumentFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var UUID = require_uuid(); + var DidOpenTextDocumentFeature = class extends features_1.TextDocumentEventFeature { + constructor(client2, syncedDocuments) { + super(client2, vscode_1.workspace.onDidOpenTextDocument, vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, () => client2.middleware.didOpen, (textDocument) => client2.code2ProtocolConverter.asOpenTextDocumentParams(textDocument), (data) => data, features_1.TextDocumentEventFeature.textDocumentFilter); + this._syncedDocuments = syncedDocuments; + } + get openDocuments() { + return this._syncedDocuments.values(); + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization").dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; + if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { + this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector } }); + } + } + get registrationType() { + return vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type; + } + register(data) { + super.register(data); + if (!data.registerOptions.documentSelector) { + return; + } + const documentSelector = this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector); + vscode_1.workspace.textDocuments.forEach((textDocument) => { + const uri = textDocument.uri.toString(); + if (this._syncedDocuments.has(uri)) { + return; + } + if (vscode_1.languages.match(documentSelector, textDocument) > 0 && !this._client.hasDedicatedTextSynchronizationFeature(textDocument)) { + const middleware = this._client.middleware; + const didOpen = (textDocument2) => { + return this._client.sendNotification(this._type, this._createParams(textDocument2)); + }; + (middleware.didOpen ? middleware.didOpen(textDocument, didOpen) : didOpen(textDocument)).catch((error) => { + this._client.error(`Sending document notification ${this._type.method} failed`, error); + }); + this._syncedDocuments.set(uri, textDocument); + } + }); + } + getTextDocument(data) { + return data; + } + notificationSent(textDocument, type, params) { + this._syncedDocuments.set(textDocument.uri.toString(), textDocument); + super.notificationSent(textDocument, type, params); + } + }; + exports2.DidOpenTextDocumentFeature = DidOpenTextDocumentFeature; + var DidCloseTextDocumentFeature = class extends features_1.TextDocumentEventFeature { + constructor(client2, syncedDocuments, pendingTextDocumentChanges) { + super(client2, vscode_1.workspace.onDidCloseTextDocument, vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, () => client2.middleware.didClose, (textDocument) => client2.code2ProtocolConverter.asCloseTextDocumentParams(textDocument), (data) => data, features_1.TextDocumentEventFeature.textDocumentFilter); + this._syncedDocuments = syncedDocuments; + this._pendingTextDocumentChanges = pendingTextDocumentChanges; + } + get registrationType() { + return vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type; + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization").dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; + if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { + this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector } }); + } + } + async callback(data) { + await super.callback(data); + this._pendingTextDocumentChanges.delete(data.uri.toString()); + } + getTextDocument(data) { + return data; + } + notificationSent(textDocument, type, params) { + this._syncedDocuments.delete(textDocument.uri.toString()); + super.notificationSent(textDocument, type, params); + } + unregister(id) { + const selector = this._selectors.get(id); + super.unregister(id); + const selectors = this._selectors.values(); + this._syncedDocuments.forEach((textDocument) => { + if (vscode_1.languages.match(selector, textDocument) > 0 && !this._selectorFilter(selectors, textDocument) && !this._client.hasDedicatedTextSynchronizationFeature(textDocument)) { + let middleware = this._client.middleware; + let didClose = (textDocument2) => { + return this._client.sendNotification(this._type, this._createParams(textDocument2)); + }; + this._syncedDocuments.delete(textDocument.uri.toString()); + (middleware.didClose ? middleware.didClose(textDocument, didClose) : didClose(textDocument)).catch((error) => { + this._client.error(`Sending document notification ${this._type.method} failed`, error); + }); + } + }); + } + }; + exports2.DidCloseTextDocumentFeature = DidCloseTextDocumentFeature; + var DidChangeTextDocumentFeature = class extends features_1.DynamicDocumentFeature { + constructor(client2, pendingTextDocumentChanges) { + super(client2); + this._changeData = /* @__PURE__ */ new Map(); + this._onNotificationSent = new vscode_1.EventEmitter(); + this._onPendingChangeAdded = new vscode_1.EventEmitter(); + this._pendingTextDocumentChanges = pendingTextDocumentChanges; + this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None; + } + get onNotificationSent() { + return this._onNotificationSent.event; + } + get onPendingChangeAdded() { + return this._onPendingChangeAdded.event; + } + get syncKind() { + return this._syncKind; + } + get registrationType() { + return vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type; + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization").dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; + if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.change !== void 0 && textDocumentSyncOptions.change !== vscode_languageserver_protocol_1.TextDocumentSyncKind.None) { + this.register({ + id: UUID.generateUuid(), + registerOptions: Object.assign({}, { documentSelector }, { syncKind: textDocumentSyncOptions.change }) + }); + } + } + register(data) { + if (!data.registerOptions.documentSelector) { + return; + } + if (!this._listener) { + this._listener = vscode_1.workspace.onDidChangeTextDocument(this.callback, this); + } + this._changeData.set(data.id, { + syncKind: data.registerOptions.syncKind, + documentSelector: this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector) + }); + this.updateSyncKind(data.registerOptions.syncKind); + } + *getDocumentSelectors() { + for (const data of this._changeData.values()) { + yield data.documentSelector; + } + } + async callback(event) { + if (event.contentChanges.length === 0) { + return; + } + const uri = event.document.uri; + const version = event.document.version; + const promises = []; + for (const changeData of this._changeData.values()) { + if (vscode_1.languages.match(changeData.documentSelector, event.document) > 0 && !this._client.hasDedicatedTextSynchronizationFeature(event.document)) { + const middleware = this._client.middleware; + if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental) { + const didChange = async (event2) => { + const params = this._client.code2ProtocolConverter.asChangeTextDocumentParams(event2, uri, version); + await this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params); + this.notificationSent(event2.document, vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params); + }; + promises.push(middleware.didChange ? middleware.didChange(event, (event2) => didChange(event2)) : didChange(event)); + } else if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) { + const didChange = async (event2) => { + const eventUri = event2.document.uri.toString(); + this._pendingTextDocumentChanges.set(eventUri, event2.document); + this._onPendingChangeAdded.fire(); + }; + promises.push(middleware.didChange ? middleware.didChange(event, (event2) => didChange(event2)) : didChange(event)); + } + } + } + return Promise.all(promises).then(void 0, (error) => { + this._client.error(`Sending document notification ${vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type.method} failed`, error); + throw error; + }); + } + notificationSent(textDocument, type, params) { + this._onNotificationSent.fire({ textDocument, type, params }); + } + unregister(id) { + this._changeData.delete(id); + if (this._changeData.size === 0) { + if (this._listener) { + this._listener.dispose(); + this._listener = void 0; + } + this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None; + } else { + this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None; + for (const changeData of this._changeData.values()) { + this.updateSyncKind(changeData.syncKind); + if (this._syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) { + break; + } + } + } + } + clear() { + this._pendingTextDocumentChanges.clear(); + this._changeData.clear(); + this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None; + if (this._listener) { + this._listener.dispose(); + this._listener = void 0; + } + } + getPendingDocumentChanges(excludes) { + if (this._pendingTextDocumentChanges.size === 0) { + return []; + } + let result; + if (excludes.size === 0) { + result = Array.from(this._pendingTextDocumentChanges.values()); + this._pendingTextDocumentChanges.clear(); + } else { + result = []; + for (const entry of this._pendingTextDocumentChanges) { + if (!excludes.has(entry[0])) { + result.push(entry[1]); + this._pendingTextDocumentChanges.delete(entry[0]); + } + } + } + return result; + } + getProvider(document) { + for (const changeData of this._changeData.values()) { + if (vscode_1.languages.match(changeData.documentSelector, document) > 0) { + return { + send: (event) => { + return this.callback(event); + } + }; + } + } + return void 0; + } + updateSyncKind(syncKind) { + if (this._syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) { + return; + } + switch (syncKind) { + case vscode_languageserver_protocol_1.TextDocumentSyncKind.Full: + this._syncKind = syncKind; + break; + case vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental: + if (this._syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.None) { + this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental; + } + break; + } + } + }; + exports2.DidChangeTextDocumentFeature = DidChangeTextDocumentFeature; + var WillSaveFeature = class extends features_1.TextDocumentEventFeature { + constructor(client2) { + super(client2, vscode_1.workspace.onWillSaveTextDocument, vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, () => client2.middleware.willSave, (willSaveEvent) => client2.code2ProtocolConverter.asWillSaveTextDocumentParams(willSaveEvent), (event) => event.document, (selectors, willSaveEvent) => features_1.TextDocumentEventFeature.textDocumentFilter(selectors, willSaveEvent.document)); + } + get registrationType() { + return vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type; + } + fillClientCapabilities(capabilities) { + let value = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization"); + value.willSave = true; + } + initialize(capabilities, documentSelector) { + let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; + if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSave) { + this.register({ + id: UUID.generateUuid(), + registerOptions: { documentSelector } + }); + } + } + getTextDocument(data) { + return data.document; + } + }; + exports2.WillSaveFeature = WillSaveFeature; + var WillSaveWaitUntilFeature = class extends features_1.DynamicDocumentFeature { + constructor(client2) { + super(client2); + this._selectors = /* @__PURE__ */ new Map(); + } + getDocumentSelectors() { + return this._selectors.values(); + } + get registrationType() { + return vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type; + } + fillClientCapabilities(capabilities) { + let value = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization"); + value.willSaveWaitUntil = true; + } + initialize(capabilities, documentSelector) { + let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; + if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSaveWaitUntil) { + this.register({ + id: UUID.generateUuid(), + registerOptions: { documentSelector } + }); + } + } + register(data) { + if (!data.registerOptions.documentSelector) { + return; + } + if (!this._listener) { + this._listener = vscode_1.workspace.onWillSaveTextDocument(this.callback, this); + } + this._selectors.set(data.id, this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector)); + } + callback(event) { + if (features_1.TextDocumentEventFeature.textDocumentFilter(this._selectors.values(), event.document) && !this._client.hasDedicatedTextSynchronizationFeature(event.document)) { + let middleware = this._client.middleware; + let willSaveWaitUntil = (event2) => { + return this._client.sendRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, this._client.code2ProtocolConverter.asWillSaveTextDocumentParams(event2)).then(async (edits) => { + let vEdits = await this._client.protocol2CodeConverter.asTextEdits(edits); + return vEdits === void 0 ? [] : vEdits; + }); + }; + event.waitUntil(middleware.willSaveWaitUntil ? middleware.willSaveWaitUntil(event, willSaveWaitUntil) : willSaveWaitUntil(event)); + } + } + unregister(id) { + this._selectors.delete(id); + if (this._selectors.size === 0 && this._listener) { + this._listener.dispose(); + this._listener = void 0; + } + } + clear() { + this._selectors.clear(); + if (this._listener) { + this._listener.dispose(); + this._listener = void 0; + } + } + }; + exports2.WillSaveWaitUntilFeature = WillSaveWaitUntilFeature; + var DidSaveTextDocumentFeature = class extends features_1.TextDocumentEventFeature { + constructor(client2) { + super(client2, vscode_1.workspace.onDidSaveTextDocument, vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, () => client2.middleware.didSave, (textDocument) => client2.code2ProtocolConverter.asSaveTextDocumentParams(textDocument, this._includeText), (data) => data, features_1.TextDocumentEventFeature.textDocumentFilter); + this._includeText = false; + } + get registrationType() { + return vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type; + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization").didSave = true; + } + initialize(capabilities, documentSelector) { + const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; + if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.save) { + const saveOptions = typeof textDocumentSyncOptions.save === "boolean" ? { includeText: false } : { includeText: !!textDocumentSyncOptions.save.includeText }; + this.register({ + id: UUID.generateUuid(), + registerOptions: Object.assign({}, { documentSelector }, saveOptions) + }); + } + } + register(data) { + this._includeText = !!data.registerOptions.includeText; + super.register(data); + } + getTextDocument(data) { + return data; + } + }; + exports2.DidSaveTextDocumentFeature = DidSaveTextDocumentFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/completion.js +var require_completion = __commonJS({ + "node_modules/vscode-languageclient/lib/common/completion.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CompletionItemFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var UUID = require_uuid(); + var SupportedCompletionItemKinds = [ + vscode_languageserver_protocol_1.CompletionItemKind.Text, + vscode_languageserver_protocol_1.CompletionItemKind.Method, + vscode_languageserver_protocol_1.CompletionItemKind.Function, + vscode_languageserver_protocol_1.CompletionItemKind.Constructor, + vscode_languageserver_protocol_1.CompletionItemKind.Field, + vscode_languageserver_protocol_1.CompletionItemKind.Variable, + vscode_languageserver_protocol_1.CompletionItemKind.Class, + vscode_languageserver_protocol_1.CompletionItemKind.Interface, + vscode_languageserver_protocol_1.CompletionItemKind.Module, + vscode_languageserver_protocol_1.CompletionItemKind.Property, + vscode_languageserver_protocol_1.CompletionItemKind.Unit, + vscode_languageserver_protocol_1.CompletionItemKind.Value, + vscode_languageserver_protocol_1.CompletionItemKind.Enum, + vscode_languageserver_protocol_1.CompletionItemKind.Keyword, + vscode_languageserver_protocol_1.CompletionItemKind.Snippet, + vscode_languageserver_protocol_1.CompletionItemKind.Color, + vscode_languageserver_protocol_1.CompletionItemKind.File, + vscode_languageserver_protocol_1.CompletionItemKind.Reference, + vscode_languageserver_protocol_1.CompletionItemKind.Folder, + vscode_languageserver_protocol_1.CompletionItemKind.EnumMember, + vscode_languageserver_protocol_1.CompletionItemKind.Constant, + vscode_languageserver_protocol_1.CompletionItemKind.Struct, + vscode_languageserver_protocol_1.CompletionItemKind.Event, + vscode_languageserver_protocol_1.CompletionItemKind.Operator, + vscode_languageserver_protocol_1.CompletionItemKind.TypeParameter + ]; + var CompletionItemFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.CompletionRequest.type); + this.labelDetailsSupport = /* @__PURE__ */ new Map(); + } + fillClientCapabilities(capabilities) { + let completion = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "completion"); + completion.dynamicRegistration = true; + completion.contextSupport = true; + completion.completionItem = { + snippetSupport: true, + commitCharactersSupport: true, + documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText], + deprecatedSupport: true, + preselectSupport: true, + tagSupport: { valueSet: [vscode_languageserver_protocol_1.CompletionItemTag.Deprecated] }, + insertReplaceSupport: true, + resolveSupport: { + properties: ["documentation", "detail", "additionalTextEdits"] + }, + insertTextModeSupport: { valueSet: [vscode_languageserver_protocol_1.InsertTextMode.asIs, vscode_languageserver_protocol_1.InsertTextMode.adjustIndentation] }, + labelDetailsSupport: true + }; + completion.insertTextMode = vscode_languageserver_protocol_1.InsertTextMode.adjustIndentation; + completion.completionItemKind = { valueSet: SupportedCompletionItemKinds }; + completion.completionList = { + itemDefaults: [ + "commitCharacters", + "editRange", + "insertTextFormat", + "insertTextMode", + "data" + ] + }; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.completionProvider); + if (!options) { + return; + } + this.register({ + id: UUID.generateUuid(), + registerOptions: options + }); + } + registerLanguageProvider(options, id) { + this.labelDetailsSupport.set(id, !!options.completionItem?.labelDetailsSupport); + const triggerCharacters = options.triggerCharacters ?? []; + const defaultCommitCharacters = options.allCommitCharacters; + const selector = options.documentSelector; + const provider = { + provideCompletionItems: (document, position, token, context) => { + const client2 = this._client; + const middleware = this._client.middleware; + const provideCompletionItems = (document2, position2, context2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.CompletionRequest.type, client2.code2ProtocolConverter.asCompletionParams(document2, position2, context2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asCompletionResult(result, defaultCommitCharacters, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.CompletionRequest.type, token2, error, null); + }); + }; + return middleware.provideCompletionItem ? middleware.provideCompletionItem(document, position, context, token, provideCompletionItems) : provideCompletionItems(document, position, context, token); + }, + resolveCompletionItem: options.resolveProvider ? (item, token) => { + const client2 = this._client; + const middleware = this._client.middleware; + const resolveCompletionItem = (item2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, client2.code2ProtocolConverter.asCompletionItem(item2, !!this.labelDetailsSupport.get(id)), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asCompletionItem(result); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, token2, error, item2); + }); + }; + return middleware.resolveCompletionItem ? middleware.resolveCompletionItem(item, token, resolveCompletionItem) : resolveCompletionItem(item, token); + } : void 0 + }; + return [vscode_1.languages.registerCompletionItemProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, ...triggerCharacters), provider]; + } + }; + exports2.CompletionItemFeature = CompletionItemFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/hover.js +var require_hover = __commonJS({ + "node_modules/vscode-languageclient/lib/common/hover.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HoverFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var UUID = require_uuid(); + var HoverFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.HoverRequest.type); + } + fillClientCapabilities(capabilities) { + const hoverCapability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "hover"); + hoverCapability.dynamicRegistration = true; + hoverCapability.contentFormat = [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText]; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.hoverProvider); + if (!options) { + return; + } + this.register({ + id: UUID.generateUuid(), + registerOptions: options + }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideHover: (document, position, token) => { + const client2 = this._client; + const provideHover = (document2, position2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.HoverRequest.type, client2.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asHover(result); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.HoverRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideHover ? middleware.provideHover(document, position, token, provideHover) : provideHover(document, position, token); + } + }; + return [this.registerProvider(selector, provider), provider]; + } + registerProvider(selector, provider) { + return vscode_1.languages.registerHoverProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider); + } + }; + exports2.HoverFeature = HoverFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/definition.js +var require_definition = __commonJS({ + "node_modules/vscode-languageclient/lib/common/definition.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DefinitionFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var UUID = require_uuid(); + var DefinitionFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.DefinitionRequest.type); + } + fillClientCapabilities(capabilities) { + let definitionSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "definition"); + definitionSupport.dynamicRegistration = true; + definitionSupport.linkSupport = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.definitionProvider); + if (!options) { + return; + } + this.register({ id: UUID.generateUuid(), registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideDefinition: (document, position, token) => { + const client2 = this._client; + const provideDefinition = (document2, position2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, client2.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asDefinitionResult(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideDefinition ? middleware.provideDefinition(document, position, token, provideDefinition) : provideDefinition(document, position, token); + } + }; + return [this.registerProvider(selector, provider), provider]; + } + registerProvider(selector, provider) { + return vscode_1.languages.registerDefinitionProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider); + } + }; + exports2.DefinitionFeature = DefinitionFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/signatureHelp.js +var require_signatureHelp = __commonJS({ + "node_modules/vscode-languageclient/lib/common/signatureHelp.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SignatureHelpFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var UUID = require_uuid(); + var SignatureHelpFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.SignatureHelpRequest.type); + } + fillClientCapabilities(capabilities) { + let config = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "signatureHelp"); + config.dynamicRegistration = true; + config.signatureInformation = { documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText] }; + config.signatureInformation.parameterInformation = { labelOffsetSupport: true }; + config.signatureInformation.activeParameterSupport = true; + config.contextSupport = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.signatureHelpProvider); + if (!options) { + return; + } + this.register({ + id: UUID.generateUuid(), + registerOptions: options + }); + } + registerLanguageProvider(options) { + const provider = { + provideSignatureHelp: (document, position, token, context) => { + const client2 = this._client; + const providerSignatureHelp = (document2, position2, context2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, client2.code2ProtocolConverter.asSignatureHelpParams(document2, position2, context2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asSignatureHelp(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideSignatureHelp ? middleware.provideSignatureHelp(document, position, context, token, providerSignatureHelp) : providerSignatureHelp(document, position, context, token); + } + }; + return [this.registerProvider(options, provider), provider]; + } + registerProvider(options, provider) { + const selector = this._client.protocol2CodeConverter.asDocumentSelector(options.documentSelector); + if (options.retriggerCharacters === void 0) { + const triggerCharacters = options.triggerCharacters || []; + return vscode_1.languages.registerSignatureHelpProvider(selector, provider, ...triggerCharacters); + } else { + const metaData = { + triggerCharacters: options.triggerCharacters || [], + retriggerCharacters: options.retriggerCharacters || [] + }; + return vscode_1.languages.registerSignatureHelpProvider(selector, provider, metaData); + } + } + }; + exports2.SignatureHelpFeature = SignatureHelpFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/documentHighlight.js +var require_documentHighlight = __commonJS({ + "node_modules/vscode-languageclient/lib/common/documentHighlight.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DocumentHighlightFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var UUID = require_uuid(); + var DocumentHighlightFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.DocumentHighlightRequest.type); + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "documentHighlight").dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.documentHighlightProvider); + if (!options) { + return; + } + this.register({ id: UUID.generateUuid(), registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideDocumentHighlights: (document, position, token) => { + const client2 = this._client; + const _provideDocumentHighlights = (document2, position2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, client2.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asDocumentHighlights(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideDocumentHighlights ? middleware.provideDocumentHighlights(document, position, token, _provideDocumentHighlights) : _provideDocumentHighlights(document, position, token); + } + }; + return [vscode_1.languages.registerDocumentHighlightProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider]; + } + }; + exports2.DocumentHighlightFeature = DocumentHighlightFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/documentSymbol.js +var require_documentSymbol = __commonJS({ + "node_modules/vscode-languageclient/lib/common/documentSymbol.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DocumentSymbolFeature = exports2.SupportedSymbolTags = exports2.SupportedSymbolKinds = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var UUID = require_uuid(); + exports2.SupportedSymbolKinds = [ + vscode_languageserver_protocol_1.SymbolKind.File, + vscode_languageserver_protocol_1.SymbolKind.Module, + vscode_languageserver_protocol_1.SymbolKind.Namespace, + vscode_languageserver_protocol_1.SymbolKind.Package, + vscode_languageserver_protocol_1.SymbolKind.Class, + vscode_languageserver_protocol_1.SymbolKind.Method, + vscode_languageserver_protocol_1.SymbolKind.Property, + vscode_languageserver_protocol_1.SymbolKind.Field, + vscode_languageserver_protocol_1.SymbolKind.Constructor, + vscode_languageserver_protocol_1.SymbolKind.Enum, + vscode_languageserver_protocol_1.SymbolKind.Interface, + vscode_languageserver_protocol_1.SymbolKind.Function, + vscode_languageserver_protocol_1.SymbolKind.Variable, + vscode_languageserver_protocol_1.SymbolKind.Constant, + vscode_languageserver_protocol_1.SymbolKind.String, + vscode_languageserver_protocol_1.SymbolKind.Number, + vscode_languageserver_protocol_1.SymbolKind.Boolean, + vscode_languageserver_protocol_1.SymbolKind.Array, + vscode_languageserver_protocol_1.SymbolKind.Object, + vscode_languageserver_protocol_1.SymbolKind.Key, + vscode_languageserver_protocol_1.SymbolKind.Null, + vscode_languageserver_protocol_1.SymbolKind.EnumMember, + vscode_languageserver_protocol_1.SymbolKind.Struct, + vscode_languageserver_protocol_1.SymbolKind.Event, + vscode_languageserver_protocol_1.SymbolKind.Operator, + vscode_languageserver_protocol_1.SymbolKind.TypeParameter + ]; + exports2.SupportedSymbolTags = [ + vscode_languageserver_protocol_1.SymbolTag.Deprecated + ]; + var DocumentSymbolFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.DocumentSymbolRequest.type); + } + fillClientCapabilities(capabilities) { + let symbolCapabilities = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "documentSymbol"); + symbolCapabilities.dynamicRegistration = true; + symbolCapabilities.symbolKind = { + valueSet: exports2.SupportedSymbolKinds + }; + symbolCapabilities.hierarchicalDocumentSymbolSupport = true; + symbolCapabilities.tagSupport = { + valueSet: exports2.SupportedSymbolTags + }; + symbolCapabilities.labelSupport = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.documentSymbolProvider); + if (!options) { + return; + } + this.register({ id: UUID.generateUuid(), registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideDocumentSymbols: (document, token) => { + const client2 = this._client; + const _provideDocumentSymbols = async (document2, token2) => { + try { + const data = await client2.sendRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, client2.code2ProtocolConverter.asDocumentSymbolParams(document2), token2); + if (token2.isCancellationRequested || data === void 0 || data === null) { + return null; + } + if (data.length === 0) { + return []; + } else { + const first = data[0]; + if (vscode_languageserver_protocol_1.DocumentSymbol.is(first)) { + return await client2.protocol2CodeConverter.asDocumentSymbols(data, token2); + } else { + return await client2.protocol2CodeConverter.asSymbolInformations(data, token2); + } + } + } catch (error) { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, token2, error, null); + } + }; + const middleware = client2.middleware; + return middleware.provideDocumentSymbols ? middleware.provideDocumentSymbols(document, token, _provideDocumentSymbols) : _provideDocumentSymbols(document, token); + } + }; + const metaData = options.label !== void 0 ? { label: options.label } : void 0; + return [vscode_1.languages.registerDocumentSymbolProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, metaData), provider]; + } + }; + exports2.DocumentSymbolFeature = DocumentSymbolFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/workspaceSymbol.js +var require_workspaceSymbol = __commonJS({ + "node_modules/vscode-languageclient/lib/common/workspaceSymbol.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WorkspaceSymbolFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var documentSymbol_1 = require_documentSymbol(); + var UUID = require_uuid(); + var WorkspaceSymbolFeature = class extends features_1.WorkspaceFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type); + } + fillClientCapabilities(capabilities) { + let symbolCapabilities = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "symbol"); + symbolCapabilities.dynamicRegistration = true; + symbolCapabilities.symbolKind = { + valueSet: documentSymbol_1.SupportedSymbolKinds + }; + symbolCapabilities.tagSupport = { + valueSet: documentSymbol_1.SupportedSymbolTags + }; + symbolCapabilities.resolveSupport = { properties: ["location.range"] }; + } + initialize(capabilities) { + if (!capabilities.workspaceSymbolProvider) { + return; + } + this.register({ + id: UUID.generateUuid(), + registerOptions: capabilities.workspaceSymbolProvider === true ? { workDoneProgress: false } : capabilities.workspaceSymbolProvider + }); + } + registerLanguageProvider(options) { + const provider = { + provideWorkspaceSymbols: (query, token) => { + const client2 = this._client; + const provideWorkspaceSymbols = (query2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, { query: query2 }, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asSymbolInformations(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideWorkspaceSymbols ? middleware.provideWorkspaceSymbols(query, token, provideWorkspaceSymbols) : provideWorkspaceSymbols(query, token); + }, + resolveWorkspaceSymbol: options.resolveProvider === true ? (item, token) => { + const client2 = this._client; + const resolveWorkspaceSymbol = (item2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.type, client2.code2ProtocolConverter.asWorkspaceSymbol(item2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asSymbolInformation(result); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.resolveWorkspaceSymbol ? middleware.resolveWorkspaceSymbol(item, token, resolveWorkspaceSymbol) : resolveWorkspaceSymbol(item, token); + } : void 0 + }; + return [vscode_1.languages.registerWorkspaceSymbolProvider(provider), provider]; + } + }; + exports2.WorkspaceSymbolFeature = WorkspaceSymbolFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/reference.js +var require_reference = __commonJS({ + "node_modules/vscode-languageclient/lib/common/reference.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReferencesFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var UUID = require_uuid(); + var ReferencesFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.ReferencesRequest.type); + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "references").dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.referencesProvider); + if (!options) { + return; + } + this.register({ id: UUID.generateUuid(), registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideReferences: (document, position, options2, token) => { + const client2 = this._client; + const _providerReferences = (document2, position2, options3, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, client2.code2ProtocolConverter.asReferenceParams(document2, position2, options3), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asReferences(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideReferences ? middleware.provideReferences(document, position, options2, token, _providerReferences) : _providerReferences(document, position, options2, token); + } + }; + return [this.registerProvider(selector, provider), provider]; + } + registerProvider(selector, provider) { + return vscode_1.languages.registerReferenceProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider); + } + }; + exports2.ReferencesFeature = ReferencesFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/codeAction.js +var require_codeAction = __commonJS({ + "node_modules/vscode-languageclient/lib/common/codeAction.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CodeActionFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var UUID = require_uuid(); + var features_1 = require_features(); + var CodeActionFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.CodeActionRequest.type); + } + fillClientCapabilities(capabilities) { + const cap = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "codeAction"); + cap.dynamicRegistration = true; + cap.isPreferredSupport = true; + cap.disabledSupport = true; + cap.dataSupport = true; + cap.resolveSupport = { + properties: ["edit"] + }; + cap.codeActionLiteralSupport = { + codeActionKind: { + valueSet: [ + vscode_languageserver_protocol_1.CodeActionKind.Empty, + vscode_languageserver_protocol_1.CodeActionKind.QuickFix, + vscode_languageserver_protocol_1.CodeActionKind.Refactor, + vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract, + vscode_languageserver_protocol_1.CodeActionKind.RefactorInline, + vscode_languageserver_protocol_1.CodeActionKind.RefactorRewrite, + vscode_languageserver_protocol_1.CodeActionKind.Source, + vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports + ] + } + }; + cap.honorsChangeAnnotations = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.codeActionProvider); + if (!options) { + return; + } + this.register({ id: UUID.generateUuid(), registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideCodeActions: (document, range, context, token) => { + const client2 = this._client; + const _provideCodeActions = async (document2, range2, context2, token2) => { + const params = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2), + range: client2.code2ProtocolConverter.asRange(range2), + context: client2.code2ProtocolConverter.asCodeActionContextSync(context2) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, params, token2).then((values) => { + if (token2.isCancellationRequested || values === null || values === void 0) { + return null; + } + return client2.protocol2CodeConverter.asCodeActionResult(values, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideCodeActions ? middleware.provideCodeActions(document, range, context, token, _provideCodeActions) : _provideCodeActions(document, range, context, token); + }, + resolveCodeAction: options.resolveProvider ? (item, token) => { + const client2 = this._client; + const middleware = this._client.middleware; + const resolveCodeAction = async (item2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, client2.code2ProtocolConverter.asCodeActionSync(item2), token2).then((result) => { + if (token2.isCancellationRequested) { + return item2; + } + return client2.protocol2CodeConverter.asCodeAction(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, token2, error, item2); + }); + }; + return middleware.resolveCodeAction ? middleware.resolveCodeAction(item, token, resolveCodeAction) : resolveCodeAction(item, token); + } : void 0 + }; + return [vscode_1.languages.registerCodeActionsProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, options.codeActionKinds ? { providedCodeActionKinds: this._client.protocol2CodeConverter.asCodeActionKinds(options.codeActionKinds) } : void 0), provider]; + } + }; + exports2.CodeActionFeature = CodeActionFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/codeLens.js +var require_codeLens = __commonJS({ + "node_modules/vscode-languageclient/lib/common/codeLens.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CodeLensFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var UUID = require_uuid(); + var features_1 = require_features(); + var CodeLensFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.CodeLensRequest.type); + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "codeLens").dynamicRegistration = true; + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "codeLens").refreshSupport = true; + } + initialize(capabilities, documentSelector) { + const client2 = this._client; + client2.onRequest(vscode_languageserver_protocol_1.CodeLensRefreshRequest.type, async () => { + for (const provider of this.getAllProviders()) { + provider.onDidChangeCodeLensEmitter.fire(); + } + }); + const options = this.getRegistrationOptions(documentSelector, capabilities.codeLensProvider); + if (!options) { + return; + } + this.register({ id: UUID.generateUuid(), registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const eventEmitter = new vscode_1.EventEmitter(); + const provider = { + onDidChangeCodeLenses: eventEmitter.event, + provideCodeLenses: (document, token) => { + const client2 = this._client; + const provideCodeLenses = (document2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, client2.code2ProtocolConverter.asCodeLensParams(document2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asCodeLenses(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideCodeLenses ? middleware.provideCodeLenses(document, token, provideCodeLenses) : provideCodeLenses(document, token); + }, + resolveCodeLens: options.resolveProvider ? (codeLens, token) => { + const client2 = this._client; + const resolveCodeLens = (codeLens2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, client2.code2ProtocolConverter.asCodeLens(codeLens2), token2).then((result) => { + if (token2.isCancellationRequested) { + return codeLens2; + } + return client2.protocol2CodeConverter.asCodeLens(result); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, token2, error, codeLens2); + }); + }; + const middleware = client2.middleware; + return middleware.resolveCodeLens ? middleware.resolveCodeLens(codeLens, token, resolveCodeLens) : resolveCodeLens(codeLens, token); + } : void 0 + }; + return [vscode_1.languages.registerCodeLensProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), { provider, onDidChangeCodeLensEmitter: eventEmitter }]; + } + }; + exports2.CodeLensFeature = CodeLensFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/formatting.js +var require_formatting = __commonJS({ + "node_modules/vscode-languageclient/lib/common/formatting.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DocumentOnTypeFormattingFeature = exports2.DocumentRangeFormattingFeature = exports2.DocumentFormattingFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var UUID = require_uuid(); + var features_1 = require_features(); + var FileFormattingOptions; + (function(FileFormattingOptions2) { + function fromConfiguration(document) { + const filesConfig = vscode_1.workspace.getConfiguration("files", document); + return { + trimTrailingWhitespace: filesConfig.get("trimTrailingWhitespace"), + trimFinalNewlines: filesConfig.get("trimFinalNewlines"), + insertFinalNewline: filesConfig.get("insertFinalNewline") + }; + } + FileFormattingOptions2.fromConfiguration = fromConfiguration; + })(FileFormattingOptions || (FileFormattingOptions = {})); + var DocumentFormattingFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.DocumentFormattingRequest.type); + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "formatting").dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.documentFormattingProvider); + if (!options) { + return; + } + this.register({ id: UUID.generateUuid(), registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideDocumentFormattingEdits: (document, options2, token) => { + const client2 = this._client; + const provideDocumentFormattingEdits = (document2, options3, token2) => { + const params = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2), + options: client2.code2ProtocolConverter.asFormattingOptions(options3, FileFormattingOptions.fromConfiguration(document2)) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asTextEdits(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideDocumentFormattingEdits ? middleware.provideDocumentFormattingEdits(document, options2, token, provideDocumentFormattingEdits) : provideDocumentFormattingEdits(document, options2, token); + } + }; + return [vscode_1.languages.registerDocumentFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider]; + } + }; + exports2.DocumentFormattingFeature = DocumentFormattingFeature; + var DocumentRangeFormattingFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type); + } + fillClientCapabilities(capabilities) { + const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "rangeFormatting"); + capability.dynamicRegistration = true; + capability.rangesSupport = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.documentRangeFormattingProvider); + if (!options) { + return; + } + this.register({ id: UUID.generateUuid(), registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideDocumentRangeFormattingEdits: (document, range, options2, token) => { + const client2 = this._client; + const provideDocumentRangeFormattingEdits = (document2, range2, options3, token2) => { + const params = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2), + range: client2.code2ProtocolConverter.asRange(range2), + options: client2.code2ProtocolConverter.asFormattingOptions(options3, FileFormattingOptions.fromConfiguration(document2)) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asTextEdits(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideDocumentRangeFormattingEdits ? middleware.provideDocumentRangeFormattingEdits(document, range, options2, token, provideDocumentRangeFormattingEdits) : provideDocumentRangeFormattingEdits(document, range, options2, token); + } + }; + if (options.rangesSupport) { + provider.provideDocumentRangesFormattingEdits = (document, ranges, options2, token) => { + const client2 = this._client; + const provideDocumentRangesFormattingEdits = (document2, ranges2, options3, token2) => { + const params = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2), + ranges: client2.code2ProtocolConverter.asRanges(ranges2), + options: client2.code2ProtocolConverter.asFormattingOptions(options3, FileFormattingOptions.fromConfiguration(document2)) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.DocumentRangesFormattingRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asTextEdits(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.DocumentRangesFormattingRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideDocumentRangesFormattingEdits ? middleware.provideDocumentRangesFormattingEdits(document, ranges, options2, token, provideDocumentRangesFormattingEdits) : provideDocumentRangesFormattingEdits(document, ranges, options2, token); + }; + } + return [vscode_1.languages.registerDocumentRangeFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider]; + } + }; + exports2.DocumentRangeFormattingFeature = DocumentRangeFormattingFeature; + var DocumentOnTypeFormattingFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type); + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "onTypeFormatting").dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.documentOnTypeFormattingProvider); + if (!options) { + return; + } + this.register({ id: UUID.generateUuid(), registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideOnTypeFormattingEdits: (document, position, ch, options2, token) => { + const client2 = this._client; + const provideOnTypeFormattingEdits = (document2, position2, ch2, options3, token2) => { + let params = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2), + position: client2.code2ProtocolConverter.asPosition(position2), + ch: ch2, + options: client2.code2ProtocolConverter.asFormattingOptions(options3, FileFormattingOptions.fromConfiguration(document2)) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asTextEdits(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideOnTypeFormattingEdits ? middleware.provideOnTypeFormattingEdits(document, position, ch, options2, token, provideOnTypeFormattingEdits) : provideOnTypeFormattingEdits(document, position, ch, options2, token); + } + }; + const moreTriggerCharacter = options.moreTriggerCharacter || []; + return [vscode_1.languages.registerOnTypeFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, options.firstTriggerCharacter, ...moreTriggerCharacter), provider]; + } + }; + exports2.DocumentOnTypeFormattingFeature = DocumentOnTypeFormattingFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/rename.js +var require_rename = __commonJS({ + "node_modules/vscode-languageclient/lib/common/rename.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RenameFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var UUID = require_uuid(); + var Is = require_is(); + var features_1 = require_features(); + var RenameFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.RenameRequest.type); + } + fillClientCapabilities(capabilities) { + let rename = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "rename"); + rename.dynamicRegistration = true; + rename.prepareSupport = true; + rename.prepareSupportDefaultBehavior = vscode_languageserver_protocol_1.PrepareSupportDefaultBehavior.Identifier; + rename.honorsChangeAnnotations = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.renameProvider); + if (!options) { + return; + } + if (Is.boolean(capabilities.renameProvider)) { + options.prepareProvider = false; + } + this.register({ id: UUID.generateUuid(), registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideRenameEdits: (document, position, newName, token) => { + const client2 = this._client; + const provideRenameEdits = (document2, position2, newName2, token2) => { + let params = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2), + position: client2.code2ProtocolConverter.asPosition(position2), + newName: newName2 + }; + return client2.sendRequest(vscode_languageserver_protocol_1.RenameRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asWorkspaceEdit(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.RenameRequest.type, token2, error, null, false); + }); + }; + const middleware = client2.middleware; + return middleware.provideRenameEdits ? middleware.provideRenameEdits(document, position, newName, token, provideRenameEdits) : provideRenameEdits(document, position, newName, token); + }, + prepareRename: options.prepareProvider ? (document, position, token) => { + const client2 = this._client; + const prepareRename = (document2, position2, token2) => { + let params = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2), + position: client2.code2ProtocolConverter.asPosition(position2) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + if (vscode_languageserver_protocol_1.Range.is(result)) { + return client2.protocol2CodeConverter.asRange(result); + } else if (this.isDefaultBehavior(result)) { + return result.defaultBehavior === true ? null : Promise.reject(new Error(`The element can't be renamed.`)); + } else if (result && vscode_languageserver_protocol_1.Range.is(result.range)) { + return { + range: client2.protocol2CodeConverter.asRange(result.range), + placeholder: result.placeholder + }; + } + return Promise.reject(new Error(`The element can't be renamed.`)); + }, (error) => { + if (typeof error.message === "string") { + throw new Error(error.message); + } else { + throw new Error(`The element can't be renamed.`); + } + }); + }; + const middleware = client2.middleware; + return middleware.prepareRename ? middleware.prepareRename(document, position, token, prepareRename) : prepareRename(document, position, token); + } : void 0 + }; + return [this.registerProvider(selector, provider), provider]; + } + registerProvider(selector, provider) { + return vscode_1.languages.registerRenameProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider); + } + isDefaultBehavior(value) { + const candidate = value; + return candidate && Is.boolean(candidate.defaultBehavior); + } + }; + exports2.RenameFeature = RenameFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/documentLink.js +var require_documentLink = __commonJS({ + "node_modules/vscode-languageclient/lib/common/documentLink.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DocumentLinkFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var UUID = require_uuid(); + var DocumentLinkFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.DocumentLinkRequest.type); + } + fillClientCapabilities(capabilities) { + const documentLinkCapabilities = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "documentLink"); + documentLinkCapabilities.dynamicRegistration = true; + documentLinkCapabilities.tooltipSupport = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.documentLinkProvider); + if (!options) { + return; + } + this.register({ id: UUID.generateUuid(), registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideDocumentLinks: (document, token) => { + const client2 = this._client; + const provideDocumentLinks = (document2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, client2.code2ProtocolConverter.asDocumentLinkParams(document2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asDocumentLinks(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideDocumentLinks ? middleware.provideDocumentLinks(document, token, provideDocumentLinks) : provideDocumentLinks(document, token); + }, + resolveDocumentLink: options.resolveProvider ? (link, token) => { + const client2 = this._client; + let resolveDocumentLink = (link2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, client2.code2ProtocolConverter.asDocumentLink(link2), token2).then((result) => { + if (token2.isCancellationRequested) { + return link2; + } + return client2.protocol2CodeConverter.asDocumentLink(result); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, token2, error, link2); + }); + }; + const middleware = client2.middleware; + return middleware.resolveDocumentLink ? middleware.resolveDocumentLink(link, token, resolveDocumentLink) : resolveDocumentLink(link, token); + } : void 0 + }; + return [vscode_1.languages.registerDocumentLinkProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider]; + } + }; + exports2.DocumentLinkFeature = DocumentLinkFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/executeCommand.js +var require_executeCommand = __commonJS({ + "node_modules/vscode-languageclient/lib/common/executeCommand.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ExecuteCommandFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var UUID = require_uuid(); + var features_1 = require_features(); + var ExecuteCommandFeature = class { + constructor(client2) { + this._client = client2; + this._commands = /* @__PURE__ */ new Map(); + } + getState() { + return { kind: "workspace", id: this.registrationType.method, registrations: this._commands.size > 0 }; + } + get registrationType() { + return vscode_languageserver_protocol_1.ExecuteCommandRequest.type; + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "executeCommand").dynamicRegistration = true; + } + initialize(capabilities) { + if (!capabilities.executeCommandProvider) { + return; + } + this.register({ + id: UUID.generateUuid(), + registerOptions: Object.assign({}, capabilities.executeCommandProvider) + }); + } + register(data) { + const client2 = this._client; + const middleware = client2.middleware; + const executeCommand = (command, args) => { + let params = { + command, + arguments: args + }; + return client2.sendRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, params).then(void 0, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, void 0, error, void 0); + }); + }; + if (data.registerOptions.commands) { + const disposables = []; + for (const command of data.registerOptions.commands) { + disposables.push(vscode_1.commands.registerCommand(command, (...args) => { + return middleware.executeCommand ? middleware.executeCommand(command, args, executeCommand) : executeCommand(command, args); + })); + } + this._commands.set(data.id, disposables); + } + } + unregister(id) { + let disposables = this._commands.get(id); + if (disposables) { + disposables.forEach((disposable) => disposable.dispose()); + } + } + clear() { + this._commands.forEach((value) => { + value.forEach((disposable) => disposable.dispose()); + }); + this._commands.clear(); + } + }; + exports2.ExecuteCommandFeature = ExecuteCommandFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/fileSystemWatcher.js +var require_fileSystemWatcher = __commonJS({ + "node_modules/vscode-languageclient/lib/common/fileSystemWatcher.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.FileSystemWatcherFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var FileSystemWatcherFeature = class { + constructor(client2, notifyFileEvent) { + this._client = client2; + this._notifyFileEvent = notifyFileEvent; + this._watchers = /* @__PURE__ */ new Map(); + } + getState() { + return { kind: "workspace", id: this.registrationType.method, registrations: this._watchers.size > 0 }; + } + get registrationType() { + return vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type; + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "didChangeWatchedFiles").dynamicRegistration = true; + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "didChangeWatchedFiles").relativePatternSupport = true; + } + initialize(_capabilities, _documentSelector) { + } + register(data) { + if (!Array.isArray(data.registerOptions.watchers)) { + return; + } + const disposables = []; + for (const watcher of data.registerOptions.watchers) { + const globPattern = this._client.protocol2CodeConverter.asGlobPattern(watcher.globPattern); + if (globPattern === void 0) { + continue; + } + let watchCreate = true, watchChange = true, watchDelete = true; + if (watcher.kind !== void 0 && watcher.kind !== null) { + watchCreate = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Create) !== 0; + watchChange = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Change) !== 0; + watchDelete = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Delete) !== 0; + } + const fileSystemWatcher = vscode_1.workspace.createFileSystemWatcher(globPattern, !watchCreate, !watchChange, !watchDelete); + this.hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, disposables); + disposables.push(fileSystemWatcher); + } + this._watchers.set(data.id, disposables); + } + registerRaw(id, fileSystemWatchers) { + let disposables = []; + for (let fileSystemWatcher of fileSystemWatchers) { + this.hookListeners(fileSystemWatcher, true, true, true, disposables); + } + this._watchers.set(id, disposables); + } + hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, listeners) { + if (watchCreate) { + fileSystemWatcher.onDidCreate((resource) => this._notifyFileEvent({ + uri: this._client.code2ProtocolConverter.asUri(resource), + type: vscode_languageserver_protocol_1.FileChangeType.Created + }), null, listeners); + } + if (watchChange) { + fileSystemWatcher.onDidChange((resource) => this._notifyFileEvent({ + uri: this._client.code2ProtocolConverter.asUri(resource), + type: vscode_languageserver_protocol_1.FileChangeType.Changed + }), null, listeners); + } + if (watchDelete) { + fileSystemWatcher.onDidDelete((resource) => this._notifyFileEvent({ + uri: this._client.code2ProtocolConverter.asUri(resource), + type: vscode_languageserver_protocol_1.FileChangeType.Deleted + }), null, listeners); + } + } + unregister(id) { + let disposables = this._watchers.get(id); + if (disposables) { + for (let disposable of disposables) { + disposable.dispose(); + } + } + } + clear() { + this._watchers.forEach((disposables) => { + for (let disposable of disposables) { + disposable.dispose(); + } + }); + this._watchers.clear(); + } + }; + exports2.FileSystemWatcherFeature = FileSystemWatcherFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/colorProvider.js +var require_colorProvider = __commonJS({ + "node_modules/vscode-languageclient/lib/common/colorProvider.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ColorProviderFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var ColorProviderFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.DocumentColorRequest.type); + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "colorProvider").dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + let [id, options] = this.getRegistration(documentSelector, capabilities.colorProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideColorPresentations: (color, context, token) => { + const client2 = this._client; + const provideColorPresentations = (color2, context2, token2) => { + const requestParams = { + color: color2, + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(context2.document), + range: client2.code2ProtocolConverter.asRange(context2.range) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, requestParams, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return this._client.protocol2CodeConverter.asColorPresentations(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideColorPresentations ? middleware.provideColorPresentations(color, context, token, provideColorPresentations) : provideColorPresentations(color, context, token); + }, + provideDocumentColors: (document, token) => { + const client2 = this._client; + const provideDocumentColors = (document2, token2) => { + const requestParams = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, requestParams, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return this._client.protocol2CodeConverter.asColorInformations(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideDocumentColors ? middleware.provideDocumentColors(document, token, provideDocumentColors) : provideDocumentColors(document, token); + } + }; + return [vscode_1.languages.registerColorProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider]; + } + }; + exports2.ColorProviderFeature = ColorProviderFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/implementation.js +var require_implementation = __commonJS({ + "node_modules/vscode-languageclient/lib/common/implementation.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ImplementationFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var ImplementationFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.ImplementationRequest.type); + } + fillClientCapabilities(capabilities) { + let implementationSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "implementation"); + implementationSupport.dynamicRegistration = true; + implementationSupport.linkSupport = true; + } + initialize(capabilities, documentSelector) { + let [id, options] = this.getRegistration(documentSelector, capabilities.implementationProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideImplementation: (document, position, token) => { + const client2 = this._client; + const provideImplementation = (document2, position2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, client2.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asDefinitionResult(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideImplementation ? middleware.provideImplementation(document, position, token, provideImplementation) : provideImplementation(document, position, token); + } + }; + return [this.registerProvider(selector, provider), provider]; + } + registerProvider(selector, provider) { + return vscode_1.languages.registerImplementationProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider); + } + }; + exports2.ImplementationFeature = ImplementationFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/typeDefinition.js +var require_typeDefinition = __commonJS({ + "node_modules/vscode-languageclient/lib/common/typeDefinition.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeDefinitionFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var TypeDefinitionFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.TypeDefinitionRequest.type); + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "typeDefinition").dynamicRegistration = true; + let typeDefinitionSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "typeDefinition"); + typeDefinitionSupport.dynamicRegistration = true; + typeDefinitionSupport.linkSupport = true; + } + initialize(capabilities, documentSelector) { + let [id, options] = this.getRegistration(documentSelector, capabilities.typeDefinitionProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideTypeDefinition: (document, position, token) => { + const client2 = this._client; + const provideTypeDefinition = (document2, position2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, client2.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asDefinitionResult(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideTypeDefinition ? middleware.provideTypeDefinition(document, position, token, provideTypeDefinition) : provideTypeDefinition(document, position, token); + } + }; + return [this.registerProvider(selector, provider), provider]; + } + registerProvider(selector, provider) { + return vscode_1.languages.registerTypeDefinitionProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider); + } + }; + exports2.TypeDefinitionFeature = TypeDefinitionFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/workspaceFolder.js +var require_workspaceFolder = __commonJS({ + "node_modules/vscode-languageclient/lib/common/workspaceFolder.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WorkspaceFoldersFeature = exports2.arrayDiff = void 0; + var UUID = require_uuid(); + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + function access(target, key) { + if (target === void 0 || target === null) { + return void 0; + } + return target[key]; + } + function arrayDiff(left, right) { + return left.filter((element) => right.indexOf(element) < 0); + } + exports2.arrayDiff = arrayDiff; + var WorkspaceFoldersFeature = class { + constructor(client2) { + this._client = client2; + this._listeners = /* @__PURE__ */ new Map(); + } + getState() { + return { kind: "workspace", id: this.registrationType.method, registrations: this._listeners.size > 0 }; + } + get registrationType() { + return vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type; + } + fillInitializeParams(params) { + const folders = vscode_1.workspace.workspaceFolders; + this.initializeWithFolders(folders); + if (folders === void 0) { + params.workspaceFolders = null; + } else { + params.workspaceFolders = folders.map((folder) => this.asProtocol(folder)); + } + } + initializeWithFolders(currentWorkspaceFolders) { + this._initialFolders = currentWorkspaceFolders; + } + fillClientCapabilities(capabilities) { + capabilities.workspace = capabilities.workspace || {}; + capabilities.workspace.workspaceFolders = true; + } + initialize(capabilities) { + const client2 = this._client; + client2.onRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type, (token) => { + const workspaceFolders = () => { + const folders = vscode_1.workspace.workspaceFolders; + if (folders === void 0) { + return null; + } + const result = folders.map((folder) => { + return this.asProtocol(folder); + }); + return result; + }; + const middleware = client2.middleware.workspace; + return middleware && middleware.workspaceFolders ? middleware.workspaceFolders(token, workspaceFolders) : workspaceFolders(token); + }); + const value = access(access(access(capabilities, "workspace"), "workspaceFolders"), "changeNotifications"); + let id; + if (typeof value === "string") { + id = value; + } else if (value === true) { + id = UUID.generateUuid(); + } + if (id) { + this.register({ id, registerOptions: void 0 }); + } + } + sendInitialEvent(currentWorkspaceFolders) { + let promise; + if (this._initialFolders && currentWorkspaceFolders) { + const removed = arrayDiff(this._initialFolders, currentWorkspaceFolders); + const added = arrayDiff(currentWorkspaceFolders, this._initialFolders); + if (added.length > 0 || removed.length > 0) { + promise = this.doSendEvent(added, removed); + } + } else if (this._initialFolders) { + promise = this.doSendEvent([], this._initialFolders); + } else if (currentWorkspaceFolders) { + promise = this.doSendEvent(currentWorkspaceFolders, []); + } + if (promise !== void 0) { + promise.catch((error) => { + this._client.error(`Sending notification ${vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type.method} failed`, error); + }); + } + } + doSendEvent(addedFolders, removedFolders) { + let params = { + event: { + added: addedFolders.map((folder) => this.asProtocol(folder)), + removed: removedFolders.map((folder) => this.asProtocol(folder)) + } + }; + return this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, params); + } + register(data) { + let id = data.id; + let client2 = this._client; + let disposable = vscode_1.workspace.onDidChangeWorkspaceFolders((event) => { + let didChangeWorkspaceFolders = (event2) => { + return this.doSendEvent(event2.added, event2.removed); + }; + let middleware = client2.middleware.workspace; + const promise = middleware && middleware.didChangeWorkspaceFolders ? middleware.didChangeWorkspaceFolders(event, didChangeWorkspaceFolders) : didChangeWorkspaceFolders(event); + promise.catch((error) => { + this._client.error(`Sending notification ${vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type.method} failed`, error); + }); + }); + this._listeners.set(id, disposable); + this.sendInitialEvent(vscode_1.workspace.workspaceFolders); + } + unregister(id) { + let disposable = this._listeners.get(id); + if (disposable === void 0) { + return; + } + this._listeners.delete(id); + disposable.dispose(); + } + clear() { + for (let disposable of this._listeners.values()) { + disposable.dispose(); + } + this._listeners.clear(); + } + asProtocol(workspaceFolder) { + if (workspaceFolder === void 0) { + return null; + } + return { uri: this._client.code2ProtocolConverter.asUri(workspaceFolder.uri), name: workspaceFolder.name }; + } + }; + exports2.WorkspaceFoldersFeature = WorkspaceFoldersFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/foldingRange.js +var require_foldingRange = __commonJS({ + "node_modules/vscode-languageclient/lib/common/foldingRange.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.FoldingRangeFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var FoldingRangeFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.FoldingRangeRequest.type); + } + fillClientCapabilities(capabilities) { + let capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "foldingRange"); + capability.dynamicRegistration = true; + capability.rangeLimit = 5e3; + capability.lineFoldingOnly = true; + capability.foldingRangeKind = { valueSet: [vscode_languageserver_protocol_1.FoldingRangeKind.Comment, vscode_languageserver_protocol_1.FoldingRangeKind.Imports, vscode_languageserver_protocol_1.FoldingRangeKind.Region] }; + capability.foldingRange = { collapsedText: false }; + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "foldingRange").refreshSupport = true; + } + initialize(capabilities, documentSelector) { + this._client.onRequest(vscode_languageserver_protocol_1.FoldingRangeRefreshRequest.type, async () => { + for (const provider of this.getAllProviders()) { + provider.onDidChangeFoldingRange.fire(); + } + }); + let [id, options] = this.getRegistration(documentSelector, capabilities.foldingRangeProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const eventEmitter = new vscode_1.EventEmitter(); + const provider = { + onDidChangeFoldingRanges: eventEmitter.event, + provideFoldingRanges: (document, context, token) => { + const client2 = this._client; + const provideFoldingRanges = (document2, _, token2) => { + const requestParams = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, requestParams, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asFoldingRanges(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideFoldingRanges ? middleware.provideFoldingRanges(document, context, token, provideFoldingRanges) : provideFoldingRanges(document, context, token); + } + }; + return [vscode_1.languages.registerFoldingRangeProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), { provider, onDidChangeFoldingRange: eventEmitter }]; + } + }; + exports2.FoldingRangeFeature = FoldingRangeFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/declaration.js +var require_declaration = __commonJS({ + "node_modules/vscode-languageclient/lib/common/declaration.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DeclarationFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var DeclarationFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.DeclarationRequest.type); + } + fillClientCapabilities(capabilities) { + const declarationSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "declaration"); + declarationSupport.dynamicRegistration = true; + declarationSupport.linkSupport = true; + } + initialize(capabilities, documentSelector) { + const [id, options] = this.getRegistration(documentSelector, capabilities.declarationProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideDeclaration: (document, position, token) => { + const client2 = this._client; + const provideDeclaration = (document2, position2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, client2.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asDeclarationResult(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideDeclaration ? middleware.provideDeclaration(document, position, token, provideDeclaration) : provideDeclaration(document, position, token); + } + }; + return [this.registerProvider(selector, provider), provider]; + } + registerProvider(selector, provider) { + return vscode_1.languages.registerDeclarationProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider); + } + }; + exports2.DeclarationFeature = DeclarationFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/selectionRange.js +var require_selectionRange = __commonJS({ + "node_modules/vscode-languageclient/lib/common/selectionRange.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SelectionRangeFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var SelectionRangeFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.SelectionRangeRequest.type); + } + fillClientCapabilities(capabilities) { + const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "selectionRange"); + capability.dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + const [id, options] = this.getRegistration(documentSelector, capabilities.selectionRangeProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideSelectionRanges: (document, positions, token) => { + const client2 = this._client; + const provideSelectionRanges = async (document2, positions2, token2) => { + const requestParams = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2), + positions: client2.code2ProtocolConverter.asPositionsSync(positions2, token2) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, requestParams, token2).then((ranges) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asSelectionRanges(ranges, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideSelectionRanges ? middleware.provideSelectionRanges(document, positions, token, provideSelectionRanges) : provideSelectionRanges(document, positions, token); + } + }; + return [this.registerProvider(selector, provider), provider]; + } + registerProvider(selector, provider) { + return vscode_1.languages.registerSelectionRangeProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider); + } + }; + exports2.SelectionRangeFeature = SelectionRangeFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/progress.js +var require_progress = __commonJS({ + "node_modules/vscode-languageclient/lib/common/progress.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ProgressFeature = void 0; + var vscode_languageserver_protocol_1 = require_main3(); + var progressPart_1 = require_progressPart(); + function ensure(target, key) { + if (target[key] === void 0) { + target[key] = /* @__PURE__ */ Object.create(null); + } + return target[key]; + } + var ProgressFeature = class { + constructor(_client) { + this._client = _client; + this.activeParts = /* @__PURE__ */ new Set(); + } + getState() { + return { kind: "window", id: vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.method, registrations: this.activeParts.size > 0 }; + } + fillClientCapabilities(capabilities) { + ensure(capabilities, "window").workDoneProgress = true; + } + initialize() { + const client2 = this._client; + const deleteHandler = (part) => { + this.activeParts.delete(part); + }; + const createHandler = (params) => { + this.activeParts.add(new progressPart_1.ProgressPart(this._client, params.token, deleteHandler)); + }; + client2.onRequest(vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.type, createHandler); + } + clear() { + for (const part of this.activeParts) { + part.done(); + } + this.activeParts.clear(); + } + }; + exports2.ProgressFeature = ProgressFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/callHierarchy.js +var require_callHierarchy = __commonJS({ + "node_modules/vscode-languageclient/lib/common/callHierarchy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CallHierarchyFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var CallHierarchyProvider = class { + constructor(client2) { + this.client = client2; + this.middleware = client2.middleware; + } + prepareCallHierarchy(document, position, token) { + const client2 = this.client; + const middleware = this.middleware; + const prepareCallHierarchy = (document2, position2, token2) => { + const params = client2.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2); + return client2.sendRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asCallHierarchyItems(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, token2, error, null); + }); + }; + return middleware.prepareCallHierarchy ? middleware.prepareCallHierarchy(document, position, token, prepareCallHierarchy) : prepareCallHierarchy(document, position, token); + } + provideCallHierarchyIncomingCalls(item, token) { + const client2 = this.client; + const middleware = this.middleware; + const provideCallHierarchyIncomingCalls = (item2, token2) => { + const params = { + item: client2.code2ProtocolConverter.asCallHierarchyItem(item2) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asCallHierarchyIncomingCalls(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type, token2, error, null); + }); + }; + return middleware.provideCallHierarchyIncomingCalls ? middleware.provideCallHierarchyIncomingCalls(item, token, provideCallHierarchyIncomingCalls) : provideCallHierarchyIncomingCalls(item, token); + } + provideCallHierarchyOutgoingCalls(item, token) { + const client2 = this.client; + const middleware = this.middleware; + const provideCallHierarchyOutgoingCalls = (item2, token2) => { + const params = { + item: client2.code2ProtocolConverter.asCallHierarchyItem(item2) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asCallHierarchyOutgoingCalls(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type, token2, error, null); + }); + }; + return middleware.provideCallHierarchyOutgoingCalls ? middleware.provideCallHierarchyOutgoingCalls(item, token, provideCallHierarchyOutgoingCalls) : provideCallHierarchyOutgoingCalls(item, token); + } + }; + var CallHierarchyFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type); + } + fillClientCapabilities(cap) { + const capabilities = cap; + const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "callHierarchy"); + capability.dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + const [id, options] = this.getRegistration(documentSelector, capabilities.callHierarchyProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const client2 = this._client; + const provider = new CallHierarchyProvider(client2); + return [vscode_1.languages.registerCallHierarchyProvider(this._client.protocol2CodeConverter.asDocumentSelector(options.documentSelector), provider), provider]; + } + }; + exports2.CallHierarchyFeature = CallHierarchyFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/semanticTokens.js +var require_semanticTokens = __commonJS({ + "node_modules/vscode-languageclient/lib/common/semanticTokens.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SemanticTokensFeature = void 0; + var vscode12 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var Is = require_is(); + var SemanticTokensFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.SemanticTokensRegistrationType.type); + } + fillClientCapabilities(capabilities) { + const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "semanticTokens"); + capability.dynamicRegistration = true; + capability.tokenTypes = [ + vscode_languageserver_protocol_1.SemanticTokenTypes.namespace, + vscode_languageserver_protocol_1.SemanticTokenTypes.type, + vscode_languageserver_protocol_1.SemanticTokenTypes.class, + vscode_languageserver_protocol_1.SemanticTokenTypes.enum, + vscode_languageserver_protocol_1.SemanticTokenTypes.interface, + vscode_languageserver_protocol_1.SemanticTokenTypes.struct, + vscode_languageserver_protocol_1.SemanticTokenTypes.typeParameter, + vscode_languageserver_protocol_1.SemanticTokenTypes.parameter, + vscode_languageserver_protocol_1.SemanticTokenTypes.variable, + vscode_languageserver_protocol_1.SemanticTokenTypes.property, + vscode_languageserver_protocol_1.SemanticTokenTypes.enumMember, + vscode_languageserver_protocol_1.SemanticTokenTypes.event, + vscode_languageserver_protocol_1.SemanticTokenTypes.function, + vscode_languageserver_protocol_1.SemanticTokenTypes.method, + vscode_languageserver_protocol_1.SemanticTokenTypes.macro, + vscode_languageserver_protocol_1.SemanticTokenTypes.keyword, + vscode_languageserver_protocol_1.SemanticTokenTypes.modifier, + vscode_languageserver_protocol_1.SemanticTokenTypes.comment, + vscode_languageserver_protocol_1.SemanticTokenTypes.string, + vscode_languageserver_protocol_1.SemanticTokenTypes.number, + vscode_languageserver_protocol_1.SemanticTokenTypes.regexp, + vscode_languageserver_protocol_1.SemanticTokenTypes.operator, + vscode_languageserver_protocol_1.SemanticTokenTypes.decorator + ]; + capability.tokenModifiers = [ + vscode_languageserver_protocol_1.SemanticTokenModifiers.declaration, + vscode_languageserver_protocol_1.SemanticTokenModifiers.definition, + vscode_languageserver_protocol_1.SemanticTokenModifiers.readonly, + vscode_languageserver_protocol_1.SemanticTokenModifiers.static, + vscode_languageserver_protocol_1.SemanticTokenModifiers.deprecated, + vscode_languageserver_protocol_1.SemanticTokenModifiers.abstract, + vscode_languageserver_protocol_1.SemanticTokenModifiers.async, + vscode_languageserver_protocol_1.SemanticTokenModifiers.modification, + vscode_languageserver_protocol_1.SemanticTokenModifiers.documentation, + vscode_languageserver_protocol_1.SemanticTokenModifiers.defaultLibrary + ]; + capability.formats = [vscode_languageserver_protocol_1.TokenFormat.Relative]; + capability.requests = { + range: true, + full: { + delta: true + } + }; + capability.multilineTokenSupport = false; + capability.overlappingTokenSupport = false; + capability.serverCancelSupport = true; + capability.augmentsSyntaxTokens = true; + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "semanticTokens").refreshSupport = true; + } + initialize(capabilities, documentSelector) { + const client2 = this._client; + client2.onRequest(vscode_languageserver_protocol_1.SemanticTokensRefreshRequest.type, async () => { + for (const provider of this.getAllProviders()) { + provider.onDidChangeSemanticTokensEmitter.fire(); + } + }); + const [id, options] = this.getRegistration(documentSelector, capabilities.semanticTokensProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const fullProvider = Is.boolean(options.full) ? options.full : options.full !== void 0; + const hasEditProvider = options.full !== void 0 && typeof options.full !== "boolean" && options.full.delta === true; + const eventEmitter = new vscode12.EventEmitter(); + const documentProvider = fullProvider ? { + onDidChangeSemanticTokens: eventEmitter.event, + provideDocumentSemanticTokens: (document, token) => { + const client3 = this._client; + const middleware = client3.middleware; + const provideDocumentSemanticTokens = (document2, token2) => { + const params = { + textDocument: client3.code2ProtocolConverter.asTextDocumentIdentifier(document2) + }; + return client3.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client3.protocol2CodeConverter.asSemanticTokens(result, token2); + }, (error) => { + return client3.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensRequest.type, token2, error, null); + }); + }; + return middleware.provideDocumentSemanticTokens ? middleware.provideDocumentSemanticTokens(document, token, provideDocumentSemanticTokens) : provideDocumentSemanticTokens(document, token); + }, + provideDocumentSemanticTokensEdits: hasEditProvider ? (document, previousResultId, token) => { + const client3 = this._client; + const middleware = client3.middleware; + const provideDocumentSemanticTokensEdits = (document2, previousResultId2, token2) => { + const params = { + textDocument: client3.code2ProtocolConverter.asTextDocumentIdentifier(document2), + previousResultId: previousResultId2 + }; + return client3.sendRequest(vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type, params, token2).then(async (result) => { + if (token2.isCancellationRequested) { + return null; + } + if (vscode_languageserver_protocol_1.SemanticTokens.is(result)) { + return await client3.protocol2CodeConverter.asSemanticTokens(result, token2); + } else { + return await client3.protocol2CodeConverter.asSemanticTokensEdits(result, token2); + } + }, (error) => { + return client3.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type, token2, error, null); + }); + }; + return middleware.provideDocumentSemanticTokensEdits ? middleware.provideDocumentSemanticTokensEdits(document, previousResultId, token, provideDocumentSemanticTokensEdits) : provideDocumentSemanticTokensEdits(document, previousResultId, token); + } : void 0 + } : void 0; + const hasRangeProvider = options.range === true; + const rangeProvider = hasRangeProvider ? { + provideDocumentRangeSemanticTokens: (document, range, token) => { + const client3 = this._client; + const middleware = client3.middleware; + const provideDocumentRangeSemanticTokens = (document2, range2, token2) => { + const params = { + textDocument: client3.code2ProtocolConverter.asTextDocumentIdentifier(document2), + range: client3.code2ProtocolConverter.asRange(range2) + }; + return client3.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client3.protocol2CodeConverter.asSemanticTokens(result, token2); + }, (error) => { + return client3.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type, token2, error, null); + }); + }; + return middleware.provideDocumentRangeSemanticTokens ? middleware.provideDocumentRangeSemanticTokens(document, range, token, provideDocumentRangeSemanticTokens) : provideDocumentRangeSemanticTokens(document, range, token); + } + } : void 0; + const disposables = []; + const client2 = this._client; + const legend = client2.protocol2CodeConverter.asSemanticTokensLegend(options.legend); + const documentSelector = client2.protocol2CodeConverter.asDocumentSelector(selector); + if (documentProvider !== void 0) { + disposables.push(vscode12.languages.registerDocumentSemanticTokensProvider(documentSelector, documentProvider, legend)); + } + if (rangeProvider !== void 0) { + disposables.push(vscode12.languages.registerDocumentRangeSemanticTokensProvider(documentSelector, rangeProvider, legend)); + } + return [new vscode12.Disposable(() => disposables.forEach((item) => item.dispose())), { range: rangeProvider, full: documentProvider, onDidChangeSemanticTokensEmitter: eventEmitter }]; + } + }; + exports2.SemanticTokensFeature = SemanticTokensFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/fileOperations.js +var require_fileOperations = __commonJS({ + "node_modules/vscode-languageclient/lib/common/fileOperations.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WillDeleteFilesFeature = exports2.WillRenameFilesFeature = exports2.WillCreateFilesFeature = exports2.DidDeleteFilesFeature = exports2.DidRenameFilesFeature = exports2.DidCreateFilesFeature = void 0; + var code = require("vscode"); + var minimatch = require_minimatch(); + var proto = require_main3(); + var UUID = require_uuid(); + function ensure(target, key) { + if (target[key] === void 0) { + target[key] = {}; + } + return target[key]; + } + function access(target, key) { + return target[key]; + } + function assign(target, key, value) { + target[key] = value; + } + var FileOperationFeature = class _FileOperationFeature { + constructor(client2, event, registrationType, clientCapability, serverCapability) { + this._client = client2; + this._event = event; + this._registrationType = registrationType; + this._clientCapability = clientCapability; + this._serverCapability = serverCapability; + this._filters = /* @__PURE__ */ new Map(); + } + getState() { + return { kind: "workspace", id: this._registrationType.method, registrations: this._filters.size > 0 }; + } + filterSize() { + return this._filters.size; + } + get registrationType() { + return this._registrationType; + } + fillClientCapabilities(capabilities) { + const value = ensure(ensure(capabilities, "workspace"), "fileOperations"); + assign(value, "dynamicRegistration", true); + assign(value, this._clientCapability, true); + } + initialize(capabilities) { + const options = capabilities.workspace?.fileOperations; + const capability = options !== void 0 ? access(options, this._serverCapability) : void 0; + if (capability?.filters !== void 0) { + try { + this.register({ + id: UUID.generateUuid(), + registerOptions: { filters: capability.filters } + }); + } catch (e) { + this._client.warn(`Ignoring invalid glob pattern for ${this._serverCapability} registration: ${e}`); + } + } + } + register(data) { + if (!this._listener) { + this._listener = this._event(this.send, this); + } + const minimatchFilter = data.registerOptions.filters.map((filter) => { + const matcher = new minimatch.Minimatch(filter.pattern.glob, _FileOperationFeature.asMinimatchOptions(filter.pattern.options)); + if (!matcher.makeRe()) { + throw new Error(`Invalid pattern ${filter.pattern.glob}!`); + } + return { scheme: filter.scheme, matcher, kind: filter.pattern.matches }; + }); + this._filters.set(data.id, minimatchFilter); + } + unregister(id) { + this._filters.delete(id); + if (this._filters.size === 0 && this._listener) { + this._listener.dispose(); + this._listener = void 0; + } + } + clear() { + this._filters.clear(); + if (this._listener) { + this._listener.dispose(); + this._listener = void 0; + } + } + getFileType(uri) { + return _FileOperationFeature.getFileType(uri); + } + async filter(event, prop) { + const fileMatches = await Promise.all(event.files.map(async (item) => { + const uri = prop(item); + const path8 = uri.fsPath.replace(/\\/g, "/"); + for (const filters of this._filters.values()) { + for (const filter of filters) { + if (filter.scheme !== void 0 && filter.scheme !== uri.scheme) { + continue; + } + if (filter.matcher.match(path8)) { + if (filter.kind === void 0) { + return true; + } + const fileType = await this.getFileType(uri); + if (fileType === void 0) { + this._client.error(`Failed to determine file type for ${uri.toString()}.`); + return true; + } + if (fileType === code.FileType.File && filter.kind === proto.FileOperationPatternKind.file || fileType === code.FileType.Directory && filter.kind === proto.FileOperationPatternKind.folder) { + return true; + } + } else if (filter.kind === proto.FileOperationPatternKind.folder) { + const fileType = await _FileOperationFeature.getFileType(uri); + if (fileType === code.FileType.Directory && filter.matcher.match(`${path8}/`)) { + return true; + } + } + } + } + return false; + })); + const files = event.files.filter((_, index) => fileMatches[index]); + return { ...event, files }; + } + static async getFileType(uri) { + try { + return (await code.workspace.fs.stat(uri)).type; + } catch (e) { + return void 0; + } + } + static asMinimatchOptions(options) { + const result = { dot: true }; + if (options?.ignoreCase === true) { + result.nocase = true; + } + return result; + } + }; + var NotificationFileOperationFeature = class extends FileOperationFeature { + constructor(client2, event, notificationType, clientCapability, serverCapability, accessUri, createParams) { + super(client2, event, notificationType, clientCapability, serverCapability); + this._notificationType = notificationType; + this._accessUri = accessUri; + this._createParams = createParams; + } + async send(originalEvent) { + const filteredEvent = await this.filter(originalEvent, this._accessUri); + if (filteredEvent.files.length) { + const next = async (event) => { + return this._client.sendNotification(this._notificationType, this._createParams(event)); + }; + return this.doSend(filteredEvent, next); + } + } + }; + var CachingNotificationFileOperationFeature = class extends NotificationFileOperationFeature { + constructor() { + super(...arguments); + this._fsPathFileTypes = /* @__PURE__ */ new Map(); + } + async getFileType(uri) { + const fsPath = uri.fsPath; + if (this._fsPathFileTypes.has(fsPath)) { + return this._fsPathFileTypes.get(fsPath); + } + const type = await FileOperationFeature.getFileType(uri); + if (type) { + this._fsPathFileTypes.set(fsPath, type); + } + return type; + } + async cacheFileTypes(event, prop) { + await this.filter(event, prop); + } + clearFileTypeCache() { + this._fsPathFileTypes.clear(); + } + unregister(id) { + super.unregister(id); + if (this.filterSize() === 0 && this._willListener) { + this._willListener.dispose(); + this._willListener = void 0; + } + } + clear() { + super.clear(); + if (this._willListener) { + this._willListener.dispose(); + this._willListener = void 0; + } + } + }; + var DidCreateFilesFeature = class extends NotificationFileOperationFeature { + constructor(client2) { + super(client2, code.workspace.onDidCreateFiles, proto.DidCreateFilesNotification.type, "didCreate", "didCreate", (i) => i, client2.code2ProtocolConverter.asDidCreateFilesParams); + } + doSend(event, next) { + const middleware = this._client.middleware.workspace; + return middleware?.didCreateFiles ? middleware.didCreateFiles(event, next) : next(event); + } + }; + exports2.DidCreateFilesFeature = DidCreateFilesFeature; + var DidRenameFilesFeature = class extends CachingNotificationFileOperationFeature { + constructor(client2) { + super(client2, code.workspace.onDidRenameFiles, proto.DidRenameFilesNotification.type, "didRename", "didRename", (i) => i.oldUri, client2.code2ProtocolConverter.asDidRenameFilesParams); + } + register(data) { + if (!this._willListener) { + this._willListener = code.workspace.onWillRenameFiles(this.willRename, this); + } + super.register(data); + } + willRename(e) { + e.waitUntil(this.cacheFileTypes(e, (i) => i.oldUri)); + } + doSend(event, next) { + this.clearFileTypeCache(); + const middleware = this._client.middleware.workspace; + return middleware?.didRenameFiles ? middleware.didRenameFiles(event, next) : next(event); + } + }; + exports2.DidRenameFilesFeature = DidRenameFilesFeature; + var DidDeleteFilesFeature = class extends CachingNotificationFileOperationFeature { + constructor(client2) { + super(client2, code.workspace.onDidDeleteFiles, proto.DidDeleteFilesNotification.type, "didDelete", "didDelete", (i) => i, client2.code2ProtocolConverter.asDidDeleteFilesParams); + } + register(data) { + if (!this._willListener) { + this._willListener = code.workspace.onWillDeleteFiles(this.willDelete, this); + } + super.register(data); + } + willDelete(e) { + e.waitUntil(this.cacheFileTypes(e, (i) => i)); + } + doSend(event, next) { + this.clearFileTypeCache(); + const middleware = this._client.middleware.workspace; + return middleware?.didDeleteFiles ? middleware.didDeleteFiles(event, next) : next(event); + } + }; + exports2.DidDeleteFilesFeature = DidDeleteFilesFeature; + var RequestFileOperationFeature = class extends FileOperationFeature { + constructor(client2, event, requestType, clientCapability, serverCapability, accessUri, createParams) { + super(client2, event, requestType, clientCapability, serverCapability); + this._requestType = requestType; + this._accessUri = accessUri; + this._createParams = createParams; + } + async send(originalEvent) { + const waitUntil = this.waitUntil(originalEvent); + originalEvent.waitUntil(waitUntil); + } + async waitUntil(originalEvent) { + const filteredEvent = await this.filter(originalEvent, this._accessUri); + if (filteredEvent.files.length) { + const next = (event) => { + return this._client.sendRequest(this._requestType, this._createParams(event), event.token).then(this._client.protocol2CodeConverter.asWorkspaceEdit); + }; + return this.doSend(filteredEvent, next); + } else { + return void 0; + } + } + }; + var WillCreateFilesFeature = class extends RequestFileOperationFeature { + constructor(client2) { + super(client2, code.workspace.onWillCreateFiles, proto.WillCreateFilesRequest.type, "willCreate", "willCreate", (i) => i, client2.code2ProtocolConverter.asWillCreateFilesParams); + } + doSend(event, next) { + const middleware = this._client.middleware.workspace; + return middleware?.willCreateFiles ? middleware.willCreateFiles(event, next) : next(event); + } + }; + exports2.WillCreateFilesFeature = WillCreateFilesFeature; + var WillRenameFilesFeature = class extends RequestFileOperationFeature { + constructor(client2) { + super(client2, code.workspace.onWillRenameFiles, proto.WillRenameFilesRequest.type, "willRename", "willRename", (i) => i.oldUri, client2.code2ProtocolConverter.asWillRenameFilesParams); + } + doSend(event, next) { + const middleware = this._client.middleware.workspace; + return middleware?.willRenameFiles ? middleware.willRenameFiles(event, next) : next(event); + } + }; + exports2.WillRenameFilesFeature = WillRenameFilesFeature; + var WillDeleteFilesFeature = class extends RequestFileOperationFeature { + constructor(client2) { + super(client2, code.workspace.onWillDeleteFiles, proto.WillDeleteFilesRequest.type, "willDelete", "willDelete", (i) => i, client2.code2ProtocolConverter.asWillDeleteFilesParams); + } + doSend(event, next) { + const middleware = this._client.middleware.workspace; + return middleware?.willDeleteFiles ? middleware.willDeleteFiles(event, next) : next(event); + } + }; + exports2.WillDeleteFilesFeature = WillDeleteFilesFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/linkedEditingRange.js +var require_linkedEditingRange = __commonJS({ + "node_modules/vscode-languageclient/lib/common/linkedEditingRange.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.LinkedEditingFeature = void 0; + var code = require("vscode"); + var proto = require_main3(); + var features_1 = require_features(); + var LinkedEditingFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, proto.LinkedEditingRangeRequest.type); + } + fillClientCapabilities(capabilities) { + const linkedEditingSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "linkedEditingRange"); + linkedEditingSupport.dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + let [id, options] = this.getRegistration(documentSelector, capabilities.linkedEditingRangeProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideLinkedEditingRanges: (document, position, token) => { + const client2 = this._client; + const provideLinkedEditing = (document2, position2, token2) => { + return client2.sendRequest(proto.LinkedEditingRangeRequest.type, client2.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asLinkedEditingRanges(result, token2); + }, (error) => { + return client2.handleFailedRequest(proto.LinkedEditingRangeRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideLinkedEditingRange ? middleware.provideLinkedEditingRange(document, position, token, provideLinkedEditing) : provideLinkedEditing(document, position, token); + } + }; + return [this.registerProvider(selector, provider), provider]; + } + registerProvider(selector, provider) { + return code.languages.registerLinkedEditingRangeProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider); + } + }; + exports2.LinkedEditingFeature = LinkedEditingFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/typeHierarchy.js +var require_typeHierarchy = __commonJS({ + "node_modules/vscode-languageclient/lib/common/typeHierarchy.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeHierarchyFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var TypeHierarchyProvider = class { + constructor(client2) { + this.client = client2; + this.middleware = client2.middleware; + } + prepareTypeHierarchy(document, position, token) { + const client2 = this.client; + const middleware = this.middleware; + const prepareTypeHierarchy = (document2, position2, token2) => { + const params = client2.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2); + return client2.sendRequest(vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asTypeHierarchyItems(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type, token2, error, null); + }); + }; + return middleware.prepareTypeHierarchy ? middleware.prepareTypeHierarchy(document, position, token, prepareTypeHierarchy) : prepareTypeHierarchy(document, position, token); + } + provideTypeHierarchySupertypes(item, token) { + const client2 = this.client; + const middleware = this.middleware; + const provideTypeHierarchySupertypes = (item2, token2) => { + const params = { + item: client2.code2ProtocolConverter.asTypeHierarchyItem(item2) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.TypeHierarchySupertypesRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asTypeHierarchyItems(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.TypeHierarchySupertypesRequest.type, token2, error, null); + }); + }; + return middleware.provideTypeHierarchySupertypes ? middleware.provideTypeHierarchySupertypes(item, token, provideTypeHierarchySupertypes) : provideTypeHierarchySupertypes(item, token); + } + provideTypeHierarchySubtypes(item, token) { + const client2 = this.client; + const middleware = this.middleware; + const provideTypeHierarchySubtypes = (item2, token2) => { + const params = { + item: client2.code2ProtocolConverter.asTypeHierarchyItem(item2) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.TypeHierarchySubtypesRequest.type, params, token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asTypeHierarchyItems(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.TypeHierarchySubtypesRequest.type, token2, error, null); + }); + }; + return middleware.provideTypeHierarchySubtypes ? middleware.provideTypeHierarchySubtypes(item, token, provideTypeHierarchySubtypes) : provideTypeHierarchySubtypes(item, token); + } + }; + var TypeHierarchyFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type); + } + fillClientCapabilities(capabilities) { + const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "typeHierarchy"); + capability.dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + const [id, options] = this.getRegistration(documentSelector, capabilities.typeHierarchyProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const client2 = this._client; + const provider = new TypeHierarchyProvider(client2); + return [vscode_1.languages.registerTypeHierarchyProvider(client2.protocol2CodeConverter.asDocumentSelector(options.documentSelector), provider), provider]; + } + }; + exports2.TypeHierarchyFeature = TypeHierarchyFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/inlineValue.js +var require_inlineValue = __commonJS({ + "node_modules/vscode-languageclient/lib/common/inlineValue.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.InlineValueFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var InlineValueFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.InlineValueRequest.type); + } + fillClientCapabilities(capabilities) { + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "inlineValue").dynamicRegistration = true; + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "inlineValue").refreshSupport = true; + } + initialize(capabilities, documentSelector) { + this._client.onRequest(vscode_languageserver_protocol_1.InlineValueRefreshRequest.type, async () => { + for (const provider of this.getAllProviders()) { + provider.onDidChangeInlineValues.fire(); + } + }); + const [id, options] = this.getRegistration(documentSelector, capabilities.inlineValueProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const eventEmitter = new vscode_1.EventEmitter(); + const provider = { + onDidChangeInlineValues: eventEmitter.event, + provideInlineValues: (document, viewPort, context, token) => { + const client2 = this._client; + const provideInlineValues = (document2, viewPort2, context2, token2) => { + const requestParams = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2), + range: client2.code2ProtocolConverter.asRange(viewPort2), + context: client2.code2ProtocolConverter.asInlineValueContext(context2) + }; + return client2.sendRequest(vscode_languageserver_protocol_1.InlineValueRequest.type, requestParams, token2).then((values) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asInlineValues(values, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.InlineValueRequest.type, token2, error, null); + }); + }; + const middleware = client2.middleware; + return middleware.provideInlineValues ? middleware.provideInlineValues(document, viewPort, context, token, provideInlineValues) : provideInlineValues(document, viewPort, context, token); + } + }; + return [this.registerProvider(selector, provider), { provider, onDidChangeInlineValues: eventEmitter }]; + } + registerProvider(selector, provider) { + return vscode_1.languages.registerInlineValuesProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider); + } + }; + exports2.InlineValueFeature = InlineValueFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/inlayHint.js +var require_inlayHint = __commonJS({ + "node_modules/vscode-languageclient/lib/common/inlayHint.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.InlayHintsFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var InlayHintsFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.InlayHintRequest.type); + } + fillClientCapabilities(capabilities) { + const inlayHint = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "inlayHint"); + inlayHint.dynamicRegistration = true; + inlayHint.resolveSupport = { + properties: ["tooltip", "textEdits", "label.tooltip", "label.location", "label.command"] + }; + (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "inlayHint").refreshSupport = true; + } + initialize(capabilities, documentSelector) { + this._client.onRequest(vscode_languageserver_protocol_1.InlayHintRefreshRequest.type, async () => { + for (const provider of this.getAllProviders()) { + provider.onDidChangeInlayHints.fire(); + } + }); + const [id, options] = this.getRegistration(documentSelector, capabilities.inlayHintProvider); + if (!id || !options) { + return; + } + this.register({ id, registerOptions: options }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const eventEmitter = new vscode_1.EventEmitter(); + const provider = { + onDidChangeInlayHints: eventEmitter.event, + provideInlayHints: (document, viewPort, token) => { + const client2 = this._client; + const provideInlayHints = async (document2, viewPort2, token2) => { + const requestParams = { + textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2), + range: client2.code2ProtocolConverter.asRange(viewPort2) + }; + try { + const values = await client2.sendRequest(vscode_languageserver_protocol_1.InlayHintRequest.type, requestParams, token2); + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asInlayHints(values, token2); + } catch (error) { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.InlayHintRequest.type, token2, error, null); + } + }; + const middleware = client2.middleware; + return middleware.provideInlayHints ? middleware.provideInlayHints(document, viewPort, token, provideInlayHints) : provideInlayHints(document, viewPort, token); + } + }; + provider.resolveInlayHint = options.resolveProvider === true ? (hint, token) => { + const client2 = this._client; + const resolveInlayHint = async (item, token2) => { + try { + const value = await client2.sendRequest(vscode_languageserver_protocol_1.InlayHintResolveRequest.type, client2.code2ProtocolConverter.asInlayHint(item), token2); + if (token2.isCancellationRequested) { + return null; + } + const result = client2.protocol2CodeConverter.asInlayHint(value, token2); + return token2.isCancellationRequested ? null : result; + } catch (error) { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.InlayHintResolveRequest.type, token2, error, null); + } + }; + const middleware = client2.middleware; + return middleware.resolveInlayHint ? middleware.resolveInlayHint(hint, token, resolveInlayHint) : resolveInlayHint(hint, token); + } : void 0; + return [this.registerProvider(selector, provider), { provider, onDidChangeInlayHints: eventEmitter }]; + } + registerProvider(selector, provider) { + return vscode_1.languages.registerInlayHintsProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider); + } + }; + exports2.InlayHintsFeature = InlayHintsFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/inlineCompletion.js +var require_inlineCompletion = __commonJS({ + "node_modules/vscode-languageclient/lib/common/inlineCompletion.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.InlineCompletionItemFeature = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var features_1 = require_features(); + var UUID = require_uuid(); + var InlineCompletionItemFeature = class extends features_1.TextDocumentLanguageFeature { + constructor(client2) { + super(client2, vscode_languageserver_protocol_1.InlineCompletionRequest.type); + } + fillClientCapabilities(capabilities) { + let inlineCompletion = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "inlineCompletion"); + inlineCompletion.dynamicRegistration = true; + } + initialize(capabilities, documentSelector) { + const options = this.getRegistrationOptions(documentSelector, capabilities.inlineCompletionProvider); + if (!options) { + return; + } + this.register({ + id: UUID.generateUuid(), + registerOptions: options + }); + } + registerLanguageProvider(options) { + const selector = options.documentSelector; + const provider = { + provideInlineCompletionItems: (document, position, context, token) => { + const client2 = this._client; + const middleware = this._client.middleware; + const provideInlineCompletionItems = (document2, position2, context2, token2) => { + return client2.sendRequest(vscode_languageserver_protocol_1.InlineCompletionRequest.type, client2.code2ProtocolConverter.asInlineCompletionParams(document2, position2, context2), token2).then((result) => { + if (token2.isCancellationRequested) { + return null; + } + return client2.protocol2CodeConverter.asInlineCompletionResult(result, token2); + }, (error) => { + return client2.handleFailedRequest(vscode_languageserver_protocol_1.InlineCompletionRequest.type, token2, error, null); + }); + }; + return middleware.provideInlineCompletionItems ? middleware.provideInlineCompletionItems(document, position, context, token, provideInlineCompletionItems) : provideInlineCompletionItems(document, position, context, token); + } + }; + return [vscode_1.languages.registerInlineCompletionItemProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider]; + } + }; + exports2.InlineCompletionItemFeature = InlineCompletionItemFeature; + } +}); + +// node_modules/vscode-languageclient/lib/common/client.js +var require_client = __commonJS({ + "node_modules/vscode-languageclient/lib/common/client.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ProposedFeatures = exports2.BaseLanguageClient = exports2.MessageTransports = exports2.SuspendMode = exports2.State = exports2.CloseAction = exports2.ErrorAction = exports2.RevealOutputChannelOn = void 0; + var vscode_1 = require("vscode"); + var vscode_languageserver_protocol_1 = require_main3(); + var c2p = require_codeConverter(); + var p2c = require_protocolConverter(); + var Is = require_is(); + var async_1 = require_async(); + var UUID = require_uuid(); + var progressPart_1 = require_progressPart(); + var features_1 = require_features(); + var diagnostic_1 = require_diagnostic(); + var notebook_1 = require_notebook(); + var configuration_1 = require_configuration(); + var textSynchronization_1 = require_textSynchronization(); + var completion_1 = require_completion(); + var hover_1 = require_hover(); + var definition_1 = require_definition(); + var signatureHelp_1 = require_signatureHelp(); + var documentHighlight_1 = require_documentHighlight(); + var documentSymbol_1 = require_documentSymbol(); + var workspaceSymbol_1 = require_workspaceSymbol(); + var reference_1 = require_reference(); + var codeAction_1 = require_codeAction(); + var codeLens_1 = require_codeLens(); + var formatting_1 = require_formatting(); + var rename_1 = require_rename(); + var documentLink_1 = require_documentLink(); + var executeCommand_1 = require_executeCommand(); + var fileSystemWatcher_1 = require_fileSystemWatcher(); + var colorProvider_1 = require_colorProvider(); + var implementation_1 = require_implementation(); + var typeDefinition_1 = require_typeDefinition(); + var workspaceFolder_1 = require_workspaceFolder(); + var foldingRange_1 = require_foldingRange(); + var declaration_1 = require_declaration(); + var selectionRange_1 = require_selectionRange(); + var progress_1 = require_progress(); + var callHierarchy_1 = require_callHierarchy(); + var semanticTokens_1 = require_semanticTokens(); + var fileOperations_1 = require_fileOperations(); + var linkedEditingRange_1 = require_linkedEditingRange(); + var typeHierarchy_1 = require_typeHierarchy(); + var inlineValue_1 = require_inlineValue(); + var inlayHint_1 = require_inlayHint(); + var inlineCompletion_1 = require_inlineCompletion(); + var RevealOutputChannelOn; + (function(RevealOutputChannelOn2) { + RevealOutputChannelOn2[RevealOutputChannelOn2["Debug"] = 0] = "Debug"; + RevealOutputChannelOn2[RevealOutputChannelOn2["Info"] = 1] = "Info"; + RevealOutputChannelOn2[RevealOutputChannelOn2["Warn"] = 2] = "Warn"; + RevealOutputChannelOn2[RevealOutputChannelOn2["Error"] = 3] = "Error"; + RevealOutputChannelOn2[RevealOutputChannelOn2["Never"] = 4] = "Never"; + })(RevealOutputChannelOn || (exports2.RevealOutputChannelOn = RevealOutputChannelOn = {})); + var ErrorAction; + (function(ErrorAction2) { + ErrorAction2[ErrorAction2["Continue"] = 1] = "Continue"; + ErrorAction2[ErrorAction2["Shutdown"] = 2] = "Shutdown"; + })(ErrorAction || (exports2.ErrorAction = ErrorAction = {})); + var CloseAction; + (function(CloseAction2) { + CloseAction2[CloseAction2["DoNotRestart"] = 1] = "DoNotRestart"; + CloseAction2[CloseAction2["Restart"] = 2] = "Restart"; + })(CloseAction || (exports2.CloseAction = CloseAction = {})); + var State; + (function(State2) { + State2[State2["Stopped"] = 1] = "Stopped"; + State2[State2["Starting"] = 3] = "Starting"; + State2[State2["Running"] = 2] = "Running"; + })(State || (exports2.State = State = {})); + var SuspendMode; + (function(SuspendMode2) { + SuspendMode2["off"] = "off"; + SuspendMode2["on"] = "on"; + })(SuspendMode || (exports2.SuspendMode = SuspendMode = {})); + var ResolvedClientOptions; + (function(ResolvedClientOptions2) { + function sanitizeIsTrusted(isTrusted) { + if (isTrusted === void 0 || isTrusted === null) { + return false; + } + if (typeof isTrusted === "boolean" || typeof isTrusted === "object" && isTrusted !== null && Is.stringArray(isTrusted.enabledCommands)) { + return isTrusted; + } + return false; + } + ResolvedClientOptions2.sanitizeIsTrusted = sanitizeIsTrusted; + })(ResolvedClientOptions || (ResolvedClientOptions = {})); + var DefaultErrorHandler = class { + constructor(client2, maxRestartCount) { + this.client = client2; + this.maxRestartCount = maxRestartCount; + this.restarts = []; + } + error(_error, _message, count) { + if (count && count <= 3) { + return { action: ErrorAction.Continue }; + } + return { action: ErrorAction.Shutdown }; + } + closed() { + this.restarts.push(Date.now()); + if (this.restarts.length <= this.maxRestartCount) { + return { action: CloseAction.Restart }; + } else { + let diff = this.restarts[this.restarts.length - 1] - this.restarts[0]; + if (diff <= 3 * 60 * 1e3) { + return { action: CloseAction.DoNotRestart, message: `The ${this.client.name} server crashed ${this.maxRestartCount + 1} times in the last 3 minutes. The server will not be restarted. See the output for more information.` }; + } else { + this.restarts.shift(); + return { action: CloseAction.Restart }; + } + } + } + }; + var ClientState; + (function(ClientState2) { + ClientState2["Initial"] = "initial"; + ClientState2["Starting"] = "starting"; + ClientState2["StartFailed"] = "startFailed"; + ClientState2["Running"] = "running"; + ClientState2["Stopping"] = "stopping"; + ClientState2["Stopped"] = "stopped"; + })(ClientState || (ClientState = {})); + var MessageTransports; + (function(MessageTransports2) { + function is(value) { + let candidate = value; + return candidate && vscode_languageserver_protocol_1.MessageReader.is(value.reader) && vscode_languageserver_protocol_1.MessageWriter.is(value.writer); + } + MessageTransports2.is = is; + })(MessageTransports || (exports2.MessageTransports = MessageTransports = {})); + var BaseLanguageClient = class _BaseLanguageClient { + constructor(id, name, clientOptions) { + this._traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text; + this._diagnosticQueue = /* @__PURE__ */ new Map(); + this._diagnosticQueueState = { state: "idle" }; + this._features = []; + this._dynamicFeatures = /* @__PURE__ */ new Map(); + this.workspaceEditLock = new async_1.Semaphore(1); + this._id = id; + this._name = name; + clientOptions = clientOptions || {}; + const markdown = { isTrusted: false, supportHtml: false }; + if (clientOptions.markdown !== void 0) { + markdown.isTrusted = ResolvedClientOptions.sanitizeIsTrusted(clientOptions.markdown.isTrusted); + markdown.supportHtml = clientOptions.markdown.supportHtml === true; + } + this._clientOptions = { + documentSelector: clientOptions.documentSelector ?? [], + synchronize: clientOptions.synchronize ?? {}, + diagnosticCollectionName: clientOptions.diagnosticCollectionName, + outputChannelName: clientOptions.outputChannelName ?? this._name, + revealOutputChannelOn: clientOptions.revealOutputChannelOn ?? RevealOutputChannelOn.Error, + stdioEncoding: clientOptions.stdioEncoding ?? "utf8", + initializationOptions: clientOptions.initializationOptions, + initializationFailedHandler: clientOptions.initializationFailedHandler, + progressOnInitialization: !!clientOptions.progressOnInitialization, + errorHandler: clientOptions.errorHandler ?? this.createDefaultErrorHandler(clientOptions.connectionOptions?.maxRestartCount), + middleware: clientOptions.middleware ?? {}, + uriConverters: clientOptions.uriConverters, + workspaceFolder: clientOptions.workspaceFolder, + connectionOptions: clientOptions.connectionOptions, + markdown, + // suspend: { + // mode: clientOptions.suspend?.mode ?? SuspendMode.off, + // callback: clientOptions.suspend?.callback ?? (() => Promise.resolve(true)), + // interval: clientOptions.suspend?.interval ? Math.max(clientOptions.suspend.interval, defaultInterval) : defaultInterval + // }, + diagnosticPullOptions: clientOptions.diagnosticPullOptions ?? { onChange: true, onSave: false }, + notebookDocumentOptions: clientOptions.notebookDocumentOptions ?? {} + }; + this._clientOptions.synchronize = this._clientOptions.synchronize || {}; + this._state = ClientState.Initial; + this._ignoredRegistrations = /* @__PURE__ */ new Set(); + this._listeners = []; + this._notificationHandlers = /* @__PURE__ */ new Map(); + this._pendingNotificationHandlers = /* @__PURE__ */ new Map(); + this._notificationDisposables = /* @__PURE__ */ new Map(); + this._requestHandlers = /* @__PURE__ */ new Map(); + this._pendingRequestHandlers = /* @__PURE__ */ new Map(); + this._requestDisposables = /* @__PURE__ */ new Map(); + this._progressHandlers = /* @__PURE__ */ new Map(); + this._pendingProgressHandlers = /* @__PURE__ */ new Map(); + this._progressDisposables = /* @__PURE__ */ new Map(); + this._connection = void 0; + this._initializeResult = void 0; + if (clientOptions.outputChannel) { + this._outputChannel = clientOptions.outputChannel; + this._disposeOutputChannel = false; + } else { + this._outputChannel = void 0; + this._disposeOutputChannel = true; + } + this._traceOutputChannel = clientOptions.traceOutputChannel; + this._diagnostics = void 0; + this._pendingOpenNotifications = /* @__PURE__ */ new Set(); + this._pendingChangeSemaphore = new async_1.Semaphore(1); + this._pendingChangeDelayer = new async_1.Delayer(250); + this._fileEvents = []; + this._fileEventDelayer = new async_1.Delayer(250); + this._onStop = void 0; + this._telemetryEmitter = new vscode_languageserver_protocol_1.Emitter(); + this._stateChangeEmitter = new vscode_languageserver_protocol_1.Emitter(); + this._trace = vscode_languageserver_protocol_1.Trace.Off; + this._tracer = { + log: (messageOrDataObject, data) => { + if (Is.string(messageOrDataObject)) { + this.logTrace(messageOrDataObject, data); + } else { + this.logObjectTrace(messageOrDataObject); + } + } + }; + this._c2p = c2p.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.code2Protocol : void 0); + this._p2c = p2c.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.protocol2Code : void 0, this._clientOptions.markdown.isTrusted, this._clientOptions.markdown.supportHtml); + this._syncedDocuments = /* @__PURE__ */ new Map(); + this.registerBuiltinFeatures(); + } + get name() { + return this._name; + } + get middleware() { + return this._clientOptions.middleware ?? /* @__PURE__ */ Object.create(null); + } + get clientOptions() { + return this._clientOptions; + } + get protocol2CodeConverter() { + return this._p2c; + } + get code2ProtocolConverter() { + return this._c2p; + } + get onTelemetry() { + return this._telemetryEmitter.event; + } + get onDidChangeState() { + return this._stateChangeEmitter.event; + } + get outputChannel() { + if (!this._outputChannel) { + this._outputChannel = vscode_1.window.createOutputChannel(this._clientOptions.outputChannelName ? this._clientOptions.outputChannelName : this._name); + } + return this._outputChannel; + } + get traceOutputChannel() { + if (this._traceOutputChannel) { + return this._traceOutputChannel; + } + return this.outputChannel; + } + get diagnostics() { + return this._diagnostics; + } + get state() { + return this.getPublicState(); + } + get $state() { + return this._state; + } + set $state(value) { + let oldState = this.getPublicState(); + this._state = value; + let newState = this.getPublicState(); + if (newState !== oldState) { + this._stateChangeEmitter.fire({ oldState, newState }); + } + } + getPublicState() { + switch (this.$state) { + case ClientState.Starting: + return State.Starting; + case ClientState.Running: + return State.Running; + default: + return State.Stopped; + } + } + get initializeResult() { + return this._initializeResult; + } + async sendRequest(type, ...params) { + if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) { + return Promise.reject(new vscode_languageserver_protocol_1.ResponseError(vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive, `Client is not running`)); + } + const connection = await this.$start(); + if (this._didChangeTextDocumentFeature.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) { + await this.sendPendingFullTextDocumentChanges(connection); + } + const _sendRequest = this._clientOptions.middleware?.sendRequest; + if (_sendRequest !== void 0) { + let param = void 0; + let token = void 0; + if (params.length === 1) { + if (vscode_languageserver_protocol_1.CancellationToken.is(params[0])) { + token = params[0]; + } else { + param = params[0]; + } + } else if (params.length === 2) { + param = params[0]; + token = params[1]; + } + return _sendRequest(type, param, token, (type2, param2, token2) => { + const params2 = []; + if (param2 !== void 0) { + params2.push(param2); + } + if (token2 !== void 0) { + params2.push(token2); + } + return connection.sendRequest(type2, ...params2); + }); + } else { + return connection.sendRequest(type, ...params); + } + } + onRequest(type, handler) { + const method = typeof type === "string" ? type : type.method; + this._requestHandlers.set(method, handler); + const connection = this.activeConnection(); + let disposable; + if (connection !== void 0) { + this._requestDisposables.set(method, connection.onRequest(type, handler)); + disposable = { + dispose: () => { + const disposable2 = this._requestDisposables.get(method); + if (disposable2 !== void 0) { + disposable2.dispose(); + this._requestDisposables.delete(method); + } + } + }; + } else { + this._pendingRequestHandlers.set(method, handler); + disposable = { + dispose: () => { + this._pendingRequestHandlers.delete(method); + const disposable2 = this._requestDisposables.get(method); + if (disposable2 !== void 0) { + disposable2.dispose(); + this._requestDisposables.delete(method); + } + } + }; + } + return { + dispose: () => { + this._requestHandlers.delete(method); + disposable.dispose(); + } + }; + } + async sendNotification(type, params) { + if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) { + return Promise.reject(new vscode_languageserver_protocol_1.ResponseError(vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive, `Client is not running`)); + } + const needsPendingFullTextDocumentSync = this._didChangeTextDocumentFeature.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full; + let openNotification; + if (needsPendingFullTextDocumentSync && typeof type !== "string" && type.method === vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.method) { + openNotification = params?.textDocument.uri; + this._pendingOpenNotifications.add(openNotification); + } + const connection = await this.$start(); + if (needsPendingFullTextDocumentSync) { + await this.sendPendingFullTextDocumentChanges(connection); + } + if (openNotification !== void 0) { + this._pendingOpenNotifications.delete(openNotification); + } + const _sendNotification = this._clientOptions.middleware?.sendNotification; + return _sendNotification ? _sendNotification(type, connection.sendNotification.bind(connection), params) : connection.sendNotification(type, params); + } + onNotification(type, handler) { + const method = typeof type === "string" ? type : type.method; + this._notificationHandlers.set(method, handler); + const connection = this.activeConnection(); + let disposable; + if (connection !== void 0) { + this._notificationDisposables.set(method, connection.onNotification(type, handler)); + disposable = { + dispose: () => { + const disposable2 = this._notificationDisposables.get(method); + if (disposable2 !== void 0) { + disposable2.dispose(); + this._notificationDisposables.delete(method); + } + } + }; + } else { + this._pendingNotificationHandlers.set(method, handler); + disposable = { + dispose: () => { + this._pendingNotificationHandlers.delete(method); + const disposable2 = this._notificationDisposables.get(method); + if (disposable2 !== void 0) { + disposable2.dispose(); + this._notificationDisposables.delete(method); + } + } + }; + } + return { + dispose: () => { + this._notificationHandlers.delete(method); + disposable.dispose(); + } + }; + } + async sendProgress(type, token, value) { + if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) { + return Promise.reject(new vscode_languageserver_protocol_1.ResponseError(vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive, `Client is not running`)); + } + try { + const connection = await this.$start(); + return connection.sendProgress(type, token, value); + } catch (error) { + this.error(`Sending progress for token ${token} failed.`, error); + throw error; + } + } + onProgress(type, token, handler) { + this._progressHandlers.set(token, { type, handler }); + const connection = this.activeConnection(); + let disposable; + const handleWorkDoneProgress = this._clientOptions.middleware?.handleWorkDoneProgress; + const realHandler = vscode_languageserver_protocol_1.WorkDoneProgress.is(type) && handleWorkDoneProgress !== void 0 ? (params) => { + handleWorkDoneProgress(token, params, () => handler(params)); + } : handler; + if (connection !== void 0) { + this._progressDisposables.set(token, connection.onProgress(type, token, realHandler)); + disposable = { + dispose: () => { + const disposable2 = this._progressDisposables.get(token); + if (disposable2 !== void 0) { + disposable2.dispose(); + this._progressDisposables.delete(token); + } + } + }; + } else { + this._pendingProgressHandlers.set(token, { type, handler }); + disposable = { + dispose: () => { + this._pendingProgressHandlers.delete(token); + const disposable2 = this._progressDisposables.get(token); + if (disposable2 !== void 0) { + disposable2.dispose(); + this._progressDisposables.delete(token); + } + } + }; + } + return { + dispose: () => { + this._progressHandlers.delete(token); + disposable.dispose(); + } + }; + } + createDefaultErrorHandler(maxRestartCount) { + if (maxRestartCount !== void 0 && maxRestartCount < 0) { + throw new Error(`Invalid maxRestartCount: ${maxRestartCount}`); + } + return new DefaultErrorHandler(this, maxRestartCount ?? 4); + } + async setTrace(value) { + this._trace = value; + const connection = this.activeConnection(); + if (connection !== void 0) { + await connection.trace(this._trace, this._tracer, { + sendNotification: false, + traceFormat: this._traceFormat + }); + } + } + data2String(data) { + if (data instanceof vscode_languageserver_protocol_1.ResponseError) { + const responseError = data; + return ` Message: ${responseError.message} + Code: ${responseError.code} ${responseError.data ? "\n" + responseError.data.toString() : ""}`; + } + if (data instanceof Error) { + if (Is.string(data.stack)) { + return data.stack; + } + return data.message; + } + if (Is.string(data)) { + return data; + } + return data.toString(); + } + debug(message, data, showNotification = true) { + this.logOutputMessage(vscode_languageserver_protocol_1.MessageType.Debug, RevealOutputChannelOn.Debug, "Debug", message, data, showNotification); + } + info(message, data, showNotification = true) { + this.logOutputMessage(vscode_languageserver_protocol_1.MessageType.Info, RevealOutputChannelOn.Info, "Info", message, data, showNotification); + } + warn(message, data, showNotification = true) { + this.logOutputMessage(vscode_languageserver_protocol_1.MessageType.Warning, RevealOutputChannelOn.Warn, "Warn", message, data, showNotification); + } + error(message, data, showNotification = true) { + this.logOutputMessage(vscode_languageserver_protocol_1.MessageType.Error, RevealOutputChannelOn.Error, "Error", message, data, showNotification); + } + logOutputMessage(type, reveal, name, message, data, showNotification) { + this.outputChannel.appendLine(`[${name.padEnd(5)} - ${(/* @__PURE__ */ new Date()).toLocaleTimeString()}] ${message}`); + if (data !== null && data !== void 0) { + this.outputChannel.appendLine(this.data2String(data)); + } + if (showNotification === "force" || showNotification && this._clientOptions.revealOutputChannelOn <= reveal) { + this.showNotificationMessage(type, message); + } + } + showNotificationMessage(type, message) { + message = message ?? "A request has failed. See the output for more information."; + const messageFunc = type === vscode_languageserver_protocol_1.MessageType.Error ? vscode_1.window.showErrorMessage : type === vscode_languageserver_protocol_1.MessageType.Warning ? vscode_1.window.showWarningMessage : vscode_1.window.showInformationMessage; + void messageFunc(message, "Go to output").then((selection) => { + if (selection !== void 0) { + this.outputChannel.show(true); + } + }); + } + logTrace(message, data) { + this.traceOutputChannel.appendLine(`[Trace - ${(/* @__PURE__ */ new Date()).toLocaleTimeString()}] ${message}`); + if (data) { + this.traceOutputChannel.appendLine(this.data2String(data)); + } + } + logObjectTrace(data) { + if (data.isLSPMessage && data.type) { + this.traceOutputChannel.append(`[LSP - ${(/* @__PURE__ */ new Date()).toLocaleTimeString()}] `); + } else { + this.traceOutputChannel.append(`[Trace - ${(/* @__PURE__ */ new Date()).toLocaleTimeString()}] `); + } + if (data) { + this.traceOutputChannel.appendLine(`${JSON.stringify(data)}`); + } + } + needsStart() { + return this.$state === ClientState.Initial || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped; + } + needsStop() { + return this.$state === ClientState.Starting || this.$state === ClientState.Running; + } + activeConnection() { + return this.$state === ClientState.Running && this._connection !== void 0 ? this._connection : void 0; + } + isRunning() { + return this.$state === ClientState.Running; + } + async start() { + if (this._disposed === "disposing" || this._disposed === "disposed") { + throw new Error(`Client got disposed and can't be restarted.`); + } + if (this.$state === ClientState.Stopping) { + throw new Error(`Client is currently stopping. Can only restart a full stopped client`); + } + if (this._onStart !== void 0) { + return this._onStart; + } + const [promise, resolve, reject] = this.createOnStartPromise(); + this._onStart = promise; + if (this._diagnostics === void 0) { + this._diagnostics = this._clientOptions.diagnosticCollectionName ? vscode_1.languages.createDiagnosticCollection(this._clientOptions.diagnosticCollectionName) : vscode_1.languages.createDiagnosticCollection(); + } + for (const [method, handler] of this._notificationHandlers) { + if (!this._pendingNotificationHandlers.has(method)) { + this._pendingNotificationHandlers.set(method, handler); + } + } + for (const [method, handler] of this._requestHandlers) { + if (!this._pendingRequestHandlers.has(method)) { + this._pendingRequestHandlers.set(method, handler); + } + } + for (const [token, data] of this._progressHandlers) { + if (!this._pendingProgressHandlers.has(token)) { + this._pendingProgressHandlers.set(token, data); + } + } + this.$state = ClientState.Starting; + try { + const connection = await this.createConnection(); + connection.onNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, (message) => { + switch (message.type) { + case vscode_languageserver_protocol_1.MessageType.Error: + this.error(message.message, void 0, false); + break; + case vscode_languageserver_protocol_1.MessageType.Warning: + this.warn(message.message, void 0, false); + break; + case vscode_languageserver_protocol_1.MessageType.Info: + this.info(message.message, void 0, false); + break; + case vscode_languageserver_protocol_1.MessageType.Debug: + this.debug(message.message, void 0, false); + break; + default: + this.outputChannel.appendLine(message.message); + } + }); + connection.onNotification(vscode_languageserver_protocol_1.ShowMessageNotification.type, (message) => { + switch (message.type) { + case vscode_languageserver_protocol_1.MessageType.Error: + void vscode_1.window.showErrorMessage(message.message); + break; + case vscode_languageserver_protocol_1.MessageType.Warning: + void vscode_1.window.showWarningMessage(message.message); + break; + case vscode_languageserver_protocol_1.MessageType.Info: + void vscode_1.window.showInformationMessage(message.message); + break; + default: + void vscode_1.window.showInformationMessage(message.message); + } + }); + connection.onRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, (params) => { + let messageFunc; + switch (params.type) { + case vscode_languageserver_protocol_1.MessageType.Error: + messageFunc = vscode_1.window.showErrorMessage; + break; + case vscode_languageserver_protocol_1.MessageType.Warning: + messageFunc = vscode_1.window.showWarningMessage; + break; + case vscode_languageserver_protocol_1.MessageType.Info: + messageFunc = vscode_1.window.showInformationMessage; + break; + default: + messageFunc = vscode_1.window.showInformationMessage; + } + let actions = params.actions || []; + return messageFunc(params.message, ...actions); + }); + connection.onNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, (data) => { + this._telemetryEmitter.fire(data); + }); + connection.onRequest(vscode_languageserver_protocol_1.ShowDocumentRequest.type, async (params) => { + const showDocument = async (params2) => { + const uri = this.protocol2CodeConverter.asUri(params2.uri); + try { + if (params2.external === true) { + const success = await vscode_1.env.openExternal(uri); + return { success }; + } else { + const options = {}; + if (params2.selection !== void 0) { + options.selection = this.protocol2CodeConverter.asRange(params2.selection); + } + if (params2.takeFocus === void 0 || params2.takeFocus === false) { + options.preserveFocus = true; + } else if (params2.takeFocus === true) { + options.preserveFocus = false; + } + await vscode_1.window.showTextDocument(uri, options); + return { success: true }; + } + } catch (error) { + return { success: false }; + } + }; + const middleware = this._clientOptions.middleware.window?.showDocument; + if (middleware !== void 0) { + return middleware(params, showDocument); + } else { + return showDocument(params); + } + }); + connection.listen(); + await this.initialize(connection); + resolve(); + } catch (error) { + this.$state = ClientState.StartFailed; + this.error(`${this._name} client: couldn't create connection to server.`, error, "force"); + reject(error); + } + return this._onStart; + } + createOnStartPromise() { + let resolve; + let reject; + const promise = new Promise((_resolve, _reject) => { + resolve = _resolve; + reject = _reject; + }); + return [promise, resolve, reject]; + } + async initialize(connection) { + this.refreshTrace(connection, false); + const initOption = this._clientOptions.initializationOptions; + const [rootPath, workspaceFolders] = this._clientOptions.workspaceFolder !== void 0 ? [this._clientOptions.workspaceFolder.uri.fsPath, [{ uri: this._c2p.asUri(this._clientOptions.workspaceFolder.uri), name: this._clientOptions.workspaceFolder.name }]] : [this._clientGetRootPath(), null]; + const initParams = { + processId: null, + clientInfo: { + name: vscode_1.env.appName, + version: vscode_1.version + }, + locale: this.getLocale(), + rootPath: rootPath ? rootPath : null, + rootUri: rootPath ? this._c2p.asUri(vscode_1.Uri.file(rootPath)) : null, + capabilities: this.computeClientCapabilities(), + initializationOptions: Is.func(initOption) ? initOption() : initOption, + trace: vscode_languageserver_protocol_1.Trace.toString(this._trace), + workspaceFolders + }; + this.fillInitializeParams(initParams); + if (this._clientOptions.progressOnInitialization) { + const token = UUID.generateUuid(); + const part = new progressPart_1.ProgressPart(connection, token); + initParams.workDoneToken = token; + try { + const result = await this.doInitialize(connection, initParams); + part.done(); + return result; + } catch (error) { + part.cancel(); + throw error; + } + } else { + return this.doInitialize(connection, initParams); + } + } + async doInitialize(connection, initParams) { + try { + const result = await connection.initialize(initParams); + if (result.capabilities.positionEncoding !== void 0 && result.capabilities.positionEncoding !== vscode_languageserver_protocol_1.PositionEncodingKind.UTF16) { + throw new Error(`Unsupported position encoding (${result.capabilities.positionEncoding}) received from server ${this.name}`); + } + this._initializeResult = result; + this.$state = ClientState.Running; + let textDocumentSyncOptions = void 0; + if (Is.number(result.capabilities.textDocumentSync)) { + if (result.capabilities.textDocumentSync === vscode_languageserver_protocol_1.TextDocumentSyncKind.None) { + textDocumentSyncOptions = { + openClose: false, + change: vscode_languageserver_protocol_1.TextDocumentSyncKind.None, + save: void 0 + }; + } else { + textDocumentSyncOptions = { + openClose: true, + change: result.capabilities.textDocumentSync, + save: { + includeText: false + } + }; + } + } else if (result.capabilities.textDocumentSync !== void 0 && result.capabilities.textDocumentSync !== null) { + textDocumentSyncOptions = result.capabilities.textDocumentSync; + } + this._capabilities = Object.assign({}, result.capabilities, { resolvedTextDocumentSync: textDocumentSyncOptions }); + connection.onNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, (params) => this.handleDiagnostics(params)); + connection.onRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, (params) => this.handleRegistrationRequest(params)); + connection.onRequest("client/registerFeature", (params) => this.handleRegistrationRequest(params)); + connection.onRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, (params) => this.handleUnregistrationRequest(params)); + connection.onRequest("client/unregisterFeature", (params) => this.handleUnregistrationRequest(params)); + connection.onRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, (params) => this.handleApplyWorkspaceEdit(params)); + for (const [method, handler] of this._pendingNotificationHandlers) { + this._notificationDisposables.set(method, connection.onNotification(method, handler)); + } + this._pendingNotificationHandlers.clear(); + for (const [method, handler] of this._pendingRequestHandlers) { + this._requestDisposables.set(method, connection.onRequest(method, handler)); + } + this._pendingRequestHandlers.clear(); + for (const [token, data] of this._pendingProgressHandlers) { + this._progressDisposables.set(token, connection.onProgress(data.type, token, data.handler)); + } + this._pendingProgressHandlers.clear(); + await connection.sendNotification(vscode_languageserver_protocol_1.InitializedNotification.type, {}); + this.hookFileEvents(connection); + this.hookConfigurationChanged(connection); + this.initializeFeatures(connection); + return result; + } catch (error) { + if (this._clientOptions.initializationFailedHandler) { + if (this._clientOptions.initializationFailedHandler(error)) { + void this.initialize(connection); + } else { + void this.stop(); + } + } else if (error instanceof vscode_languageserver_protocol_1.ResponseError && error.data && error.data.retry) { + void vscode_1.window.showErrorMessage(error.message, { title: "Retry", id: "retry" }).then((item) => { + if (item && item.id === "retry") { + void this.initialize(connection); + } else { + void this.stop(); + } + }); + } else { + if (error && error.message) { + void vscode_1.window.showErrorMessage(error.message); + } + this.error("Server initialization failed.", error); + void this.stop(); + } + throw error; + } + } + _clientGetRootPath() { + let folders = vscode_1.workspace.workspaceFolders; + if (!folders || folders.length === 0) { + return void 0; + } + let folder = folders[0]; + if (folder.uri.scheme === "file") { + return folder.uri.fsPath; + } + return void 0; + } + stop(timeout = 2e3) { + return this.shutdown("stop", timeout); + } + dispose(timeout = 2e3) { + try { + this._disposed = "disposing"; + return this.stop(timeout); + } finally { + this._disposed = "disposed"; + } + } + async shutdown(mode, timeout) { + if (this.$state === ClientState.Stopped || this.$state === ClientState.Initial) { + return; + } + if (this.$state === ClientState.Stopping) { + if (this._onStop !== void 0) { + return this._onStop; + } else { + throw new Error(`Client is stopping but no stop promise available.`); + } + } + const connection = this.activeConnection(); + if (connection === void 0 || this.$state !== ClientState.Running) { + throw new Error(`Client is not running and can't be stopped. It's current state is: ${this.$state}`); + } + this._initializeResult = void 0; + this.$state = ClientState.Stopping; + this.cleanUp(mode); + const tp = new Promise((c) => { + (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(c, timeout); + }); + const shutdown = (async (connection2) => { + await connection2.shutdown(); + await connection2.exit(); + return connection2; + })(connection); + return this._onStop = Promise.race([tp, shutdown]).then((connection2) => { + if (connection2 !== void 0) { + connection2.end(); + connection2.dispose(); + } else { + this.error(`Stopping server timed out`, void 0, false); + throw new Error(`Stopping the server timed out`); + } + }, (error) => { + this.error(`Stopping server failed`, error, false); + throw error; + }).finally(() => { + this.$state = ClientState.Stopped; + mode === "stop" && this.cleanUpChannel(); + this._onStart = void 0; + this._onStop = void 0; + this._connection = void 0; + this._ignoredRegistrations.clear(); + }); + } + cleanUp(mode) { + this._fileEvents = []; + this._fileEventDelayer.cancel(); + const disposables = this._listeners.splice(0, this._listeners.length); + for (const disposable of disposables) { + disposable.dispose(); + } + if (this._syncedDocuments) { + this._syncedDocuments.clear(); + } + for (const feature of Array.from(this._features.entries()).map((entry) => entry[1]).reverse()) { + feature.clear(); + } + if (mode === "stop" && this._diagnostics !== void 0) { + this._diagnostics.dispose(); + this._diagnostics = void 0; + } + if (this._idleInterval !== void 0) { + this._idleInterval.dispose(); + this._idleInterval = void 0; + } + } + cleanUpChannel() { + if (this._outputChannel !== void 0 && this._disposeOutputChannel) { + this._outputChannel.dispose(); + this._outputChannel = void 0; + } + } + notifyFileEvent(event) { + const client2 = this; + async function didChangeWatchedFile(event2) { + client2._fileEvents.push(event2); + return client2._fileEventDelayer.trigger(async () => { + await client2.sendNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, { changes: client2._fileEvents }); + client2._fileEvents = []; + }); + } + const workSpaceMiddleware = this.clientOptions.middleware?.workspace; + (workSpaceMiddleware?.didChangeWatchedFile ? workSpaceMiddleware.didChangeWatchedFile(event, didChangeWatchedFile) : didChangeWatchedFile(event)).catch((error) => { + client2.error(`Notify file events failed.`, error); + }); + } + async sendPendingFullTextDocumentChanges(connection) { + return this._pendingChangeSemaphore.lock(async () => { + try { + const changes = this._didChangeTextDocumentFeature.getPendingDocumentChanges(this._pendingOpenNotifications); + if (changes.length === 0) { + return; + } + for (const document of changes) { + const params = this.code2ProtocolConverter.asChangeTextDocumentParams(document); + await connection.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params); + this._didChangeTextDocumentFeature.notificationSent(document, vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params); + } + } catch (error) { + this.error(`Sending pending changes failed`, error, false); + throw error; + } + }); + } + triggerPendingChangeDelivery() { + this._pendingChangeDelayer.trigger(async () => { + const connection = this.activeConnection(); + if (connection === void 0) { + this.triggerPendingChangeDelivery(); + return; + } + await this.sendPendingFullTextDocumentChanges(connection); + }).catch((error) => this.error(`Delivering pending changes failed`, error, false)); + } + handleDiagnostics(params) { + if (!this._diagnostics) { + return; + } + const key = params.uri; + if (this._diagnosticQueueState.state === "busy" && this._diagnosticQueueState.document === key) { + this._diagnosticQueueState.tokenSource.cancel(); + } + this._diagnosticQueue.set(params.uri, params.diagnostics); + this.triggerDiagnosticQueue(); + } + triggerDiagnosticQueue() { + (0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => { + this.workDiagnosticQueue(); + }); + } + workDiagnosticQueue() { + if (this._diagnosticQueueState.state === "busy") { + return; + } + const next = this._diagnosticQueue.entries().next(); + if (next.done === true) { + return; + } + const [document, diagnostics] = next.value; + this._diagnosticQueue.delete(document); + const tokenSource = new vscode_1.CancellationTokenSource(); + this._diagnosticQueueState = { state: "busy", document, tokenSource }; + this._p2c.asDiagnostics(diagnostics, tokenSource.token).then((converted) => { + if (!tokenSource.token.isCancellationRequested) { + const uri = this._p2c.asUri(document); + const middleware = this.clientOptions.middleware; + if (middleware.handleDiagnostics) { + middleware.handleDiagnostics(uri, converted, (uri2, diagnostics2) => this.setDiagnostics(uri2, diagnostics2)); + } else { + this.setDiagnostics(uri, converted); + } + } + }).finally(() => { + this._diagnosticQueueState = { state: "idle" }; + this.triggerDiagnosticQueue(); + }); + } + setDiagnostics(uri, diagnostics) { + if (!this._diagnostics) { + return; + } + this._diagnostics.set(uri, diagnostics); + } + getLocale() { + return vscode_1.env.language; + } + async $start() { + if (this.$state === ClientState.StartFailed) { + throw new Error(`Previous start failed. Can't restart server.`); + } + await this.start(); + const connection = this.activeConnection(); + if (connection === void 0) { + throw new Error(`Starting server failed`); + } + return connection; + } + async createConnection() { + let errorHandler = (error, message, count) => { + this.handleConnectionError(error, message, count).catch((error2) => this.error(`Handling connection error failed`, error2)); + }; + let closeHandler = () => { + this.handleConnectionClosed().catch((error) => this.error(`Handling connection close failed`, error)); + }; + const transports = await this.createMessageTransports(this._clientOptions.stdioEncoding || "utf8"); + this._connection = createConnection(transports.reader, transports.writer, errorHandler, closeHandler, this._clientOptions.connectionOptions); + return this._connection; + } + async handleConnectionClosed() { + if (this.$state === ClientState.Stopped) { + return; + } + try { + if (this._connection !== void 0) { + this._connection.dispose(); + } + } catch (error) { + } + let handlerResult = { action: CloseAction.DoNotRestart }; + if (this.$state !== ClientState.Stopping) { + try { + handlerResult = await this._clientOptions.errorHandler.closed(); + } catch (error) { + } + } + this._connection = void 0; + if (handlerResult.action === CloseAction.DoNotRestart) { + this.error(handlerResult.message ?? "Connection to server got closed. Server will not be restarted.", void 0, handlerResult.handled === true ? false : "force"); + this.cleanUp("stop"); + if (this.$state === ClientState.Starting) { + this.$state = ClientState.StartFailed; + } else { + this.$state = ClientState.Stopped; + } + this._onStop = Promise.resolve(); + this._onStart = void 0; + } else if (handlerResult.action === CloseAction.Restart) { + this.info(handlerResult.message ?? "Connection to server got closed. Server will restart.", !handlerResult.handled); + this.cleanUp("restart"); + this.$state = ClientState.Initial; + this._onStop = Promise.resolve(); + this._onStart = void 0; + this.start().catch((error) => this.error(`Restarting server failed`, error, "force")); + } + } + async handleConnectionError(error, message, count) { + const handlerResult = await this._clientOptions.errorHandler.error(error, message, count); + if (handlerResult.action === ErrorAction.Shutdown) { + this.error(handlerResult.message ?? `Client ${this._name}: connection to server is erroring. +${error.message} +Shutting down server.`, void 0, handlerResult.handled === true ? false : "force"); + this.stop().catch((error2) => { + this.error(`Stopping server failed`, error2, false); + }); + } else { + this.error(handlerResult.message ?? `Client ${this._name}: connection to server is erroring. +${error.message}`, void 0, handlerResult.handled === true ? false : "force"); + } + } + hookConfigurationChanged(connection) { + this._listeners.push(vscode_1.workspace.onDidChangeConfiguration(() => { + this.refreshTrace(connection, true); + })); + } + refreshTrace(connection, sendNotification = false) { + const config = vscode_1.workspace.getConfiguration(this._id); + let trace = vscode_languageserver_protocol_1.Trace.Off; + let traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text; + if (config) { + const traceConfig = config.get("trace.server", "off"); + if (typeof traceConfig === "string") { + trace = vscode_languageserver_protocol_1.Trace.fromString(traceConfig); + } else { + trace = vscode_languageserver_protocol_1.Trace.fromString(config.get("trace.server.verbosity", "off")); + traceFormat = vscode_languageserver_protocol_1.TraceFormat.fromString(config.get("trace.server.format", "text")); + } + } + this._trace = trace; + this._traceFormat = traceFormat; + connection.trace(this._trace, this._tracer, { + sendNotification, + traceFormat: this._traceFormat + }).catch((error) => { + this.error(`Updating trace failed with error`, error, false); + }); + } + hookFileEvents(_connection) { + let fileEvents = this._clientOptions.synchronize.fileEvents; + if (!fileEvents) { + return; + } + let watchers; + if (Is.array(fileEvents)) { + watchers = fileEvents; + } else { + watchers = [fileEvents]; + } + if (!watchers) { + return; + } + this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type.method).registerRaw(UUID.generateUuid(), watchers); + } + registerFeatures(features) { + for (let feature of features) { + this.registerFeature(feature); + } + } + registerFeature(feature) { + this._features.push(feature); + if (features_1.DynamicFeature.is(feature)) { + const registrationType = feature.registrationType; + this._dynamicFeatures.set(registrationType.method, feature); + } + } + getFeature(request) { + return this._dynamicFeatures.get(request); + } + hasDedicatedTextSynchronizationFeature(textDocument) { + const feature = this.getFeature(vscode_languageserver_protocol_1.NotebookDocumentSyncRegistrationType.method); + if (feature === void 0 || !(feature instanceof notebook_1.NotebookDocumentSyncFeature)) { + return false; + } + return feature.handles(textDocument); + } + registerBuiltinFeatures() { + const pendingFullTextDocumentChanges = /* @__PURE__ */ new Map(); + this.registerFeature(new configuration_1.ConfigurationFeature(this)); + this.registerFeature(new textSynchronization_1.DidOpenTextDocumentFeature(this, this._syncedDocuments)); + this._didChangeTextDocumentFeature = new textSynchronization_1.DidChangeTextDocumentFeature(this, pendingFullTextDocumentChanges); + this._didChangeTextDocumentFeature.onPendingChangeAdded(() => { + this.triggerPendingChangeDelivery(); + }); + this.registerFeature(this._didChangeTextDocumentFeature); + this.registerFeature(new textSynchronization_1.WillSaveFeature(this)); + this.registerFeature(new textSynchronization_1.WillSaveWaitUntilFeature(this)); + this.registerFeature(new textSynchronization_1.DidSaveTextDocumentFeature(this)); + this.registerFeature(new textSynchronization_1.DidCloseTextDocumentFeature(this, this._syncedDocuments, pendingFullTextDocumentChanges)); + this.registerFeature(new fileSystemWatcher_1.FileSystemWatcherFeature(this, (event) => this.notifyFileEvent(event))); + this.registerFeature(new completion_1.CompletionItemFeature(this)); + this.registerFeature(new hover_1.HoverFeature(this)); + this.registerFeature(new signatureHelp_1.SignatureHelpFeature(this)); + this.registerFeature(new definition_1.DefinitionFeature(this)); + this.registerFeature(new reference_1.ReferencesFeature(this)); + this.registerFeature(new documentHighlight_1.DocumentHighlightFeature(this)); + this.registerFeature(new documentSymbol_1.DocumentSymbolFeature(this)); + this.registerFeature(new workspaceSymbol_1.WorkspaceSymbolFeature(this)); + this.registerFeature(new codeAction_1.CodeActionFeature(this)); + this.registerFeature(new codeLens_1.CodeLensFeature(this)); + this.registerFeature(new formatting_1.DocumentFormattingFeature(this)); + this.registerFeature(new formatting_1.DocumentRangeFormattingFeature(this)); + this.registerFeature(new formatting_1.DocumentOnTypeFormattingFeature(this)); + this.registerFeature(new rename_1.RenameFeature(this)); + this.registerFeature(new documentLink_1.DocumentLinkFeature(this)); + this.registerFeature(new executeCommand_1.ExecuteCommandFeature(this)); + this.registerFeature(new configuration_1.SyncConfigurationFeature(this)); + this.registerFeature(new typeDefinition_1.TypeDefinitionFeature(this)); + this.registerFeature(new implementation_1.ImplementationFeature(this)); + this.registerFeature(new colorProvider_1.ColorProviderFeature(this)); + if (this.clientOptions.workspaceFolder === void 0) { + this.registerFeature(new workspaceFolder_1.WorkspaceFoldersFeature(this)); + } + this.registerFeature(new foldingRange_1.FoldingRangeFeature(this)); + this.registerFeature(new declaration_1.DeclarationFeature(this)); + this.registerFeature(new selectionRange_1.SelectionRangeFeature(this)); + this.registerFeature(new progress_1.ProgressFeature(this)); + this.registerFeature(new callHierarchy_1.CallHierarchyFeature(this)); + this.registerFeature(new semanticTokens_1.SemanticTokensFeature(this)); + this.registerFeature(new linkedEditingRange_1.LinkedEditingFeature(this)); + this.registerFeature(new fileOperations_1.DidCreateFilesFeature(this)); + this.registerFeature(new fileOperations_1.DidRenameFilesFeature(this)); + this.registerFeature(new fileOperations_1.DidDeleteFilesFeature(this)); + this.registerFeature(new fileOperations_1.WillCreateFilesFeature(this)); + this.registerFeature(new fileOperations_1.WillRenameFilesFeature(this)); + this.registerFeature(new fileOperations_1.WillDeleteFilesFeature(this)); + this.registerFeature(new typeHierarchy_1.TypeHierarchyFeature(this)); + this.registerFeature(new inlineValue_1.InlineValueFeature(this)); + this.registerFeature(new inlayHint_1.InlayHintsFeature(this)); + this.registerFeature(new diagnostic_1.DiagnosticFeature(this)); + this.registerFeature(new notebook_1.NotebookDocumentSyncFeature(this)); + } + registerProposedFeatures() { + this.registerFeatures(ProposedFeatures.createAll(this)); + } + fillInitializeParams(params) { + for (let feature of this._features) { + if (Is.func(feature.fillInitializeParams)) { + feature.fillInitializeParams(params); + } + } + } + computeClientCapabilities() { + const result = {}; + (0, features_1.ensure)(result, "workspace").applyEdit = true; + const workspaceEdit = (0, features_1.ensure)((0, features_1.ensure)(result, "workspace"), "workspaceEdit"); + workspaceEdit.documentChanges = true; + workspaceEdit.resourceOperations = [vscode_languageserver_protocol_1.ResourceOperationKind.Create, vscode_languageserver_protocol_1.ResourceOperationKind.Rename, vscode_languageserver_protocol_1.ResourceOperationKind.Delete]; + workspaceEdit.failureHandling = vscode_languageserver_protocol_1.FailureHandlingKind.TextOnlyTransactional; + workspaceEdit.normalizesLineEndings = true; + workspaceEdit.changeAnnotationSupport = { + groupsOnLabel: true + }; + const diagnostics = (0, features_1.ensure)((0, features_1.ensure)(result, "textDocument"), "publishDiagnostics"); + diagnostics.relatedInformation = true; + diagnostics.versionSupport = false; + diagnostics.tagSupport = { valueSet: [vscode_languageserver_protocol_1.DiagnosticTag.Unnecessary, vscode_languageserver_protocol_1.DiagnosticTag.Deprecated] }; + diagnostics.codeDescriptionSupport = true; + diagnostics.dataSupport = true; + const windowCapabilities = (0, features_1.ensure)(result, "window"); + const showMessage = (0, features_1.ensure)(windowCapabilities, "showMessage"); + showMessage.messageActionItem = { additionalPropertiesSupport: true }; + const showDocument = (0, features_1.ensure)(windowCapabilities, "showDocument"); + showDocument.support = true; + const generalCapabilities = (0, features_1.ensure)(result, "general"); + generalCapabilities.staleRequestSupport = { + cancel: true, + retryOnContentModified: Array.from(_BaseLanguageClient.RequestsToCancelOnContentModified) + }; + generalCapabilities.regularExpressions = { engine: "ECMAScript", version: "ES2020" }; + generalCapabilities.markdown = { + parser: "marked", + version: "1.1.0" + }; + generalCapabilities.positionEncodings = ["utf-16"]; + if (this._clientOptions.markdown.supportHtml) { + generalCapabilities.markdown.allowedTags = ["ul", "li", "p", "code", "blockquote", "ol", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "em", "pre", "table", "thead", "tbody", "tr", "th", "td", "div", "del", "a", "strong", "br", "img", "span"]; + } + for (let feature of this._features) { + feature.fillClientCapabilities(result); + } + return result; + } + initializeFeatures(_connection) { + const documentSelector = this._clientOptions.documentSelector; + for (const feature of this._features) { + if (Is.func(feature.preInitialize)) { + feature.preInitialize(this._capabilities, documentSelector); + } + } + for (const feature of this._features) { + feature.initialize(this._capabilities, documentSelector); + } + } + async handleRegistrationRequest(params) { + const middleware = this.clientOptions.middleware?.handleRegisterCapability; + if (middleware) { + return middleware(params, (nextParams) => this.doRegisterCapability(nextParams)); + } else { + return this.doRegisterCapability(params); + } + } + async doRegisterCapability(params) { + if (!this.isRunning()) { + for (const registration of params.registrations) { + this._ignoredRegistrations.add(registration.id); + } + return; + } + for (const registration of params.registrations) { + const feature = this._dynamicFeatures.get(registration.method); + if (feature === void 0) { + return Promise.reject(new Error(`No feature implementation for ${registration.method} found. Registration failed.`)); + } + const options = registration.registerOptions ?? {}; + options.documentSelector = options.documentSelector ?? this._clientOptions.documentSelector; + const data = { + id: registration.id, + registerOptions: options + }; + try { + feature.register(data); + } catch (err) { + return Promise.reject(err); + } + } + } + async handleUnregistrationRequest(params) { + const middleware = this.clientOptions.middleware?.handleUnregisterCapability; + if (middleware) { + return middleware(params, (nextParams) => this.doUnregisterCapability(nextParams)); + } else { + return this.doUnregisterCapability(params); + } + } + async doUnregisterCapability(params) { + for (const unregistration of params.unregisterations) { + if (this._ignoredRegistrations.has(unregistration.id)) { + continue; + } + const feature = this._dynamicFeatures.get(unregistration.method); + if (!feature) { + return Promise.reject(new Error(`No feature implementation for ${unregistration.method} found. Unregistration failed.`)); + } + feature.unregister(unregistration.id); + } + } + async handleApplyWorkspaceEdit(params) { + const workspaceEdit = params.edit; + const converted = await this.workspaceEditLock.lock(() => { + return this._p2c.asWorkspaceEdit(workspaceEdit); + }); + const openTextDocuments = /* @__PURE__ */ new Map(); + vscode_1.workspace.textDocuments.forEach((document) => openTextDocuments.set(document.uri.toString(), document)); + let versionMismatch = false; + if (workspaceEdit.documentChanges) { + for (const change of workspaceEdit.documentChanges) { + if (vscode_languageserver_protocol_1.TextDocumentEdit.is(change) && change.textDocument.version && change.textDocument.version >= 0) { + const changeUri = this._p2c.asUri(change.textDocument.uri).toString(); + const textDocument = openTextDocuments.get(changeUri); + if (textDocument && textDocument.version !== change.textDocument.version) { + versionMismatch = true; + break; + } + } + } + } + if (versionMismatch) { + return Promise.resolve({ applied: false }); + } + return Is.asPromise(vscode_1.workspace.applyEdit(converted).then((value) => { + return { applied: value }; + })); + } + handleFailedRequest(type, token, error, defaultValue, showNotification = true) { + if (error instanceof vscode_languageserver_protocol_1.ResponseError) { + if (error.code === vscode_languageserver_protocol_1.ErrorCodes.PendingResponseRejected || error.code === vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive) { + return defaultValue; + } + if (error.code === vscode_languageserver_protocol_1.LSPErrorCodes.RequestCancelled || error.code === vscode_languageserver_protocol_1.LSPErrorCodes.ServerCancelled) { + if (token !== void 0 && token.isCancellationRequested) { + return defaultValue; + } else { + if (error.data !== void 0) { + throw new features_1.LSPCancellationError(error.data); + } else { + throw new vscode_1.CancellationError(); + } + } + } else if (error.code === vscode_languageserver_protocol_1.LSPErrorCodes.ContentModified) { + if (_BaseLanguageClient.RequestsToCancelOnContentModified.has(type.method) || _BaseLanguageClient.CancellableResolveCalls.has(type.method)) { + throw new vscode_1.CancellationError(); + } else { + return defaultValue; + } + } + } + this.error(`Request ${type.method} failed.`, error, showNotification); + throw error; + } + }; + exports2.BaseLanguageClient = BaseLanguageClient; + BaseLanguageClient.RequestsToCancelOnContentModified = /* @__PURE__ */ new Set([ + vscode_languageserver_protocol_1.SemanticTokensRequest.method, + vscode_languageserver_protocol_1.SemanticTokensRangeRequest.method, + vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.method + ]); + BaseLanguageClient.CancellableResolveCalls = /* @__PURE__ */ new Set([ + vscode_languageserver_protocol_1.CompletionResolveRequest.method, + vscode_languageserver_protocol_1.CodeLensResolveRequest.method, + vscode_languageserver_protocol_1.CodeActionResolveRequest.method, + vscode_languageserver_protocol_1.InlayHintResolveRequest.method, + vscode_languageserver_protocol_1.DocumentLinkResolveRequest.method, + vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.method + ]); + var ConsoleLogger = class { + error(message) { + (0, vscode_languageserver_protocol_1.RAL)().console.error(message); + } + warn(message) { + (0, vscode_languageserver_protocol_1.RAL)().console.warn(message); + } + info(message) { + (0, vscode_languageserver_protocol_1.RAL)().console.info(message); + } + log(message) { + (0, vscode_languageserver_protocol_1.RAL)().console.log(message); + } + }; + function createConnection(input, output, errorHandler, closeHandler, options) { + const logger = new ConsoleLogger(); + const connection = (0, vscode_languageserver_protocol_1.createProtocolConnection)(input, output, logger, options); + connection.onError((data) => { + errorHandler(data[0], data[1], data[2]); + }); + connection.onClose(closeHandler); + const result = { + listen: () => connection.listen(), + sendRequest: connection.sendRequest, + onRequest: connection.onRequest, + hasPendingResponse: connection.hasPendingResponse, + sendNotification: connection.sendNotification, + onNotification: connection.onNotification, + onProgress: connection.onProgress, + sendProgress: connection.sendProgress, + trace: (value, tracer, sendNotificationOrTraceOptions) => { + const defaultTraceOptions = { + sendNotification: false, + traceFormat: vscode_languageserver_protocol_1.TraceFormat.Text + }; + if (sendNotificationOrTraceOptions === void 0) { + return connection.trace(value, tracer, defaultTraceOptions); + } else if (Is.boolean(sendNotificationOrTraceOptions)) { + return connection.trace(value, tracer, sendNotificationOrTraceOptions); + } else { + return connection.trace(value, tracer, sendNotificationOrTraceOptions); + } + }, + initialize: (params) => { + return connection.sendRequest(vscode_languageserver_protocol_1.InitializeRequest.type, params); + }, + shutdown: () => { + return connection.sendRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, void 0); + }, + exit: () => { + return connection.sendNotification(vscode_languageserver_protocol_1.ExitNotification.type); + }, + end: () => connection.end(), + dispose: () => connection.dispose() + }; + return result; + } + var ProposedFeatures; + (function(ProposedFeatures2) { + function createAll(_client) { + let result = [ + new inlineCompletion_1.InlineCompletionItemFeature(_client) + ]; + return result; + } + ProposedFeatures2.createAll = createAll; + })(ProposedFeatures || (exports2.ProposedFeatures = ProposedFeatures = {})); + } +}); + +// node_modules/vscode-languageclient/lib/node/processes.js +var require_processes = __commonJS({ + "node_modules/vscode-languageclient/lib/node/processes.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.terminate = void 0; + var cp2 = require("child_process"); + var path_1 = require("path"); + var isWindows = process.platform === "win32"; + var isMacintosh = process.platform === "darwin"; + var isLinux = process.platform === "linux"; + function terminate(process2, cwd) { + if (isWindows) { + try { + let options = { + stdio: ["pipe", "pipe", "ignore"] + }; + if (cwd) { + options.cwd = cwd; + } + cp2.execFileSync("taskkill", ["/T", "/F", "/PID", process2.pid.toString()], options); + return true; + } catch (err) { + return false; + } + } else if (isLinux || isMacintosh) { + try { + var cmd = (0, path_1.join)(__dirname, "terminateProcess.sh"); + var result = cp2.spawnSync(cmd, [process2.pid.toString()]); + return result.error ? false : true; + } catch (err) { + return false; + } + } else { + process2.kill("SIGKILL"); + return true; + } + } + exports2.terminate = terminate; + } +}); + +// node_modules/vscode-languageserver-protocol/node.js +var require_node2 = __commonJS({ + "node_modules/vscode-languageserver-protocol/node.js"(exports2, module2) { + "use strict"; + module2.exports = require_main3(); + } +}); + +// node_modules/semver/internal/debug.js +var require_debug = __commonJS({ + "node_modules/semver/internal/debug.js"(exports2, module2) { + "use strict"; + var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { + }; + module2.exports = debug; + } +}); + +// node_modules/semver/internal/constants.js +var require_constants = __commonJS({ + "node_modules/semver/internal/constants.js"(exports2, module2) { + "use strict"; + var SEMVER_SPEC_VERSION = "2.0.0"; + var MAX_LENGTH = 256; + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ + 9007199254740991; + var MAX_SAFE_COMPONENT_LENGTH = 16; + var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; + var RELEASE_TYPES = [ + "major", + "premajor", + "minor", + "preminor", + "patch", + "prepatch", + "prerelease" + ]; + module2.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 1, + FLAG_LOOSE: 2 + }; + } +}); + +// node_modules/semver/internal/re.js +var require_re = __commonJS({ + "node_modules/semver/internal/re.js"(exports2, module2) { + "use strict"; + var { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH + } = require_constants(); + var debug = require_debug(); + exports2 = module2.exports = {}; + var re = exports2.re = []; + var safeRe = exports2.safeRe = []; + var src = exports2.src = []; + var safeSrc = exports2.safeSrc = []; + var t = exports2.t = {}; + var R = 0; + var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; + var safeRegexReplacements = [ + ["\\s", 1], + ["\\d", MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] + ]; + var makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`); + } + return value; + }; + var createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value); + const index = R++; + debug(name, index, value); + t[name] = index; + src[index] = value; + safeSrc[index] = safe; + re[index] = new RegExp(value, isGlobal ? "g" : void 0); + safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0); + }; + createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); + createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); + createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); + createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`); + createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`); + createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); + createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); + createToken("FULL", `^${src[t.FULLPLAIN]}$`); + createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); + createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`); + createToken("GTLT", "((?:<|>)?=?)"); + createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`); + createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`); + createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`); + createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`); + createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`); + createToken("COERCERTL", src[t.COERCE], true); + createToken("COERCERTLFULL", src[t.COERCEFULL], true); + createToken("LONETILDE", "(?:~>?)"); + createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports2.tildeTrimReplace = "$1~"; + createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken("LONECARET", "(?:\\^)"); + createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports2.caretTrimReplace = "$1^"; + createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports2.comparatorTrimReplace = "$1$2$3"; + createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`); + createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`); + createToken("STAR", "(<|>)?=?\\s*\\*"); + createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); + createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); + } +}); + +// node_modules/semver/internal/parse-options.js +var require_parse_options = __commonJS({ + "node_modules/semver/internal/parse-options.js"(exports2, module2) { + "use strict"; + var looseOption = Object.freeze({ loose: true }); + var emptyOpts = Object.freeze({}); + var parseOptions = (options) => { + if (!options) { + return emptyOpts; + } + if (typeof options !== "object") { + return looseOption; + } + return options; + }; + module2.exports = parseOptions; + } +}); + +// node_modules/semver/internal/identifiers.js +var require_identifiers = __commonJS({ + "node_modules/semver/internal/identifiers.js"(exports2, module2) { + "use strict"; + var numeric = /^[0-9]+$/; + var compareIdentifiers = (a, b) => { + if (typeof a === "number" && typeof b === "number") { + return a === b ? 0 : a < b ? -1 : 1; + } + const anum = numeric.test(a); + const bnum = numeric.test(b); + if (anum && bnum) { + a = +a; + b = +b; + } + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; + }; + var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a); + module2.exports = { + compareIdentifiers, + rcompareIdentifiers + }; + } +}); + +// node_modules/semver/classes/semver.js +var require_semver = __commonJS({ + "node_modules/semver/classes/semver.js"(exports2, module2) { + "use strict"; + var debug = require_debug(); + var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants(); + var { safeRe: re, t } = require_re(); + var parseOptions = require_parse_options(); + var { compareIdentifiers } = require_identifiers(); + var isPrereleaseIdentifier = (prerelease, identifier) => { + const identifiers = identifier.split("."); + if (identifiers.length > prerelease.length) { + return false; + } + for (let i = 0; i < identifiers.length; i++) { + if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) { + return false; + } + } + return true; + }; + var SemVer = class _SemVer { + constructor(version, options) { + options = parseOptions(options); + if (version instanceof _SemVer) { + if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== "string") { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`); + } + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ); + } + debug("SemVer", version, options); + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); + if (!m) { + throw new TypeError(`Invalid Version: ${version}`); + } + this.raw = version; + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError("Invalid major version"); + } + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError("Invalid minor version"); + } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError("Invalid patch version"); + } + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split(".").map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + return id; + }); + } + this.build = m[5] ? m[5].split(".") : []; + this.format(); + } + format() { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join(".")}`; + } + return this.version; + } + toString() { + return this.version; + } + compare(other) { + debug("SemVer.compare", this.version, this.options, other); + if (!(other instanceof _SemVer)) { + if (typeof other === "string" && other === this.version) { + return 0; + } + other = new _SemVer(other, this.options); + } + if (other.version === this.version) { + return 0; + } + return this.compareMain(other) || this.comparePre(other); + } + compareMain(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + if (this.major < other.major) { + return -1; + } + if (this.major > other.major) { + return 1; + } + if (this.minor < other.minor) { + return -1; + } + if (this.minor > other.minor) { + return 1; + } + if (this.patch < other.patch) { + return -1; + } + if (this.patch > other.patch) { + return 1; + } + return 0; + } + comparePre(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug("prerelease compare", i, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + compareBuild(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug("build compare", i, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc(release, identifier, identifierBase) { + if (release.startsWith("pre")) { + if (!identifier && identifierBase === false) { + throw new Error("invalid increment argument: identifier is empty"); + } + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]); + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`); + } + } + } + switch (release) { + case "premajor": + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc("pre", identifier, identifierBase); + break; + case "preminor": + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc("pre", identifier, identifierBase); + break; + case "prepatch": + this.prerelease.length = 0; + this.inc("patch", identifier, identifierBase); + this.inc("pre", identifier, identifierBase); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case "prerelease": + if (this.prerelease.length === 0) { + this.inc("patch", identifier, identifierBase); + } + this.inc("pre", identifier, identifierBase); + break; + case "release": + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`); + } + this.prerelease.length = 0; + break; + case "major": + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case "minor": + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break; + case "patch": + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case "pre": { + const base = Number(identifierBase) ? 1 : 0; + if (this.prerelease.length === 0) { + this.prerelease = [base]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === "number") { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) { + if (identifier === this.prerelease.join(".") && identifierBase === false) { + throw new Error("invalid increment argument: identifier already exists"); + } + this.prerelease.push(base); + } + } + if (identifier) { + let prerelease = [identifier, base]; + if (identifierBase === false) { + prerelease = [identifier]; + } + if (isPrereleaseIdentifier(this.prerelease, identifier)) { + const prereleaseBase = this.prerelease[identifier.split(".").length]; + if (isNaN(prereleaseBase)) { + this.prerelease = prerelease; + } + } else { + this.prerelease = prerelease; + } + } + break; + } + default: + throw new Error(`invalid increment argument: ${release}`); + } + this.raw = this.format(); + if (this.build.length) { + this.raw += `+${this.build.join(".")}`; + } + return this; + } + }; + module2.exports = SemVer; + } +}); + +// node_modules/semver/functions/parse.js +var require_parse = __commonJS({ + "node_modules/semver/functions/parse.js"(exports2, module2) { + "use strict"; + var SemVer = require_semver(); + var parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version; + } + try { + return new SemVer(version, options); + } catch (er) { + if (!throwErrors) { + return null; + } + throw er; + } + }; + module2.exports = parse; + } +}); + +// node_modules/semver/internal/lrucache.js +var require_lrucache = __commonJS({ + "node_modules/semver/internal/lrucache.js"(exports2, module2) { + "use strict"; + var LRUCache = class { + constructor() { + this.max = 1e3; + this.map = /* @__PURE__ */ new Map(); + } + get(key) { + const value = this.map.get(key); + if (value === void 0) { + return void 0; + } else { + this.map.delete(key); + this.map.set(key, value); + return value; + } + } + delete(key) { + return this.map.delete(key); + } + set(key, value) { + const deleted = this.delete(key); + if (!deleted && value !== void 0) { + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value; + this.delete(firstKey); + } + this.map.set(key, value); + } + return this; + } + }; + module2.exports = LRUCache; + } +}); + +// node_modules/semver/functions/compare.js +var require_compare = __commonJS({ + "node_modules/semver/functions/compare.js"(exports2, module2) { + "use strict"; + var SemVer = require_semver(); + var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)); + module2.exports = compare; + } +}); + +// node_modules/semver/functions/eq.js +var require_eq = __commonJS({ + "node_modules/semver/functions/eq.js"(exports2, module2) { + "use strict"; + var compare = require_compare(); + var eq = (a, b, loose) => compare(a, b, loose) === 0; + module2.exports = eq; + } +}); + +// node_modules/semver/functions/neq.js +var require_neq = __commonJS({ + "node_modules/semver/functions/neq.js"(exports2, module2) { + "use strict"; + var compare = require_compare(); + var neq = (a, b, loose) => compare(a, b, loose) !== 0; + module2.exports = neq; + } +}); + +// node_modules/semver/functions/gt.js +var require_gt = __commonJS({ + "node_modules/semver/functions/gt.js"(exports2, module2) { + "use strict"; + var compare = require_compare(); + var gt = (a, b, loose) => compare(a, b, loose) > 0; + module2.exports = gt; + } +}); + +// node_modules/semver/functions/gte.js +var require_gte = __commonJS({ + "node_modules/semver/functions/gte.js"(exports2, module2) { + "use strict"; + var compare = require_compare(); + var gte = (a, b, loose) => compare(a, b, loose) >= 0; + module2.exports = gte; + } +}); + +// node_modules/semver/functions/lt.js +var require_lt = __commonJS({ + "node_modules/semver/functions/lt.js"(exports2, module2) { + "use strict"; + var compare = require_compare(); + var lt = (a, b, loose) => compare(a, b, loose) < 0; + module2.exports = lt; + } +}); + +// node_modules/semver/functions/lte.js +var require_lte = __commonJS({ + "node_modules/semver/functions/lte.js"(exports2, module2) { + "use strict"; + var compare = require_compare(); + var lte = (a, b, loose) => compare(a, b, loose) <= 0; + module2.exports = lte; + } +}); + +// node_modules/semver/functions/cmp.js +var require_cmp = __commonJS({ + "node_modules/semver/functions/cmp.js"(exports2, module2) { + "use strict"; + var eq = require_eq(); + var neq = require_neq(); + var gt = require_gt(); + var gte = require_gte(); + var lt = require_lt(); + var lte = require_lte(); + var cmp = (a, op, b, loose) => { + switch (op) { + case "===": + if (typeof a === "object") { + a = a.version; + } + if (typeof b === "object") { + b = b.version; + } + return a === b; + case "!==": + if (typeof a === "object") { + a = a.version; + } + if (typeof b === "object") { + b = b.version; + } + return a !== b; + case "": + case "=": + case "==": + return eq(a, b, loose); + case "!=": + return neq(a, b, loose); + case ">": + return gt(a, b, loose); + case ">=": + return gte(a, b, loose); + case "<": + return lt(a, b, loose); + case "<=": + return lte(a, b, loose); + default: + throw new TypeError(`Invalid operator: ${op}`); + } + }; + module2.exports = cmp; + } +}); + +// node_modules/semver/classes/comparator.js +var require_comparator = __commonJS({ + "node_modules/semver/classes/comparator.js"(exports2, module2) { + "use strict"; + var ANY = /* @__PURE__ */ Symbol("SemVer ANY"); + var Comparator = class _Comparator { + static get ANY() { + return ANY; + } + constructor(comp, options) { + options = parseOptions(options); + if (comp instanceof _Comparator) { + if (comp.loose === !!options.loose) { + return comp; + } else { + comp = comp.value; + } + } + comp = comp.trim().split(/\s+/).join(" "); + debug("comparator", comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + if (this.semver === ANY) { + this.value = ""; + } else { + this.value = this.operator + this.semver.version; + } + debug("comp", this); + } + parse(comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`); + } + this.operator = m[1] !== void 0 ? m[1] : ""; + if (this.operator === "=") { + this.operator = ""; + } + if (!m[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m[2], this.options.loose); + } + } + toString() { + return this.value; + } + test(version) { + debug("Comparator.test", version, this.options.loose); + if (this.semver === ANY || version === ANY) { + return true; + } + if (typeof version === "string") { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + return cmp(version, this.operator, this.semver, this.options); + } + intersects(comp, options) { + if (!(comp instanceof _Comparator)) { + throw new TypeError("a Comparator is required"); + } + if (this.operator === "") { + if (this.value === "") { + return true; + } + return new Range(comp.value, options).test(this.value); + } else if (comp.operator === "") { + if (comp.value === "") { + return true; + } + return new Range(this.value, options).test(comp.semver); + } + options = parseOptions(options); + if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) { + return false; + } + if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) { + return false; + } + if (this.operator.startsWith(">") && comp.operator.startsWith(">")) { + return true; + } + if (this.operator.startsWith("<") && comp.operator.startsWith("<")) { + return true; + } + if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) { + return true; + } + if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) { + return true; + } + if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) { + return true; + } + return false; + } + }; + module2.exports = Comparator; + var parseOptions = require_parse_options(); + var { safeRe: re, t } = require_re(); + var cmp = require_cmp(); + var debug = require_debug(); + var SemVer = require_semver(); + var Range = require_range(); + } +}); + +// node_modules/semver/classes/range.js +var require_range = __commonJS({ + "node_modules/semver/classes/range.js"(exports2, module2) { + "use strict"; + var SPACE_CHARACTERS = /\s+/g; + var Range = class _Range { + constructor(range, options) { + options = parseOptions(options); + if (range instanceof _Range) { + if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { + return range; + } else { + return new _Range(range.raw, options); + } + } + if (range instanceof Comparator) { + this.raw = range.value; + this.set = [[range]]; + this.formatted = void 0; + return this; + } + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + this.raw = range.trim().replace(SPACE_CHARACTERS, " "); + this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length); + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`); + } + if (this.set.length > 1) { + const first = this.set[0]; + this.set = this.set.filter((c) => !isNullSet(c[0])); + if (this.set.length === 0) { + this.set = [first]; + } else if (this.set.length > 1) { + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break; + } + } + } + } + this.formatted = void 0; + } + get range() { + if (this.formatted === void 0) { + this.formatted = ""; + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += "||"; + } + const comps = this.set[i]; + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += " "; + } + this.formatted += comps[k].toString().trim(); + } + } + } + return this.formatted; + } + format() { + return this.range; + } + toString() { + return this.range; + } + parseRange(range) { + range = range.replace(BUILDSTRIPRE, ""); + const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE); + const memoKey = memoOpts + ":" + range; + const cached = cache.get(memoKey); + if (cached) { + return cached; + } + const loose = this.options.loose; + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug("hyphen replace", range); + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace); + debug("comparator trim", range); + range = range.replace(re[t.TILDETRIM], tildeTrimReplace); + debug("tilde trim", range); + range = range.replace(re[t.CARETTRIM], caretTrimReplace); + debug("caret trim", range); + let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)); + if (loose) { + rangeList = rangeList.filter((comp) => { + debug("loose invalid filter", comp, this.options); + return !!comp.match(re[t.COMPARATORLOOSE]); + }); + } + debug("range list", rangeList); + const rangeMap = /* @__PURE__ */ new Map(); + const comparators = rangeList.map((comp) => new Comparator(comp, this.options)); + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp]; + } + rangeMap.set(comp.value, comp); + } + if (rangeMap.size > 1 && rangeMap.has("")) { + rangeMap.delete(""); + } + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result; + } + intersects(range, options) { + if (!(range instanceof _Range)) { + throw new TypeError("a Range is required"); + } + return this.set.some((thisComparators) => { + return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { + return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); + } + // if ANY of the sets match ALL of its comparators, then pass + test(version) { + if (!version) { + return false; + } + if (typeof version === "string") { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true; + } + } + return false; + } + }; + module2.exports = Range; + var LRU = require_lrucache(); + var cache = new LRU(); + var parseOptions = require_parse_options(); + var Comparator = require_comparator(); + var debug = require_debug(); + var SemVer = require_semver(); + var { + safeRe: re, + src, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = require_re(); + var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants(); + var BUILDSTRIPRE = new RegExp(src[t.BUILD], "g"); + var isNullSet = (c) => c.value === "<0.0.0-0"; + var isAny = (c) => c.value === ""; + var isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options); + }); + testComparator = remainingComparators.pop(); + } + return result; + }; + var parseComparator = (comp, options) => { + comp = comp.replace(re[t.BUILD], ""); + debug("comp", comp, options); + comp = replaceCarets(comp, options); + debug("caret", comp); + comp = replaceTildes(comp, options); + debug("tildes", comp); + comp = replaceXRanges(comp, options); + debug("xrange", comp); + comp = replaceStars(comp, options); + debug("stars", comp); + return comp; + }; + var isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; + var replaceTildes = (comp, options) => { + return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" "); + }; + var replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug("tilde", comp, _, M, m, p, pr); + let ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug("replaceTilde pr", pr); + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; + } + debug("tilde return", ret); + return ret; + }); + }; + var replaceCarets = (comp, options) => { + return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" "); + }; + var replaceCaret = (comp, options) => { + debug("caret", comp, options); + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]; + const z = options.includePrerelease ? "-0" : ""; + return comp.replace(r, (_, M, m, p, pr) => { + debug("caret", comp, _, M, m, p, pr); + let ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === "0") { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug("replaceCaret pr", pr); + if (M === "0") { + if (m === "0") { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; + } + } else { + debug("no pr"); + if (M === "0") { + if (m === "0") { + ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; + } + } + debug("caret return", ret); + return ret; + }); + }; + var replaceXRanges = (comp, options) => { + debug("replaceXRanges", comp, options); + return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" "); + }; + var replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug("xRange", comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + if (gtlt === "=" && anyX) { + gtlt = ""; + } + pr = options.includePrerelease ? "-0" : ""; + if (xM) { + if (gtlt === ">" || gtlt === "<") { + ret = "<0.0.0-0"; + } else { + ret = "*"; + } + } else if (gtlt && anyX) { + if (xm) { + m = 0; + } + p = 0; + if (gtlt === ">") { + gtlt = ">="; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === "<=") { + gtlt = "<"; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + if (gtlt === "<") { + pr = "-0"; + } + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; + } + debug("xRange return", ret); + return ret; + }); + }; + var replaceStars = (comp, options) => { + debug("replaceStars", comp, options); + return comp.trim().replace(re[t.STAR], ""); + }; + var replaceGTE0 = (comp, options) => { + debug("replaceGTE0", comp, options); + return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], ""); + }; + var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = ""; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? "-0" : ""}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? "-0" : ""}`; + } + if (isX(tM)) { + to = ""; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + return `${from} ${to}`.trim(); + }; + var testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false; + } + } + if (version.prerelease.length && !options.includePrerelease) { + for (let i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === Comparator.ANY) { + continue; + } + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { + return true; + } + } + } + return false; + } + return true; + }; + } +}); + +// node_modules/semver/functions/satisfies.js +var require_satisfies = __commonJS({ + "node_modules/semver/functions/satisfies.js"(exports2, module2) { + "use strict"; + var Range = require_range(); + var satisfies = (version, range, options) => { + try { + range = new Range(range, options); + } catch (er) { + return false; + } + return range.test(version); + }; + module2.exports = satisfies; + } +}); + +// node_modules/vscode-languageclient/lib/common/api.js +var require_api3 = __commonJS({ + "node_modules/vscode-languageclient/lib/common/api.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DiagnosticPullMode = exports2.vsdiag = void 0; + __exportStar(require_main3(), exports2); + __exportStar(require_features(), exports2); + var diagnostic_1 = require_diagnostic(); + Object.defineProperty(exports2, "vsdiag", { enumerable: true, get: function() { + return diagnostic_1.vsdiag; + } }); + Object.defineProperty(exports2, "DiagnosticPullMode", { enumerable: true, get: function() { + return diagnostic_1.DiagnosticPullMode; + } }); + __exportStar(require_client(), exports2); + } +}); + +// node_modules/vscode-languageclient/lib/node/main.js +var require_main4 = __commonJS({ + "node_modules/vscode-languageclient/lib/node/main.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SettingMonitor = exports2.LanguageClient = exports2.TransportKind = void 0; + var cp2 = require("child_process"); + var fs5 = require("fs"); + var path8 = require("path"); + var vscode_1 = require("vscode"); + var Is = require_is(); + var client_1 = require_client(); + var processes_1 = require_processes(); + var node_1 = require_node2(); + var semverParse = require_parse(); + var semverSatisfies = require_satisfies(); + __exportStar(require_node2(), exports2); + __exportStar(require_api3(), exports2); + var REQUIRED_VSCODE_VERSION = "^1.82.0"; + var TransportKind2; + (function(TransportKind3) { + TransportKind3[TransportKind3["stdio"] = 0] = "stdio"; + TransportKind3[TransportKind3["ipc"] = 1] = "ipc"; + TransportKind3[TransportKind3["pipe"] = 2] = "pipe"; + TransportKind3[TransportKind3["socket"] = 3] = "socket"; + })(TransportKind2 || (exports2.TransportKind = TransportKind2 = {})); + var Transport; + (function(Transport2) { + function isSocket(value) { + const candidate = value; + return candidate && candidate.kind === TransportKind2.socket && Is.number(candidate.port); + } + Transport2.isSocket = isSocket; + })(Transport || (Transport = {})); + var Executable; + (function(Executable2) { + function is(value) { + return Is.string(value.command); + } + Executable2.is = is; + })(Executable || (Executable = {})); + var NodeModule; + (function(NodeModule2) { + function is(value) { + return Is.string(value.module); + } + NodeModule2.is = is; + })(NodeModule || (NodeModule = {})); + var StreamInfo; + (function(StreamInfo2) { + function is(value) { + let candidate = value; + return candidate && candidate.writer !== void 0 && candidate.reader !== void 0; + } + StreamInfo2.is = is; + })(StreamInfo || (StreamInfo = {})); + var ChildProcessInfo; + (function(ChildProcessInfo2) { + function is(value) { + let candidate = value; + return candidate && candidate.process !== void 0 && typeof candidate.detached === "boolean"; + } + ChildProcessInfo2.is = is; + })(ChildProcessInfo || (ChildProcessInfo = {})); + var LanguageClient2 = class extends client_1.BaseLanguageClient { + constructor(arg1, arg2, arg3, arg4, arg5) { + let id; + let name; + let serverOptions; + let clientOptions; + let forceDebug; + if (Is.string(arg2)) { + id = arg1; + name = arg2; + serverOptions = arg3; + clientOptions = arg4; + forceDebug = !!arg5; + } else { + id = arg1.toLowerCase(); + name = arg1; + serverOptions = arg2; + clientOptions = arg3; + forceDebug = arg4; + } + if (forceDebug === void 0) { + forceDebug = false; + } + super(id, name, clientOptions); + this._serverOptions = serverOptions; + this._forceDebug = forceDebug; + this._isInDebugMode = forceDebug; + try { + this.checkVersion(); + } catch (error) { + if (Is.string(error.message)) { + this.outputChannel.appendLine(error.message); + } + throw error; + } + } + checkVersion() { + const codeVersion = semverParse(vscode_1.version); + if (!codeVersion) { + throw new Error(`No valid VS Code version detected. Version string is: ${vscode_1.version}`); + } + if (codeVersion.prerelease && codeVersion.prerelease.length > 0) { + codeVersion.prerelease = []; + } + if (!semverSatisfies(codeVersion, REQUIRED_VSCODE_VERSION)) { + throw new Error(`The language client requires VS Code version ${REQUIRED_VSCODE_VERSION} but received version ${vscode_1.version}`); + } + } + get isInDebugMode() { + return this._isInDebugMode; + } + async restart() { + await this.stop(); + if (this.isInDebugMode) { + await new Promise((resolve) => setTimeout(resolve, 1e3)); + await this.start(); + } else { + await this.start(); + } + } + stop(timeout = 2e3) { + return super.stop(timeout).finally(() => { + if (this._serverProcess) { + const toCheck = this._serverProcess; + this._serverProcess = void 0; + if (this._isDetached === void 0 || !this._isDetached) { + this.checkProcessDied(toCheck); + } + this._isDetached = void 0; + } + }); + } + checkProcessDied(childProcess) { + if (!childProcess || childProcess.pid === void 0) { + return; + } + setTimeout(() => { + try { + if (childProcess.pid !== void 0) { + process.kill(childProcess.pid, 0); + (0, processes_1.terminate)(childProcess); + } + } catch (error) { + } + }, 2e3); + } + handleConnectionClosed() { + this._serverProcess = void 0; + return super.handleConnectionClosed(); + } + fillInitializeParams(params) { + super.fillInitializeParams(params); + if (params.processId === null) { + params.processId = process.pid; + } + } + createMessageTransports(encoding) { + function getEnvironment(env4, fork) { + if (!env4 && !fork) { + return void 0; + } + const result = /* @__PURE__ */ Object.create(null); + Object.keys(process.env).forEach((key) => result[key] = process.env[key]); + if (fork) { + result["ELECTRON_RUN_AS_NODE"] = "1"; + result["ELECTRON_NO_ASAR"] = "1"; + } + if (env4) { + Object.keys(env4).forEach((key) => result[key] = env4[key]); + } + return result; + } + const debugStartWith = ["--debug=", "--debug-brk=", "--inspect=", "--inspect-brk="]; + const debugEquals = ["--debug", "--debug-brk", "--inspect", "--inspect-brk"]; + function startedInDebugMode() { + let args = process.execArgv; + if (args) { + return args.some((arg) => { + return debugStartWith.some((value) => arg.startsWith(value)) || debugEquals.some((value) => arg === value); + }); + } + return false; + } + function assertStdio(process2) { + if (process2.stdin === null || process2.stdout === null || process2.stderr === null) { + throw new Error("Process created without stdio streams"); + } + } + const server = this._serverOptions; + if (Is.func(server)) { + return server().then((result) => { + if (client_1.MessageTransports.is(result)) { + this._isDetached = !!result.detached; + return result; + } else if (StreamInfo.is(result)) { + this._isDetached = !!result.detached; + return { reader: new node_1.StreamMessageReader(result.reader), writer: new node_1.StreamMessageWriter(result.writer) }; + } else { + let cp3; + if (ChildProcessInfo.is(result)) { + cp3 = result.process; + this._isDetached = result.detached; + } else { + cp3 = result; + this._isDetached = false; + } + cp3.stderr.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + return { reader: new node_1.StreamMessageReader(cp3.stdout), writer: new node_1.StreamMessageWriter(cp3.stdin) }; + } + }); + } + let json; + let runDebug = server; + if (runDebug.run || runDebug.debug) { + if (this._forceDebug || startedInDebugMode()) { + json = runDebug.debug; + this._isInDebugMode = true; + } else { + json = runDebug.run; + this._isInDebugMode = false; + } + } else { + json = server; + } + return this._getServerWorkingDir(json.options).then((serverWorkingDir) => { + if (NodeModule.is(json) && json.module) { + let node = json; + let transport = node.transport || TransportKind2.stdio; + if (node.runtime) { + const args = []; + const options = node.options ?? /* @__PURE__ */ Object.create(null); + if (options.execArgv) { + options.execArgv.forEach((element) => args.push(element)); + } + args.push(node.module); + if (node.args) { + node.args.forEach((element) => args.push(element)); + } + const execOptions = /* @__PURE__ */ Object.create(null); + execOptions.cwd = serverWorkingDir; + execOptions.env = getEnvironment(options.env, false); + const runtime = this._getRuntimePath(node.runtime, serverWorkingDir); + let pipeName = void 0; + if (transport === TransportKind2.ipc) { + execOptions.stdio = [null, null, null, "ipc"]; + args.push("--node-ipc"); + } else if (transport === TransportKind2.stdio) { + args.push("--stdio"); + } else if (transport === TransportKind2.pipe) { + pipeName = (0, node_1.generateRandomPipeName)(); + args.push(`--pipe=${pipeName}`); + } else if (Transport.isSocket(transport)) { + args.push(`--socket=${transport.port}`); + } + args.push(`--clientProcessId=${process.pid.toString()}`); + if (transport === TransportKind2.ipc || transport === TransportKind2.stdio) { + const serverProcess = cp2.spawn(runtime, args, execOptions); + if (!serverProcess || !serverProcess.pid) { + return handleChildProcessStartError(serverProcess, `Launching server using runtime ${runtime} failed.`); + } + this._serverProcess = serverProcess; + serverProcess.stderr.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + if (transport === TransportKind2.ipc) { + serverProcess.stdout.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + return Promise.resolve({ reader: new node_1.IPCMessageReader(serverProcess), writer: new node_1.IPCMessageWriter(serverProcess) }); + } else { + return Promise.resolve({ reader: new node_1.StreamMessageReader(serverProcess.stdout), writer: new node_1.StreamMessageWriter(serverProcess.stdin) }); + } + } else if (transport === TransportKind2.pipe) { + return (0, node_1.createClientPipeTransport)(pipeName).then((transport2) => { + const process2 = cp2.spawn(runtime, args, execOptions); + if (!process2 || !process2.pid) { + return handleChildProcessStartError(process2, `Launching server using runtime ${runtime} failed.`); + } + this._serverProcess = process2; + process2.stderr.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + process2.stdout.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + return transport2.onConnected().then((protocol) => { + return { reader: protocol[0], writer: protocol[1] }; + }); + }); + } else if (Transport.isSocket(transport)) { + return (0, node_1.createClientSocketTransport)(transport.port).then((transport2) => { + const process2 = cp2.spawn(runtime, args, execOptions); + if (!process2 || !process2.pid) { + return handleChildProcessStartError(process2, `Launching server using runtime ${runtime} failed.`); + } + this._serverProcess = process2; + process2.stderr.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + process2.stdout.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + return transport2.onConnected().then((protocol) => { + return { reader: protocol[0], writer: protocol[1] }; + }); + }); + } + } else { + let pipeName = void 0; + return new Promise((resolve, reject) => { + const args = (node.args && node.args.slice()) ?? []; + if (transport === TransportKind2.ipc) { + args.push("--node-ipc"); + } else if (transport === TransportKind2.stdio) { + args.push("--stdio"); + } else if (transport === TransportKind2.pipe) { + pipeName = (0, node_1.generateRandomPipeName)(); + args.push(`--pipe=${pipeName}`); + } else if (Transport.isSocket(transport)) { + args.push(`--socket=${transport.port}`); + } + args.push(`--clientProcessId=${process.pid.toString()}`); + const options = node.options ?? /* @__PURE__ */ Object.create(null); + options.env = getEnvironment(options.env, true); + options.execArgv = options.execArgv || []; + options.cwd = serverWorkingDir; + options.silent = true; + if (transport === TransportKind2.ipc || transport === TransportKind2.stdio) { + const sp = cp2.fork(node.module, args || [], options); + assertStdio(sp); + this._serverProcess = sp; + sp.stderr.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + if (transport === TransportKind2.ipc) { + sp.stdout.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + resolve({ reader: new node_1.IPCMessageReader(this._serverProcess), writer: new node_1.IPCMessageWriter(this._serverProcess) }); + } else { + resolve({ reader: new node_1.StreamMessageReader(sp.stdout), writer: new node_1.StreamMessageWriter(sp.stdin) }); + } + } else if (transport === TransportKind2.pipe) { + (0, node_1.createClientPipeTransport)(pipeName).then((transport2) => { + const sp = cp2.fork(node.module, args || [], options); + assertStdio(sp); + this._serverProcess = sp; + sp.stderr.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + sp.stdout.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + transport2.onConnected().then((protocol) => { + resolve({ reader: protocol[0], writer: protocol[1] }); + }, reject); + }, reject); + } else if (Transport.isSocket(transport)) { + (0, node_1.createClientSocketTransport)(transport.port).then((transport2) => { + const sp = cp2.fork(node.module, args || [], options); + assertStdio(sp); + this._serverProcess = sp; + sp.stderr.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + sp.stdout.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + transport2.onConnected().then((protocol) => { + resolve({ reader: protocol[0], writer: protocol[1] }); + }, reject); + }, reject); + } + }); + } + } else if (Executable.is(json) && json.command) { + const command = json; + const args = json.args !== void 0 ? json.args.slice(0) : []; + let pipeName = void 0; + const transport = json.transport; + if (transport === TransportKind2.stdio) { + args.push("--stdio"); + } else if (transport === TransportKind2.pipe) { + pipeName = (0, node_1.generateRandomPipeName)(); + args.push(`--pipe=${pipeName}`); + } else if (Transport.isSocket(transport)) { + args.push(`--socket=${transport.port}`); + } else if (transport === TransportKind2.ipc) { + throw new Error(`Transport kind ipc is not support for command executable`); + } + const options = Object.assign({}, command.options); + options.cwd = options.cwd || serverWorkingDir; + if (transport === void 0 || transport === TransportKind2.stdio) { + const serverProcess = cp2.spawn(command.command, args, options); + if (!serverProcess || !serverProcess.pid) { + return handleChildProcessStartError(serverProcess, `Launching server using command ${command.command} failed.`); + } + serverProcess.stderr.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + this._serverProcess = serverProcess; + this._isDetached = !!options.detached; + return Promise.resolve({ reader: new node_1.StreamMessageReader(serverProcess.stdout), writer: new node_1.StreamMessageWriter(serverProcess.stdin) }); + } else if (transport === TransportKind2.pipe) { + return (0, node_1.createClientPipeTransport)(pipeName).then((transport2) => { + const serverProcess = cp2.spawn(command.command, args, options); + if (!serverProcess || !serverProcess.pid) { + return handleChildProcessStartError(serverProcess, `Launching server using command ${command.command} failed.`); + } + this._serverProcess = serverProcess; + this._isDetached = !!options.detached; + serverProcess.stderr.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + serverProcess.stdout.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + return transport2.onConnected().then((protocol) => { + return { reader: protocol[0], writer: protocol[1] }; + }); + }); + } else if (Transport.isSocket(transport)) { + return (0, node_1.createClientSocketTransport)(transport.port).then((transport2) => { + const serverProcess = cp2.spawn(command.command, args, options); + if (!serverProcess || !serverProcess.pid) { + return handleChildProcessStartError(serverProcess, `Launching server using command ${command.command} failed.`); + } + this._serverProcess = serverProcess; + this._isDetached = !!options.detached; + serverProcess.stderr.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + serverProcess.stdout.on("data", (data) => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); + return transport2.onConnected().then((protocol) => { + return { reader: protocol[0], writer: protocol[1] }; + }); + }); + } + } + return Promise.reject(new Error(`Unsupported server configuration ` + JSON.stringify(server, null, 4))); + }).finally(() => { + if (this._serverProcess !== void 0) { + this._serverProcess.on("exit", (code, signal) => { + if (code !== null) { + this.error(`Server process exited with code ${code}.`, void 0, false); + } + if (signal !== null) { + this.error(`Server process exited with signal ${signal}.`, void 0, false); + } + }); + } + }); + } + _getRuntimePath(runtime, serverWorkingDirectory) { + if (path8.isAbsolute(runtime)) { + return runtime; + } + const mainRootPath = this._mainGetRootPath(); + if (mainRootPath !== void 0) { + const result = path8.join(mainRootPath, runtime); + if (fs5.existsSync(result)) { + return result; + } + } + if (serverWorkingDirectory !== void 0) { + const result = path8.join(serverWorkingDirectory, runtime); + if (fs5.existsSync(result)) { + return result; + } + } + return runtime; + } + _mainGetRootPath() { + let folders = vscode_1.workspace.workspaceFolders; + if (!folders || folders.length === 0) { + return void 0; + } + let folder = folders[0]; + if (folder.uri.scheme === "file") { + return folder.uri.fsPath; + } + return void 0; + } + _getServerWorkingDir(options) { + let cwd = options && options.cwd; + if (!cwd) { + cwd = this.clientOptions.workspaceFolder ? this.clientOptions.workspaceFolder.uri.fsPath : this._mainGetRootPath(); + } + if (cwd) { + return new Promise((s) => { + fs5.lstat(cwd, (err, stats) => { + s(!err && stats.isDirectory() ? cwd : void 0); + }); + }); + } + return Promise.resolve(void 0); + } + }; + exports2.LanguageClient = LanguageClient2; + var SettingMonitor = class { + constructor(_client, _setting) { + this._client = _client; + this._setting = _setting; + this._listeners = []; + } + start() { + vscode_1.workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this, this._listeners); + this.onDidChangeConfiguration(); + return new vscode_1.Disposable(() => { + if (this._client.needsStop()) { + void this._client.stop(); + } + }); + } + onDidChangeConfiguration() { + let index = this._setting.indexOf("."); + let primary = index >= 0 ? this._setting.substr(0, index) : this._setting; + let rest = index >= 0 ? this._setting.substr(index + 1) : void 0; + let enabled = rest ? vscode_1.workspace.getConfiguration(primary).get(rest, false) : vscode_1.workspace.getConfiguration(primary); + if (enabled && this._client.needsStart()) { + this._client.start().catch((error) => this._client.error("Start failed after configuration change", error, "force")); + } else if (!enabled && this._client.needsStop()) { + void this._client.stop().catch((error) => this._client.error("Stop failed after configuration change", error, "force")); + } + } + }; + exports2.SettingMonitor = SettingMonitor; + function handleChildProcessStartError(process2, message) { + if (process2 === null) { + return Promise.reject(message); + } + return new Promise((_, reject) => { + process2.on("error", (err) => { + reject(`${message} ${err}`); + }); + setImmediate(() => reject(message)); + }); + } } }); -// src/toolchain/doctor.ts -var doctor_exports = {}; -__export(doctor_exports, { - parseDoctorOutput: () => parseDoctorOutput, - runDoctor: () => runDoctor -}); -function parseDoctorOutput(stdout) { - const checks = []; - const lines = stdout.split(/\r?\n/); - for (const line of lines) { - const match = line.match(CHECK_PATTERN); - if (match) { - checks.push({ - status: STATUS_MAP[match[1]], - name: match[2].trim(), - message: match[3].trim() - }); - } - } - let summary = ""; - for (let i = lines.length - 1; i >= 0; i--) { - const trimmed = lines[i].trim(); - if (trimmed.length > 0 && !CHECK_PATTERN.test(lines[i])) { - summary = trimmed; - break; - } - } - return { - checks, - hasErrors: checks.some((c) => c.status === "fail"), - hasWarnings: checks.some((c) => c.status === "warn"), - summary - }; -} -async function runDoctor(infsPath) { - try { - const binDir = path4.join(inferenceHome(), "bin"); - const sep = process.platform === "win32" ? ";" : ":"; - const augmentedPath = `${binDir}${sep}${process.env["PATH"] ?? ""}`; - const result = await exec(infsPath, ["doctor"], { - env: { PATH: augmentedPath } - }); - return parseDoctorOutput(result.stdout); - } catch (err) { - console.error("infs doctor failed:", err); - return null; - } -} -var path4, STATUS_MAP, CHECK_PATTERN; -var init_doctor = __esm({ - "src/toolchain/doctor.ts"() { +// node_modules/vscode-languageclient/node.js +var require_node3 = __commonJS({ + "node_modules/vscode-languageclient/node.js"(exports2, module2) { "use strict"; - path4 = __toESM(require("path")); - init_exec(); - init_home(); - STATUS_MAP = { - OK: "ok", - WARN: "warn", - FAIL: "fail" - }; - CHECK_PATTERN = /^\s+\[(OK|WARN|FAIL)]\s+(.+?):\s+(.*)/; + module2.exports = require_main4(); } }); @@ -148,8 +18241,8 @@ __export(extension_exports, { deactivate: () => deactivate }); module.exports = __toCommonJS(extension_exports); -var vscode10 = __toESM(require("vscode")); -var path6 = __toESM(require("path")); +var vscode11 = __toESM(require("vscode")); +var path7 = __toESM(require("path")); // src/toolchain/platform.ts var os = __toESM(require("os")); @@ -182,7 +18275,9 @@ function getSettings() { return { path: config.get("path", ""), autoInstall: config.get("autoInstall", true), - checkForUpdates: config.get("checkForUpdates", true) + checkForUpdates: config.get("checkForUpdates", true), + lspEnabled: config.get("lsp.enabled", true), + lspPath: config.get("lsp.path", "") }; } @@ -290,7 +18385,7 @@ function compareSemver(a, b) { } // src/commands/install.ts -var vscode3 = __toESM(require("vscode")); +var vscode4 = __toESM(require("vscode")); // src/toolchain/installation.ts var fs4 = __toESM(require("fs")); @@ -789,21 +18884,200 @@ function updateStatusBar(item, result) { item.backgroundColor = BACKGROUND_MAP[state.background]; } +// src/lsp/client.ts +var vscode3 = __toESM(require("vscode")); +var import_node = __toESM(require_node3()); +init_home(); + +// src/lsp/resolve.ts +var path6 = __toESM(require("path")); +function lspBinaryName(isWindows) { + return isWindows ? "inference-lsp.exe" : "inference-lsp"; +} +function resolveLspBinary(options) { + if (options.configuredPath) { + if (options.isExecutable(options.configuredPath)) { + return { path: options.configuredPath, source: "settings" }; + } + return null; + } + const binaryName = lspBinaryName(options.isWindows); + const managedPath = path6.join(options.inferenceHome, "bin", binaryName); + if (options.isExecutable(managedPath)) { + return { path: managedPath, source: "managed" }; + } + const sep = options.isWindows ? ";" : ":"; + const dirs = options.envPath.split(sep).filter(Boolean); + for (const dir of dirs) { + const candidate = path6.join(dir, binaryName); + if (options.isExecutable(candidate)) { + return { path: candidate, source: "path" }; + } + } + return null; +} +function lspActionForConfigChange(change) { + if (!change.affectsLsp) { + return "none"; + } + if (!change.enabled) { + return change.running ? "stop" : "none"; + } + return "restart"; +} + +// src/lsp/client.ts +var mainChannel; +var serverChannel; +var client; +var queue = Promise.resolve(); +function enqueue(operation) { + const next = queue.then(operation); + queue = next.catch(() => void 0); + return next; +} +function initializeLspClient(context, outputChannel2) { + mainChannel = outputChannel2; + serverChannel = vscode3.window.createOutputChannel( + "Inference Language Server", + { log: true } + ); + context.subscriptions.push(serverChannel); + context.subscriptions.push( + new vscode3.Disposable(() => { + void stopLspClient(); + }) + ); +} +function isLspRunning() { + return client !== void 0; +} +function startLspClient() { + return enqueue(() => doStart()); +} +function stopLspClient() { + return enqueue(() => doStop()); +} +function restartLspClient() { + return enqueue(async () => { + await doStop(); + await doStart(); + }); +} +function ensureLspStarted() { + return enqueue(async () => { + if (client) { + return; + } + await doStart(); + }).catch((err) => { + mainChannel?.error(`Language server start failed: ${err}`); + }); +} +function handleLspConfigChange(event) { + const action = lspActionForConfigChange({ + affectsLsp: event.affectsConfiguration("inference.lsp"), + enabled: getSettings().lspEnabled, + running: isLspRunning() + }); + switch (action) { + case "restart": + return restartLspClient(); + case "stop": + return stopLspClient(); + case "none": + return Promise.resolve(); + } +} +async function doStart() { + if (client) { + return; + } + const settings = getSettings(); + if (!settings.lspEnabled) { + mainChannel?.info( + "Language server disabled (inference.lsp.enabled is false)." + ); + return; + } + const resolution = resolveLspBinary({ + configuredPath: settings.lspPath, + inferenceHome: inferenceHome(), + isWindows: process.platform === "win32", + envPath: process.env["PATH"] || "", + isExecutable + }); + if (!resolution) { + if (settings.lspPath) { + mainChannel?.warn( + `Language server not started: inference.lsp.path is set to ${settings.lspPath} but it is not executable.` + ); + } else { + mainChannel?.info( + `Language server not started: inference-lsp not found (searched ${inferenceHome()}/bin and PATH). Install or update the toolchain to enable it.` + ); + } + return; + } + const serverOptions = { + command: resolution.path, + transport: import_node.TransportKind.stdio + }; + const clientOptions = { + documentSelector: [{ scheme: "file", language: "inference" }], + outputChannel: serverChannel + }; + const candidate = new import_node.LanguageClient( + "inference-lsp", + "Inference Language Server", + serverOptions, + clientOptions + ); + try { + await candidate.start(); + } catch (err) { + mainChannel?.error( + `Language server failed to start (${resolution.path}): ${err}` + ); + await candidate.dispose().catch(() => void 0); + return; + } + client = candidate; + mainChannel?.info( + `Language server started: ${resolution.path} (${resolution.source})` + ); +} +async function doStop() { + if (!client) { + return; + } + const stopping = client; + client = void 0; + try { + await stopping.stop(); + mainChannel?.info("Language server stopped."); + } catch (err) { + mainChannel?.warn(`Language server stop failed: ${err}`); + } finally { + await stopping.dispose().catch(() => void 0); + } +} + // src/commands/install.ts var installing = false; function registerInstallCommand(outputChannel2, statusBarItem) { - return vscode3.commands.registerCommand( + return vscode4.commands.registerCommand( "inference.installToolchain", async () => { if (installing) { - vscode3.window.showInformationMessage( + vscode4.window.showInformationMessage( "Inference toolchain installation is already in progress." ); return; } const platform2 = detectPlatform(); if (!platform2) { - vscode3.window.showErrorMessage( + vscode4.window.showErrorMessage( `Inference: unsupported platform (${process.platform}-${process.arch}).` ); return; @@ -817,15 +19091,16 @@ function registerInstallCommand(outputChannel2, statusBarItem) { outputChannel2.appendLine( `Toolchain v${result.version} installed at ${result.infsPath}` ); - vscode3.commands.executeCommand( + vscode4.commands.executeCommand( "setContext", "inference.toolchainInstalled", true ); const doctorResult = await runDoctor(result.infsPath); updateStatusBar(statusBarItem, doctorResult); - vscode3.commands.executeCommand("inference.refreshConfigView"); - vscode3.commands.executeCommand("inference.applyTerminalPath"); + vscode4.commands.executeCommand("inference.refreshConfigView"); + vscode4.commands.executeCommand("inference.applyTerminalPath"); + void ensureLspStarted(); notifyInstallSuccess(result.version, result.doctorWarnings); } catch (err) { const message = err instanceof Error ? err.message : String(err); @@ -838,9 +19113,9 @@ function registerInstallCommand(outputChannel2, statusBarItem) { ); } function installWithProgress(platform2, outputChannel2) { - return vscode3.window.withProgress( + return vscode4.window.withProgress( { - location: vscode3.ProgressLocation.Notification, + location: vscode4.ProgressLocation.Notification, title: "Inference Toolchain", cancellable: false }, @@ -862,37 +19137,37 @@ function installWithProgress(platform2, outputChannel2) { } function notifyInstallSuccess(version, doctorWarnings) { if (doctorWarnings) { - vscode3.window.showWarningMessage( + vscode4.window.showWarningMessage( `Inference toolchain v${version} installed, but doctor reported issues. See output for details.`, "Show Output" ).then((action) => { if (action === "Show Output") { - vscode3.commands.executeCommand("inference.showOutput"); + vscode4.commands.executeCommand("inference.showOutput"); } }); } else { - vscode3.window.showInformationMessage( + vscode4.window.showInformationMessage( `Inference toolchain v${version} installed successfully.` ); } } function notifyInstallError(errorMessage) { - vscode3.window.showErrorMessage( + vscode4.window.showErrorMessage( `Inference toolchain installation failed: ${errorMessage}`, "Retry", "Download Manually", "Settings" ).then((action) => { if (action === "Retry") { - vscode3.commands.executeCommand("inference.installToolchain"); + vscode4.commands.executeCommand("inference.installToolchain"); } else if (action === "Download Manually") { - vscode3.env.openExternal( - vscode3.Uri.parse( + vscode4.env.openExternal( + vscode4.Uri.parse( "https://github.com/Inferara/inference/releases" ) ); } else if (action === "Settings") { - vscode3.commands.executeCommand( + vscode4.commands.executeCommand( "workbench.action.openSettings", "inference.path" ); @@ -901,7 +19176,7 @@ function notifyInstallError(errorMessage) { } // src/commands/installComponent.ts -var vscode4 = __toESM(require("vscode")); +var vscode5 = __toESM(require("vscode")); init_exec(); // src/toolchain/components.ts @@ -919,29 +19194,29 @@ function wasmOptNeedsAttention(result) { var installing2 = false; var INSTALL_TIMEOUT_MS = 6e5; function registerInstallComponentCommand(outputChannel2) { - return vscode4.commands.registerCommand( + return vscode5.commands.registerCommand( "inference.installComponent", async (component = "wasm-opt") => { if (installing2) { - vscode4.window.showInformationMessage( + vscode5.window.showInformationMessage( "Inference component installation is already in progress." ); return; } if (!isKnownComponent(component)) { - vscode4.window.showErrorMessage( + vscode5.window.showErrorMessage( `Inference: unknown component '${component}'.` ); return; } const detection = detectInfs(); if (!detection) { - vscode4.window.showWarningMessage( + vscode5.window.showWarningMessage( "Inference toolchain not found. Install it first.", "Install" ).then((action) => { if (action === "Install") { - vscode4.commands.executeCommand( + vscode5.commands.executeCommand( "inference.installToolchain" ); } @@ -962,10 +19237,10 @@ function registerInstallComponentCommand(outputChannel2) { outputChannel2.appendLine(result.stderr); } if (result.exitCode === 0) { - vscode4.window.showInformationMessage( + vscode5.window.showInformationMessage( `Inference: component '${component}' installed.` ); - vscode4.commands.executeCommand("inference.runDoctor"); + vscode5.commands.executeCommand("inference.runDoctor"); } else { notifyInstallError2(component); } @@ -985,9 +19260,9 @@ function isKnownComponent(name) { return KNOWN_COMPONENTS.includes(name); } function installWithProgress2(infsPath, component, outputChannel2) { - return vscode4.window.withProgress( + return vscode5.window.withProgress( { - location: vscode4.ProgressLocation.Notification, + location: vscode5.ProgressLocation.Notification, title: "Inference Component", cancellable: false }, @@ -1001,15 +19276,15 @@ function installWithProgress2(infsPath, component, outputChannel2) { ); } function notifyInstallError2(component) { - vscode4.window.showErrorMessage( + vscode5.window.showErrorMessage( `Inference: failed to install component '${component}'. See output for details.`, "Show Output", "Retry" ).then((action) => { if (action === "Show Output") { - vscode4.commands.executeCommand("inference.showOutput"); + vscode5.commands.executeCommand("inference.showOutput"); } else if (action === "Retry") { - vscode4.commands.executeCommand( + vscode5.commands.executeCommand( "inference.installComponent", component ); @@ -1018,7 +19293,7 @@ function notifyInstallError2(component) { } // src/commands/doctor.ts -var vscode5 = __toESM(require("vscode")); +var vscode6 = __toESM(require("vscode")); init_doctor(); // src/toolchain/doctorFormat.ts @@ -1045,7 +19320,7 @@ function formatDoctorChecks(result) { // src/commands/doctor.ts var running = false; function registerDoctorCommand(outputChannel2, statusBarItem) { - return vscode5.commands.registerCommand( + return vscode6.commands.registerCommand( "inference.runDoctor", async () => { if (running) { @@ -1055,12 +19330,12 @@ function registerDoctorCommand(outputChannel2, statusBarItem) { if (!detection) { outputChannel2.appendLine("Doctor: infs binary not found."); updateStatusBar(statusBarItem, null); - vscode5.window.showWarningMessage( + vscode6.window.showWarningMessage( "Inference toolchain not found. Install it first.", "Install" ).then((action) => { if (action === "Install") { - vscode5.commands.executeCommand( + vscode6.commands.executeCommand( "inference.installToolchain" ); } @@ -1078,7 +19353,7 @@ function registerDoctorCommand(outputChannel2, statusBarItem) { "Doctor: failed to execute infs doctor." ); updateStatusBar(statusBarItem, null); - vscode5.window.showErrorMessage( + vscode6.window.showErrorMessage( "Inference: Failed to run doctor. See output for details." ); return; @@ -1087,20 +19362,20 @@ function registerDoctorCommand(outputChannel2, statusBarItem) { outputChannel2.appendLine(line); } updateStatusBar(statusBarItem, result); - vscode5.commands.executeCommand("inference.refreshConfigView"); + vscode6.commands.executeCommand("inference.refreshConfigView"); if (result.hasErrors) { const actions = ["Show Output"]; if (wasmOptNeedsAttention(result)) { actions.push("Install wasm-opt"); } - vscode5.window.showErrorMessage( + vscode6.window.showErrorMessage( `Inference doctor: ${result.summary}`, ...actions ).then((action) => { if (action === "Show Output") { outputChannel2.show(); } else if (action === "Install wasm-opt") { - vscode5.commands.executeCommand( + vscode6.commands.executeCommand( "inference.installComponent", "wasm-opt" ); @@ -1111,21 +19386,21 @@ function registerDoctorCommand(outputChannel2, statusBarItem) { if (wasmOptNeedsAttention(result)) { actions.push("Install wasm-opt"); } - vscode5.window.showWarningMessage( + vscode6.window.showWarningMessage( `Inference doctor: ${result.summary}`, ...actions ).then((action) => { if (action === "Show Output") { outputChannel2.show(); } else if (action === "Install wasm-opt") { - vscode5.commands.executeCommand( + vscode6.commands.executeCommand( "inference.installComponent", "wasm-opt" ); } }); } else { - vscode5.window.showInformationMessage( + vscode6.window.showInformationMessage( "Inference: Toolchain is healthy." ); } @@ -1137,7 +19412,7 @@ function registerDoctorCommand(outputChannel2, statusBarItem) { } // src/commands/selectVersion.ts -var vscode7 = __toESM(require("vscode")); +var vscode8 = __toESM(require("vscode")); // src/toolchain/versions.ts init_exec(); @@ -1227,11 +19502,11 @@ function buildVersionPickItems(versions, currentVersion) { } // src/commands/versionChange.ts -var vscode6 = __toESM(require("vscode")); +var vscode7 = __toESM(require("vscode")); async function performVersionChange(infsPath, version, outputChannel2, actionVerb) { - await vscode6.window.withProgress( + await vscode7.window.withProgress( { - location: vscode6.ProgressLocation.Notification, + location: vscode7.ProgressLocation.Notification, title: "Inference Toolchain", cancellable: false }, @@ -1243,14 +19518,15 @@ async function performVersionChange(infsPath, version, outputChannel2, actionVer outputChannel2.appendLine( `${actionVerb} toolchain v${version} complete.` ); - vscode6.commands.executeCommand( + vscode7.commands.executeCommand( "setContext", "inference.toolchainInstalled", true ); - vscode6.commands.executeCommand("inference.applyTerminalPath"); - vscode6.commands.executeCommand("inference.runDoctor"); - vscode6.window.showInformationMessage( + vscode7.commands.executeCommand("inference.applyTerminalPath"); + vscode7.commands.executeCommand("inference.runDoctor"); + void ensureLspStarted(); + vscode7.window.showInformationMessage( `Inference toolchain ${actionVerb.toLowerCase()} to v${version}.`, "Show Output" ).then((action) => { @@ -1264,7 +19540,7 @@ async function performVersionChange(infsPath, version, outputChannel2, actionVer `${actionVerb} failed: ${result.error}` ); if (result.installedButNotDefault) { - vscode6.window.showWarningMessage( + vscode7.window.showWarningMessage( `Inference: v${version} was installed but could not be set as default. Run \`infs default ${version}\` manually.`, "Show Output" ).then((action) => { @@ -1273,7 +19549,7 @@ async function performVersionChange(infsPath, version, outputChannel2, actionVer } }); } else { - vscode6.window.showErrorMessage( + vscode7.window.showErrorMessage( `Inference: Failed to install v${version}: ${result.error}` ); } @@ -1284,23 +19560,23 @@ async function performVersionChange(infsPath, version, outputChannel2, actionVer // src/commands/selectVersion.ts var selecting = false; function registerSelectVersionCommand(outputChannel2) { - return vscode7.commands.registerCommand( + return vscode8.commands.registerCommand( "inference.selectVersion", async () => { if (selecting) { - vscode7.window.showInformationMessage( + vscode8.window.showInformationMessage( "Version selection is already in progress." ); return; } const detection = detectInfs(); if (!detection) { - vscode7.window.showWarningMessage( + vscode8.window.showWarningMessage( "Inference toolchain not found. Install it first.", "Install" ).then((action) => { if (action === "Install") { - vscode7.commands.executeCommand( + vscode8.commands.executeCommand( "inference.installToolchain" ); } @@ -1311,7 +19587,7 @@ function registerSelectVersionCommand(outputChannel2) { try { const versions = await fetchVersions(detection.path); if (!versions) { - vscode7.window.showErrorMessage( + vscode8.window.showErrorMessage( "Inference: Failed to fetch available versions." ); return; @@ -1319,12 +19595,12 @@ function registerSelectVersionCommand(outputChannel2) { const currentVersion = await getCurrentVersion(detection.path); const items = buildVersionPickItems(versions, currentVersion); if (items.length === 0) { - vscode7.window.showInformationMessage( + vscode8.window.showInformationMessage( "No toolchain versions available for this platform." ); return; } - const picked = await vscode7.window.showQuickPick(items, { + const picked = await vscode8.window.showQuickPick(items, { placeHolder: "Select toolchain version", matchOnDescription: true }); @@ -1333,7 +19609,7 @@ function registerSelectVersionCommand(outputChannel2) { } const selectedVersion = picked.label; if (selectedVersion === currentVersion) { - vscode7.window.showInformationMessage( + vscode8.window.showInformationMessage( `Already using toolchain v${selectedVersion}.` ); return; @@ -1347,7 +19623,7 @@ function registerSelectVersionCommand(outputChannel2) { } // src/commands/update.ts -var vscode8 = __toESM(require("vscode")); +var vscode9 = __toESM(require("vscode")); // src/toolchain/updateCheck.ts function checkUpdateAvailable(currentVersion, versions) { @@ -1378,23 +19654,23 @@ function checkUpdateAvailable(currentVersion, versions) { // src/commands/update.ts var updating = false; function registerUpdateCommand(outputChannel2) { - return vscode8.commands.registerCommand( + return vscode9.commands.registerCommand( "inference.updateToolchain", async () => { if (updating) { - vscode8.window.showInformationMessage( + vscode9.window.showInformationMessage( "Update check is already in progress." ); return; } const detection = detectInfs(); if (!detection) { - vscode8.window.showWarningMessage( + vscode9.window.showWarningMessage( "Inference toolchain not found. Install it first.", "Install" ).then((action) => { if (action === "Install") { - vscode8.commands.executeCommand( + vscode9.commands.executeCommand( "inference.installToolchain" ); } @@ -1430,7 +19706,7 @@ async function checkForUpdatesImpl(infsPath, outputChannel2, userInitiated) { if (!currentVersion) { outputChannel2.appendLine("Update check: could not determine current version."); if (userInitiated) { - vscode8.window.showErrorMessage( + vscode9.window.showErrorMessage( "Inference: Could not determine the current toolchain version." ); } @@ -1441,7 +19717,7 @@ async function checkForUpdatesImpl(infsPath, outputChannel2, userInitiated) { if (!versions) { outputChannel2.appendLine("Update check: failed to fetch available versions."); if (userInitiated) { - vscode8.window.showErrorMessage( + vscode9.window.showErrorMessage( "Inference: Failed to check for updates." ); } @@ -1452,7 +19728,7 @@ async function checkForUpdatesImpl(infsPath, outputChannel2, userInitiated) { case "no-current-version": outputChannel2.appendLine("Update check: could not determine current version."); if (userInitiated) { - vscode8.window.showErrorMessage( + vscode9.window.showErrorMessage( "Inference: Could not determine the current toolchain version." ); } @@ -1460,7 +19736,7 @@ async function checkForUpdatesImpl(infsPath, outputChannel2, userInitiated) { case "no-versions": outputChannel2.appendLine("Update check: no versions available for this platform."); if (userInitiated) { - vscode8.window.showInformationMessage( + vscode9.window.showInformationMessage( "Inference: No toolchain versions available for this platform." ); } @@ -1470,7 +19746,7 @@ async function checkForUpdatesImpl(infsPath, outputChannel2, userInitiated) { `Update check: toolchain is up to date (v${result.version}).` ); if (userInitiated) { - vscode8.window.showInformationMessage( + vscode9.window.showInformationMessage( `Inference toolchain is up to date (v${result.version}).` ); } @@ -1479,7 +19755,7 @@ async function checkForUpdatesImpl(infsPath, outputChannel2, userInitiated) { outputChannel2.appendLine( `Update check: v${result.latest} available (current: v${result.current}).` ); - const action = await vscode8.window.showInformationMessage( + const action = await vscode9.window.showInformationMessage( `Inference toolchain update available: v${result.latest} (current: v${result.current})`, "Update", "Release Notes" @@ -1487,8 +19763,8 @@ async function checkForUpdatesImpl(infsPath, outputChannel2, userInitiated) { if (action === "Update") { await performVersionChange(infsPath, result.latest, outputChannel2, "Updating to"); } else if (action === "Release Notes") { - vscode8.env.openExternal( - vscode8.Uri.parse( + vscode9.env.openExternal( + vscode9.Uri.parse( `https://github.com/Inferara/inference/releases/tag/v${result.latest}` ) ); @@ -1499,10 +19775,10 @@ async function checkForUpdatesImpl(infsPath, outputChannel2, userInitiated) { } // src/ui/configTree.ts -var vscode9 = __toESM(require("vscode")); +var vscode10 = __toESM(require("vscode")); init_home(); init_exec(); -var ConfigItem = class extends vscode9.TreeItem { +var ConfigItem = class extends vscode10.TreeItem { constructor(label, kind, collapsible, groupId, settingKey, copyValue) { super(label, collapsible); this.kind = kind; @@ -1510,7 +19786,7 @@ var ConfigItem = class extends vscode9.TreeItem { this.settingKey = settingKey; this.copyValue = copyValue; if (kind === "group") { - this.iconPath = new vscode9.ThemeIcon( + this.iconPath = new vscode10.ThemeIcon( groupId === "toolchain" ? "tools" : "gear" ); } @@ -1531,7 +19807,7 @@ var ConfigItem = class extends vscode9.TreeItem { copyValue; }; var InferenceConfigProvider = class { - _onDidChangeTreeData = new vscode9.EventEmitter(); + _onDidChangeTreeData = new vscode10.EventEmitter(); onDidChangeTreeData = this._onDidChangeTreeData.event; detection = null; version = null; @@ -1554,13 +19830,13 @@ var InferenceConfigProvider = class { new ConfigItem( "Toolchain", "group", - vscode9.TreeItemCollapsibleState.Expanded, + vscode10.TreeItemCollapsibleState.Expanded, "toolchain" ), new ConfigItem( "Settings", "group", - vscode9.TreeItemCollapsibleState.Expanded, + vscode10.TreeItemCollapsibleState.Expanded, "settings" ) ]; @@ -1580,9 +19856,9 @@ var InferenceConfigProvider = class { const item = new ConfigItem( "infs: not found", "property", - vscode9.TreeItemCollapsibleState.None + vscode10.TreeItemCollapsibleState.None ); - item.iconPath = new vscode9.ThemeIcon("error"); + item.iconPath = new vscode10.ThemeIcon("error"); item.command = { title: "Install Toolchain", command: "inference.installToolchain", @@ -1594,49 +19870,49 @@ var InferenceConfigProvider = class { const infsItem = new ConfigItem( `infs: ${detection.path} (${detection.source})`, "property", - vscode9.TreeItemCollapsibleState.None, + vscode10.TreeItemCollapsibleState.None, void 0, void 0, detection.path ); - infsItem.iconPath = new vscode9.ThemeIcon("file-binary"); + infsItem.iconPath = new vscode10.ThemeIcon("file-binary"); items.push(infsItem); const version = await this.resolveVersion(detection.path); const versionItem = new ConfigItem( `Version: ${version ?? "unknown"}`, "property", - vscode9.TreeItemCollapsibleState.None + vscode10.TreeItemCollapsibleState.None ); - versionItem.iconPath = new vscode9.ThemeIcon("tag"); + versionItem.iconPath = new vscode10.ThemeIcon("tag"); items.push(versionItem); const home = inferenceHome(); const homeIsDefault = !process.env["INFERENCE_HOME"]; const homeItem = new ConfigItem( `Home: ${home} (${homeIsDefault ? "default" : "env"})`, "property", - vscode9.TreeItemCollapsibleState.None, + vscode10.TreeItemCollapsibleState.None, void 0, void 0, home ); - homeItem.iconPath = new vscode9.ThemeIcon("home"); + homeItem.iconPath = new vscode10.ThemeIcon("home"); items.push(homeItem); const platform2 = detectPlatform(); const platformItem = new ConfigItem( `Platform: ${platform2?.id ?? "unknown"}`, "property", - vscode9.TreeItemCollapsibleState.None + vscode10.TreeItemCollapsibleState.None ); - platformItem.iconPath = new vscode9.ThemeIcon("device-desktop"); + platformItem.iconPath = new vscode10.ThemeIcon("device-desktop"); items.push(platformItem); const status = this.doctorResult ? this.doctorResult.hasErrors ? "errors" : this.doctorResult.hasWarnings ? "warnings" : "healthy" : "unknown"; const statusIcon = this.doctorResult ? this.doctorResult.hasErrors ? "error" : this.doctorResult.hasWarnings ? "warning" : "pass" : "question"; const statusItem = new ConfigItem( `Status: ${status}`, "property", - vscode9.TreeItemCollapsibleState.None + vscode10.TreeItemCollapsibleState.None ); - statusItem.iconPath = new vscode9.ThemeIcon(statusIcon); + statusItem.iconPath = new vscode10.ThemeIcon(statusIcon); statusItem.command = { title: "Run Doctor", command: "inference.runDoctor", @@ -1650,27 +19926,27 @@ var InferenceConfigProvider = class { const pathItem = new ConfigItem( `Path: ${settings.path || "(auto-detect)"}`, "property", - vscode9.TreeItemCollapsibleState.None, + vscode10.TreeItemCollapsibleState.None, void 0, "inference.path" ); - pathItem.iconPath = new vscode9.ThemeIcon("file-symlink-directory"); + pathItem.iconPath = new vscode10.ThemeIcon("file-symlink-directory"); const autoInstallItem = new ConfigItem( `Auto Install: ${settings.autoInstall ? "enabled" : "disabled"}`, "property", - vscode9.TreeItemCollapsibleState.None, + vscode10.TreeItemCollapsibleState.None, void 0, "inference.autoInstall" ); - autoInstallItem.iconPath = new vscode9.ThemeIcon("cloud-download"); + autoInstallItem.iconPath = new vscode10.ThemeIcon("cloud-download"); const updateItem = new ConfigItem( `Check for Updates: ${settings.checkForUpdates ? "enabled" : "disabled"}`, "property", - vscode9.TreeItemCollapsibleState.None, + vscode10.TreeItemCollapsibleState.None, void 0, "inference.checkForUpdates" ); - updateItem.iconPath = new vscode9.ThemeIcon("sync"); + updateItem.iconPath = new vscode10.ThemeIcon("sync"); return [pathItem, autoInstallItem, updateItem]; } async resolveVersion(infsPath) { @@ -1700,13 +19976,13 @@ var InferenceConfigProvider = class { // src/extension.ts init_doctor(); var MIN_INFS_VERSION = "0.0.1-beta.1"; -var outputChannel = vscode10.window.createOutputChannel("Inference", { log: true }); +var outputChannel = vscode11.window.createOutputChannel("Inference", { log: true }); function activate(context) { context.subscriptions.push(outputChannel); const statusBarItem = createStatusBar(); context.subscriptions.push(statusBarItem); context.subscriptions.push( - vscode10.commands.registerCommand("inference.showOutput", () => { + vscode11.commands.registerCommand("inference.showOutput", () => { outputChannel.show(); }) ); @@ -1718,28 +19994,28 @@ function activate(context) { context.subscriptions.push(registerUpdateCommand(outputChannel)); context.subscriptions.push(registerSelectVersionCommand(outputChannel)); const configProvider = new InferenceConfigProvider(); - const configView = vscode10.window.createTreeView("inference.configView", { + const configView = vscode11.window.createTreeView("inference.configView", { treeDataProvider: configProvider }); context.subscriptions.push(configView); context.subscriptions.push(configProvider); context.subscriptions.push( - vscode10.commands.registerCommand("inference.refreshConfigView", () => { + vscode11.commands.registerCommand("inference.refreshConfigView", () => { configProvider.refresh(); }) ); context.subscriptions.push( - vscode10.commands.registerCommand("inference.applyTerminalPath", () => { + vscode11.commands.registerCommand("inference.applyTerminalPath", () => { applyTerminalPath(context); }) ); context.subscriptions.push( - vscode10.commands.registerCommand( + vscode11.commands.registerCommand( "inference.copyConfigValue", (item) => { if (item.copyValue) { - vscode10.env.clipboard.writeText(item.copyValue); - vscode10.window.showInformationMessage( + vscode11.env.clipboard.writeText(item.copyValue); + vscode11.window.showInformationMessage( `Copied: ${item.copyValue}` ); } @@ -1747,44 +20023,59 @@ function activate(context) { ) ); context.subscriptions.push( - vscode10.commands.registerCommand( + vscode11.commands.registerCommand( "inference.revealConfigPath", (item) => { if (item.copyValue) { - vscode10.commands.executeCommand( + vscode11.commands.executeCommand( "revealFileInOS", - vscode10.Uri.file(item.copyValue) + vscode11.Uri.file(item.copyValue) ); } } ) ); context.subscriptions.push( - vscode10.workspace.onDidChangeConfiguration((e) => { + vscode11.workspace.onDidChangeConfiguration((e) => { if (e.affectsConfiguration("inference")) { configProvider.refresh(); } + handleLspConfigChange(e).catch( + (err) => outputChannel.error(`Language server reconfigure failed: ${err}`) + ); + }) + ); + context.subscriptions.push( + vscode11.commands.registerCommand("inference.restartLsp", () => { + restartLspClient().catch( + (err) => outputChannel.error(`Language server restart failed: ${err}`) + ); }) ); context.subscriptions.push( - vscode10.commands.registerCommand("inference.resetPathAcceptance", () => { + vscode11.commands.registerCommand("inference.resetPathAcceptance", () => { const home = inferenceHome(); const stateKey = `${PATH_FALLBACK_KEY}:${home}`; context.globalState.update(stateKey, void 0); - vscode10.window.showInformationMessage( + vscode11.window.showInformationMessage( "Inference: PATH fallback preference has been reset." ); }) ); applyTerminalPath(context); + initializeLspClient(context, outputChannel); + startLspClient().catch( + (err) => outputChannel.error(`Language server start failed: ${err}`) + ); checkToolchain(context, statusBarItem, configProvider).catch( (err) => outputChannel.error(`Toolchain check failed: ${err}`) ); } function deactivate() { + return stopLspClient(); } function applyTerminalPath(context) { - const binDir = path6.join(inferenceHome(), "bin"); + const binDir = path7.join(inferenceHome(), "bin"); const sep = process.platform === "win32" ? ";" : ":"; const env4 = context.environmentVariableCollection; env4.prepend("PATH", binDir + sep); @@ -1808,14 +20099,14 @@ async function checkToolchain(context, statusBarItem, configProvider) { `INFS_DIST_SERVER: ${distServer ?? "(not set, using production)"}` ); updateStatusBar(statusBarItem, null); - vscode10.commands.executeCommand("setContext", "inference.toolchainInstalled", false); - vscode10.window.showWarningMessage( + vscode11.commands.executeCommand("setContext", "inference.toolchainInstalled", false); + vscode11.window.showWarningMessage( `Inference: unsupported platform (${process.platform}-${process.arch}).`, "Download Page" ).then((action) => { if (action === "Download Page") { - vscode10.env.openExternal( - vscode10.Uri.parse( + vscode11.env.openExternal( + vscode11.Uri.parse( "https://github.com/Inferara/inference/releases" ) ); @@ -1835,7 +20126,7 @@ async function checkToolchain(context, statusBarItem, configProvider) { outputChannel.error("infs binary: not found"); outputChannel.error("Toolchain status: errors"); updateStatusBar(statusBarItem, null); - vscode10.commands.executeCommand("setContext", "inference.toolchainInstalled", false); + vscode11.commands.executeCommand("setContext", "inference.toolchainInstalled", false); notifyMissing(); return; } @@ -1857,13 +20148,13 @@ async function checkToolchain(context, statusBarItem, configProvider) { outputChannel.warn( `INFERENCE_HOME is set to ${home} but infs was not found there. Using binary from PATH instead.` ); - vscode10.window.showWarningMessage( + vscode11.window.showWarningMessage( `Inference: infs binary not found in INFERENCE_HOME (${home}). Found via PATH instead.`, "Install", "Dismiss" ).then((action) => { if (action === "Install") { - vscode10.commands.executeCommand("inference.installToolchain"); + vscode11.commands.executeCommand("inference.installToolchain"); } else { context.globalState.update(stateKey, "*"); } @@ -1874,10 +20165,10 @@ async function checkToolchain(context, statusBarItem, configProvider) { if (!versionOk) { outputChannel.error("Toolchain status: errors"); updateStatusBar(statusBarItem, null); - vscode10.commands.executeCommand("setContext", "inference.toolchainInstalled", false); + vscode11.commands.executeCommand("setContext", "inference.toolchainInstalled", false); return; } - vscode10.commands.executeCommand("setContext", "inference.toolchainInstalled", true); + vscode11.commands.executeCommand("setContext", "inference.toolchainInstalled", true); const doctorResult = await runDoctor(detection.path); updateStatusBar(statusBarItem, doctorResult); configProvider.refresh(detection, doctorResult); @@ -1915,12 +20206,12 @@ async function checkInfsVersion(infsPath) { outputChannel.warn( `infs version ${version} is below minimum ${MIN_INFS_VERSION}.` ); - vscode10.window.showWarningMessage( + vscode11.window.showWarningMessage( `Inference: infs version ${version} is outdated (minimum: ${MIN_INFS_VERSION}). Please update.`, "Update" ).then((action) => { if (action === "Update") { - vscode10.commands.executeCommand("inference.updateToolchain"); + vscode11.commands.executeCommand("inference.updateToolchain"); } }); return false; @@ -1932,22 +20223,22 @@ async function checkInfsVersion(infsPath) { } } function notifyMissing() { - vscode10.window.showInformationMessage( + vscode11.window.showInformationMessage( "Inference toolchain not found. Would you like to install it?", "Install", "Download Manually", "Configure Path" ).then((action) => { if (action === "Install") { - vscode10.commands.executeCommand("inference.installToolchain"); + vscode11.commands.executeCommand("inference.installToolchain"); } else if (action === "Download Manually") { - vscode10.env.openExternal( - vscode10.Uri.parse( + vscode11.env.openExternal( + vscode11.Uri.parse( "https://github.com/Inferara/inference/releases" ) ); } else if (action === "Configure Path") { - vscode10.commands.executeCommand( + vscode11.commands.executeCommand( "workbench.action.openSettings", "inference.path" ); diff --git a/editors/vscode/dist/extension.js.map b/editors/vscode/dist/extension.js.map index 230e8f0e..b3e2df71 100644 --- a/editors/vscode/dist/extension.js.map +++ b/editors/vscode/dist/extension.js.map @@ -1,7 +1,7 @@ { "version": 3, - "sources": ["../src/toolchain/home.ts", "../src/utils/exec.ts", "../src/toolchain/doctor.ts", "../src/extension.ts", "../src/toolchain/platform.ts", "../src/toolchain/detection.ts", "../src/config/settings.ts", "../src/utils/semver.ts", "../src/commands/install.ts", "../src/toolchain/installation.ts", "../src/utils/download.ts", "../src/utils/extract.ts", "../src/toolchain/manifest.ts", "../src/ui/statusBar.ts", "../src/ui/statusBarState.ts", "../src/commands/installComponent.ts", "../src/toolchain/components.ts", "../src/commands/doctor.ts", "../src/toolchain/doctorFormat.ts", "../src/commands/selectVersion.ts", "../src/toolchain/versions.ts", "../src/toolchain/versionPicker.ts", "../src/commands/versionChange.ts", "../src/commands/update.ts", "../src/toolchain/updateCheck.ts", "../src/ui/configTree.ts"], - "sourcesContent": ["import * as os from 'os';\nimport * as path from 'path';\n\n/** Resolve the INFERENCE_HOME directory (default: ~/.inference). */\nexport function inferenceHome(): string {\n return process.env['INFERENCE_HOME'] || path.join(os.homedir(), '.inference');\n}\n", "import * as cp from 'child_process';\n\nexport interface ExecResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/** Default timeout for child processes (30 seconds). */\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * Run a command and capture its output.\n *\n * Resolves with ExecResult on completion (including non-zero exit).\n * Rejects only on spawn failure or timeout.\n */\nexport function exec(\n command: string,\n args: string[],\n options?: { timeoutMs?: number; cwd?: string; env?: Record },\n): Promise {\n const timeout = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n return new Promise((resolve, reject) => {\n const child = cp.spawn(command, args, {\n cwd: options?.cwd,\n env: options?.env ? { ...process.env, ...options.env } : undefined,\n stdio: ['ignore', 'pipe', 'pipe'],\n timeout,\n });\n\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n\n child.stdout.on('data', (chunk: Buffer) => stdoutChunks.push(chunk));\n child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk));\n\n child.on('error', (err) => reject(err));\n\n child.on('close', (code) => {\n resolve({\n exitCode: code ?? 1,\n stdout: Buffer.concat(stdoutChunks).toString('utf-8'),\n stderr: Buffer.concat(stderrChunks).toString('utf-8'),\n });\n });\n });\n}\n", "import * as path from 'path';\nimport { exec } from '../utils/exec';\nimport { inferenceHome } from './home';\n\nexport type DoctorCheckStatus = 'ok' | 'warn' | 'fail';\n\nexport interface DoctorCheck {\n name: string;\n status: DoctorCheckStatus;\n message: string;\n}\n\nexport interface DoctorResult {\n checks: DoctorCheck[];\n hasErrors: boolean;\n hasWarnings: boolean;\n summary: string;\n}\n\nconst STATUS_MAP: Record = {\n OK: 'ok',\n WARN: 'warn',\n FAIL: 'fail',\n};\n\n/**\n * Check line format: ` [OK|WARN|FAIL] : `\n *\n * PATH conflict continuation lines (indented without a status prefix)\n * are intentionally not captured as individual checks.\n */\nconst CHECK_PATTERN = /^\\s+\\[(OK|WARN|FAIL)]\\s+(.+?):\\s+(.*)/;\n\n/**\n * Parse the stdout of `infs doctor` into a structured result.\n *\n * The output format is a public contract defined in\n * `apps/infs/src/commands/doctor.rs`.\n */\nexport function parseDoctorOutput(stdout: string): DoctorResult {\n const checks: DoctorCheck[] = [];\n const lines = stdout.split(/\\r?\\n/);\n\n for (const line of lines) {\n const match = line.match(CHECK_PATTERN);\n if (match) {\n checks.push({\n status: STATUS_MAP[match[1]],\n name: match[2].trim(),\n message: match[3].trim(),\n });\n }\n }\n\n let summary = '';\n for (let i = lines.length - 1; i >= 0; i--) {\n const trimmed = lines[i].trim();\n if (trimmed.length > 0 && !CHECK_PATTERN.test(lines[i])) {\n summary = trimmed;\n break;\n }\n }\n\n return {\n checks,\n hasErrors: checks.some((c) => c.status === 'fail'),\n hasWarnings: checks.some((c) => c.status === 'warn'),\n summary,\n };\n}\n\n/**\n * Execute `infs doctor` and return the parsed result.\n * Returns null if execution fails (e.g., binary not found or crash).\n */\nexport async function runDoctor(\n infsPath: string,\n): Promise {\n try {\n const binDir = path.join(inferenceHome(), 'bin');\n const sep = process.platform === 'win32' ? ';' : ':';\n const augmentedPath = `${binDir}${sep}${process.env['PATH'] ?? ''}`;\n\n const result = await exec(infsPath, ['doctor'], {\n env: { PATH: augmentedPath },\n });\n return parseDoctorOutput(result.stdout);\n } catch (err) {\n console.error('infs doctor failed:', err);\n return null;\n }\n}\n", "import * as vscode from 'vscode';\nimport * as path from 'path';\nimport { detectPlatform } from './toolchain/platform';\nimport { detectInfs, inferenceHome } from './toolchain/detection';\nimport { exec } from './utils/exec';\nimport { compareSemver } from './utils/semver';\nimport { registerInstallCommand } from './commands/install';\nimport { registerInstallComponentCommand } from './commands/installComponent';\nimport { registerDoctorCommand } from './commands/doctor';\nimport { registerSelectVersionCommand } from './commands/selectVersion';\nimport { registerUpdateCommand, checkForUpdates } from './commands/update';\nimport { createStatusBar, updateStatusBar } from './ui/statusBar';\nimport { InferenceConfigProvider, ConfigItem } from './ui/configTree';\nimport { runDoctor } from './toolchain/doctor';\n\n/** Minimum infs CLI version the extension can work with. */\nconst MIN_INFS_VERSION = '0.0.1-beta.1';\n\nconst outputChannel = vscode.window.createOutputChannel('Inference', { log: true });\n\nexport function activate(context: vscode.ExtensionContext) {\n context.subscriptions.push(outputChannel);\n\n const statusBarItem = createStatusBar();\n context.subscriptions.push(statusBarItem);\n\n context.subscriptions.push(\n vscode.commands.registerCommand('inference.showOutput', () => {\n outputChannel.show();\n }),\n );\n\n context.subscriptions.push(registerInstallCommand(outputChannel, statusBarItem));\n context.subscriptions.push(\n registerDoctorCommand(outputChannel, statusBarItem),\n );\n context.subscriptions.push(registerInstallComponentCommand(outputChannel));\n\n context.subscriptions.push(registerUpdateCommand(outputChannel));\n context.subscriptions.push(registerSelectVersionCommand(outputChannel));\n\n const configProvider = new InferenceConfigProvider();\n const configView = vscode.window.createTreeView('inference.configView', {\n treeDataProvider: configProvider,\n });\n context.subscriptions.push(configView);\n context.subscriptions.push(configProvider);\n\n context.subscriptions.push(\n vscode.commands.registerCommand('inference.refreshConfigView', () => {\n configProvider.refresh();\n }),\n );\n\n context.subscriptions.push(\n vscode.commands.registerCommand('inference.applyTerminalPath', () => {\n applyTerminalPath(context);\n }),\n );\n\n context.subscriptions.push(\n vscode.commands.registerCommand(\n 'inference.copyConfigValue',\n (item: ConfigItem) => {\n if (item.copyValue) {\n vscode.env.clipboard.writeText(item.copyValue);\n vscode.window.showInformationMessage(\n `Copied: ${item.copyValue}`,\n );\n }\n },\n ),\n );\n\n context.subscriptions.push(\n vscode.commands.registerCommand(\n 'inference.revealConfigPath',\n (item: ConfigItem) => {\n if (item.copyValue) {\n vscode.commands.executeCommand(\n 'revealFileInOS',\n vscode.Uri.file(item.copyValue),\n );\n }\n },\n ),\n );\n\n context.subscriptions.push(\n vscode.workspace.onDidChangeConfiguration((e) => {\n if (e.affectsConfiguration('inference')) {\n configProvider.refresh();\n }\n }),\n );\n\n context.subscriptions.push(\n vscode.commands.registerCommand('inference.resetPathAcceptance', () => {\n const home = inferenceHome();\n const stateKey = `${PATH_FALLBACK_KEY}:${home}`;\n context.globalState.update(stateKey, undefined);\n vscode.window.showInformationMessage(\n 'Inference: PATH fallback preference has been reset.',\n );\n }),\n );\n\n applyTerminalPath(context);\n\n checkToolchain(context, statusBarItem, configProvider).catch((err) =>\n outputChannel.error(`Toolchain check failed: ${err}`),\n );\n}\n\nexport function deactivate() {\n // Nothing to clean up\n}\n\n/**\n * Prepend `INFERENCE_HOME/bin` to PATH for all integrated terminals.\n *\n * Uses VS Code's `EnvironmentVariableCollection` so that:\n * - New terminals automatically have the toolchain on PATH.\n * - Existing terminals show a relaunch indicator when the collection changes.\n *\n * Exported so that install/update commands can re-apply the mutation to\n * trigger the relaunch indicator on already-open terminals.\n */\nexport function applyTerminalPath(context: vscode.ExtensionContext): void {\n const binDir = path.join(inferenceHome(), 'bin');\n const sep = process.platform === 'win32' ? ';' : ':';\n const env = context.environmentVariableCollection;\n env.prepend('PATH', binDir + sep);\n env.description = 'Adds the Inference toolchain to PATH';\n}\n\n/** globalState key prefix for remembering PATH fallback acceptance. */\nconst PATH_FALLBACK_KEY = 'inference.acceptedPathFallback';\n\nasync function checkToolchain(\n context: vscode.ExtensionContext,\n statusBarItem: vscode.StatusBarItem,\n configProvider: InferenceConfigProvider,\n): Promise {\n const platform = detectPlatform();\n const home = inferenceHome();\n const homeIsDefault = !process.env['INFERENCE_HOME'];\n const distServer = process.env['INFS_DIST_SERVER'];\n\n outputChannel.info('Inference Activation');\n\n if (!platform) {\n outputChannel.warn(\n `Platform: ${process.platform}-${process.arch} (unsupported)`,\n );\n outputChannel.info(\n `INFERENCE_HOME: ${home} ${homeIsDefault ? '(default)' : '(env)'}`,\n );\n outputChannel.info(\n `INFS_DIST_SERVER: ${distServer ?? '(not set, using production)'}`,\n );\n updateStatusBar(statusBarItem, null);\n vscode.commands.executeCommand('setContext', 'inference.toolchainInstalled', false);\n vscode.window\n .showWarningMessage(\n `Inference: unsupported platform (${process.platform}-${process.arch}).`,\n 'Download Page',\n )\n .then((action) => {\n if (action === 'Download Page') {\n vscode.env.openExternal(\n vscode.Uri.parse(\n 'https://github.com/Inferara/inference/releases',\n ),\n );\n }\n });\n return;\n }\n\n outputChannel.info(`Platform: ${platform.id}`);\n outputChannel.info(\n `INFERENCE_HOME: ${home} ${homeIsDefault ? '(default)' : '(env)'}`,\n );\n outputChannel.info(\n `INFS_DIST_SERVER: ${distServer ?? '(not set, using production)'}`,\n );\n\n const detection = detectInfs();\n if (!detection) {\n outputChannel.error('infs binary: not found');\n outputChannel.error('Toolchain status: errors');\n updateStatusBar(statusBarItem, null);\n vscode.commands.executeCommand('setContext', 'inference.toolchainInstalled', false);\n notifyMissing();\n return;\n }\n outputChannel.info(\n `infs binary: ${detection.path} (${detection.source})`,\n );\n\n if (!homeIsDefault && detection.source === 'path') {\n const stateKey = `${PATH_FALLBACK_KEY}:${home}`;\n const accepted = context.globalState.get(stateKey);\n\n if (accepted === '*') {\n outputChannel.info(\n `Note: Using PATH binary (notification permanently suppressed for this INFERENCE_HOME).`,\n );\n } else if (accepted === detection.path) {\n outputChannel.info(\n `Note: Using PATH binary (previously accepted for this INFERENCE_HOME).`,\n );\n } else {\n outputChannel.warn(\n `INFERENCE_HOME is set to ${home} but infs was not found there. Using binary from PATH instead.`,\n );\n vscode.window.showWarningMessage(\n `Inference: infs binary not found in INFERENCE_HOME (${home}). Found via PATH instead.`,\n 'Install',\n 'Dismiss',\n ).then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand('inference.installToolchain');\n } else {\n context.globalState.update(stateKey, '*');\n }\n });\n }\n }\n\n const versionOk = await checkInfsVersion(detection.path);\n if (!versionOk) {\n outputChannel.error('Toolchain status: errors');\n updateStatusBar(statusBarItem, null);\n vscode.commands.executeCommand('setContext', 'inference.toolchainInstalled', false);\n return;\n }\n\n vscode.commands.executeCommand('setContext', 'inference.toolchainInstalled', true);\n\n const doctorResult = await runDoctor(detection.path);\n updateStatusBar(statusBarItem, doctorResult);\n configProvider.refresh(detection, doctorResult);\n\n const status = doctorResult?.hasErrors\n ? 'errors'\n : doctorResult?.hasWarnings\n ? 'warnings'\n : 'healthy';\n if (doctorResult?.hasErrors) {\n outputChannel.error(`Toolchain status: ${status}`);\n } else if (doctorResult?.hasWarnings) {\n outputChannel.warn(`Toolchain status: ${status}`);\n } else {\n outputChannel.info(`Toolchain status: ${status}`);\n }\n\n checkForUpdates(detection.path, outputChannel).catch((err) =>\n outputChannel.error(`Update check failed: ${err}`),\n );\n}\n\n/**\n * Run `infs version` and check the output against MIN_INFS_VERSION.\n * Returns true if version is acceptable.\n */\nasync function checkInfsVersion(infsPath: string): Promise {\n try {\n const result = await exec(infsPath, ['version']);\n if (result.exitCode !== 0) {\n outputChannel.error(\n `infs version failed (exit ${result.exitCode}): ${result.stderr}`,\n );\n return false;\n }\n // Output format: \"infs 0.1.0\"\n const match = result.stdout.match(/^infs\\s+(\\S+)/);\n if (!match) {\n outputChannel.error(\n `Could not parse infs version from: ${result.stdout.trim()}`,\n );\n return false;\n }\n const version = match[1];\n outputChannel.info(`infs version: ${version}`);\n\n if (compareSemver(version, MIN_INFS_VERSION) < 0) {\n outputChannel.warn(\n `infs version ${version} is below minimum ${MIN_INFS_VERSION}.`,\n );\n vscode.window\n .showWarningMessage(\n `Inference: infs version ${version} is outdated (minimum: ${MIN_INFS_VERSION}). Please update.`,\n 'Update',\n )\n .then((action) => {\n if (action === 'Update') {\n vscode.commands.executeCommand('inference.updateToolchain');\n }\n });\n return false;\n }\n return true;\n } catch (err) {\n outputChannel.error(`Failed to run infs version: ${err}`);\n return false;\n }\n}\n\nfunction notifyMissing(): void {\n vscode.window\n .showInformationMessage(\n 'Inference toolchain not found. Would you like to install it?',\n 'Install',\n 'Download Manually',\n 'Configure Path',\n )\n .then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand('inference.installToolchain');\n } else if (action === 'Download Manually') {\n vscode.env.openExternal(\n vscode.Uri.parse(\n 'https://github.com/Inferara/inference/releases',\n ),\n );\n } else if (action === 'Configure Path') {\n vscode.commands.executeCommand(\n 'workbench.action.openSettings',\n 'inference.path',\n );\n }\n });\n}\n", "import * as os from 'os';\n\nexport type PlatformId = 'linux-x64' | 'macos-arm64' | 'windows-x64';\n\nexport interface PlatformInfo {\n id: PlatformId;\n archiveExtension: string;\n binaryName: string;\n}\n\nexport const SUPPORTED_PLATFORMS: Record = {\n 'linux-x64': 'linux-x64',\n 'darwin-arm64': 'macos-arm64',\n 'win32-x64': 'windows-x64',\n};\n\n/**\n * Detect the platform and return its info, or null if unsupported.\n * When osPlatform/osArch are omitted, uses the current runtime values.\n */\nexport function detectPlatform(\n osPlatform?: string,\n osArch?: string,\n): PlatformInfo | null {\n const key = `${osPlatform ?? os.platform()}-${osArch ?? os.arch()}`;\n const id = SUPPORTED_PLATFORMS[key];\n if (!id) {\n return null;\n }\n return {\n id,\n archiveExtension: id === 'windows-x64' ? '.zip' : '.tar.gz',\n binaryName: id === 'windows-x64' ? 'infs.exe' : 'infs',\n };\n}\n", "import * as fs from 'fs';\nimport * as path from 'path';\nimport { getSettings } from '../config/settings';\nimport { detectPlatform } from './platform';\nimport { inferenceHome } from './home';\n\nexport { inferenceHome };\n\n/** Check whether a file exists and is executable (or just exists on Windows). */\nexport function isExecutable(filePath: string): boolean {\n try {\n const mode = process.platform === 'win32'\n ? fs.constants.F_OK\n : fs.constants.X_OK;\n fs.accessSync(filePath, mode);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Search PATH for the given binary name.\n * Returns the first match or null.\n */\nexport function findInPath(binaryName: string): string | null {\n const envPath = process.env['PATH'] || '';\n const sep = process.platform === 'win32' ? ';' : ':';\n const dirs = envPath.split(sep).filter(Boolean);\n for (const dir of dirs) {\n const candidate = path.join(dir, binaryName);\n if (isExecutable(candidate)) {\n return candidate;\n }\n }\n return null;\n}\n\n/** Source where the infs binary was found. */\nexport type InfsSource = 'settings' | 'managed' | 'path';\n\n/** Result of infs binary detection. */\nexport interface InfsDetection {\n path: string;\n source: InfsSource;\n}\n\n/**\n * Detect infs binary location.\n *\n * Search order:\n * 1. Custom path from settings (inference.path)\n * 2. Managed location (INFERENCE_HOME/bin/infs)\n * 3. System PATH\n *\n * Returns the resolved absolute path and source, or null if not found.\n */\nexport function detectInfs(): InfsDetection | null {\n const platform = detectPlatform();\n const binaryName = platform?.binaryName ?? 'infs';\n\n const settings = getSettings();\n if (settings.path) {\n if (isExecutable(settings.path)) {\n return { path: settings.path, source: 'settings' };\n }\n return null;\n }\n\n const managedPath = path.join(inferenceHome(), 'bin', binaryName);\n if (isExecutable(managedPath)) {\n return { path: managedPath, source: 'managed' };\n }\n\n const pathResult = findInPath(binaryName);\n if (pathResult) {\n return { path: pathResult, source: 'path' };\n }\n\n return null;\n}\n", "import * as vscode from 'vscode';\n\nexport interface InferenceSettings {\n /** Custom path to infs binary. Empty string means auto-detect. */\n path: string;\n /** Prompt to install toolchain if not found. */\n autoInstall: boolean;\n /** Check for toolchain updates on activation. */\n checkForUpdates: boolean;\n}\n\n/** Read current inference.* configuration values. */\nexport function getSettings(): InferenceSettings {\n const config = vscode.workspace.getConfiguration('inference');\n return {\n path: config.get('path', ''),\n autoInstall: config.get('autoInstall', true),\n checkForUpdates: config.get('checkForUpdates', true),\n };\n}\n", "/**\n * Compare two semver strings. Returns negative if a < b, 0 if equal, positive if a > b.\n * Handles numeric major.minor.patch and pre-release tags per the SemVer 2.0.0 spec.\n *\n * Pre-release versions have lower precedence than the associated normal version:\n * 1.0.0-alpha < 1.0.0\n *\n * Pre-release identifiers are compared left-to-right:\n * - Numeric identifiers are compared as integers.\n * - Alphanumeric identifiers are compared lexically (ASCII order).\n * - Numeric identifiers always have lower precedence than alphanumeric.\n * - A shorter set of identifiers has lower precedence if all preceding are equal.\n */\nexport function compareSemver(a: string, b: string): number {\n const clean = (v: string) => v.replace(/^v/i, '');\n const [coreA, preA] = clean(a).split('-', 2);\n const [coreB, preB] = clean(b).split('-', 2);\n\n const pa = coreA.split('.').map(Number);\n const pb = coreB.split('.').map(Number);\n for (let i = 0; i < 3; i++) {\n const diff = (pa[i] || 0) - (pb[i] || 0);\n if (diff !== 0) {\n return diff;\n }\n }\n\n if (!preA && !preB) {\n return 0;\n }\n if (preA && !preB) {\n return -1;\n }\n if (!preA && preB) {\n return 1;\n }\n\n const partsA = preA!.split('.');\n const partsB = preB!.split('.');\n const len = Math.max(partsA.length, partsB.length);\n for (let i = 0; i < len; i++) {\n if (i >= partsA.length) {\n return -1;\n }\n if (i >= partsB.length) {\n return 1;\n }\n const numA = Number(partsA[i]);\n const numB = Number(partsB[i]);\n const aIsNum = !Number.isNaN(numA);\n const bIsNum = !Number.isNaN(numB);\n if (aIsNum && bIsNum) {\n if (numA !== numB) {\n return numA - numB;\n }\n } else if (aIsNum) {\n return -1;\n } else if (bIsNum) {\n return 1;\n } else {\n if (partsA[i] < partsB[i]) {\n return -1;\n }\n if (partsA[i] > partsB[i]) {\n return 1;\n }\n }\n }\n return 0;\n}\n", "import * as vscode from 'vscode';\nimport { detectPlatform, PlatformInfo } from '../toolchain/platform';\nimport {\n installToolchain,\n InstallProgress,\n InstallProgressCallback,\n InstallResult,\n} from '../toolchain/installation';\nimport { runDoctor } from '../toolchain/doctor';\nimport { updateStatusBar } from '../ui/statusBar';\n\n/** Guard against concurrent install attempts. */\nlet installing = false;\n\n/**\n * Register the inference.installToolchain command.\n * Returns the Disposable to add to context.subscriptions.\n */\nexport function registerInstallCommand(\n outputChannel: vscode.OutputChannel,\n statusBarItem: vscode.StatusBarItem,\n): vscode.Disposable {\n return vscode.commands.registerCommand(\n 'inference.installToolchain',\n async () => {\n if (installing) {\n vscode.window.showInformationMessage(\n 'Inference toolchain installation is already in progress.',\n );\n return;\n }\n\n const platform = detectPlatform();\n if (!platform) {\n vscode.window.showErrorMessage(\n `Inference: unsupported platform (${process.platform}-${process.arch}).`,\n );\n return;\n }\n\n installing = true;\n try {\n const result = await installWithProgress(\n platform,\n outputChannel,\n );\n outputChannel.appendLine(\n `Toolchain v${result.version} installed at ${result.infsPath}`,\n );\n vscode.commands.executeCommand(\n 'setContext', 'inference.toolchainInstalled', true,\n );\n\n const doctorResult = await runDoctor(result.infsPath);\n updateStatusBar(statusBarItem, doctorResult);\n vscode.commands.executeCommand('inference.refreshConfigView');\n vscode.commands.executeCommand('inference.applyTerminalPath');\n\n notifyInstallSuccess(result.version, result.doctorWarnings);\n } catch (err) {\n const message =\n err instanceof Error ? err.message : String(err);\n outputChannel.appendLine(`Installation failed: ${message}`);\n notifyInstallError(message);\n } finally {\n installing = false;\n }\n },\n );\n}\n\n/** Run the installation with a VS Code progress notification. */\nfunction installWithProgress(\n platform: PlatformInfo,\n outputChannel: vscode.OutputChannel,\n): Promise {\n return vscode.window.withProgress(\n {\n location: vscode.ProgressLocation.Notification,\n title: 'Inference Toolchain',\n cancellable: false,\n },\n async (progress) => {\n const onProgress: InstallProgressCallback = (\n p: InstallProgress,\n ) => {\n outputChannel.appendLine(p.message);\n if (p.stage === 'downloading' && p.bytesTotal) {\n const pct = Math.round(\n ((p.bytesReceived ?? 0) / p.bytesTotal) * 100,\n );\n progress.report({ message: `${p.message} (${pct}%)` });\n } else {\n progress.report({ message: p.message });\n }\n };\n return installToolchain(platform, onProgress);\n },\n );\n}\n\n/** Show a notification that the toolchain was installed successfully. */\nfunction notifyInstallSuccess(\n version: string,\n doctorWarnings: boolean,\n): void {\n if (doctorWarnings) {\n vscode.window\n .showWarningMessage(\n `Inference toolchain v${version} installed, but doctor reported issues. See output for details.`,\n 'Show Output',\n )\n .then((action) => {\n if (action === 'Show Output') {\n vscode.commands.executeCommand('inference.showOutput');\n }\n });\n } else {\n vscode.window.showInformationMessage(\n `Inference toolchain v${version} installed successfully.`,\n );\n }\n}\n\n/** Show an error notification for installation failure. */\nfunction notifyInstallError(errorMessage: string): void {\n vscode.window\n .showErrorMessage(\n `Inference toolchain installation failed: ${errorMessage}`,\n 'Retry',\n 'Download Manually',\n 'Settings',\n )\n .then((action) => {\n if (action === 'Retry') {\n vscode.commands.executeCommand('inference.installToolchain');\n } else if (action === 'Download Manually') {\n vscode.env.openExternal(\n vscode.Uri.parse(\n 'https://github.com/Inferara/inference/releases',\n ),\n );\n } else if (action === 'Settings') {\n vscode.commands.executeCommand(\n 'workbench.action.openSettings',\n 'inference.path',\n );\n }\n });\n}\n", "import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { PlatformInfo } from './platform';\nimport { inferenceHome } from './home';\nimport { fetchJson, downloadFile, sha256File } from '../utils/download';\nimport { extractArchive } from '../utils/extract';\nimport { exec } from '../utils/exec';\nimport {\n ReleaseEntry,\n findLatestRelease,\n} from './manifest';\n\nexport type { FileEntry, ReleaseEntry } from './manifest';\nexport { findLatestRelease } from './manifest';\n\n/** Progress updates emitted during installation. */\nexport interface InstallProgress {\n stage:\n | 'fetching-manifest'\n | 'downloading'\n | 'extracting'\n | 'installing'\n | 'verifying';\n message: string;\n bytesReceived?: number;\n bytesTotal?: number;\n}\n\nexport type InstallProgressCallback = (progress: InstallProgress) => void;\n\n/** Result of a successful installation. */\nexport interface InstallResult {\n infsPath: string;\n version: string;\n doctorWarnings: boolean;\n}\n\nconst DEFAULT_DIST_SERVER = 'https://inference-lang.org';\nconst RELEASES_PATH = '/releases.json';\n\nfunction manifestUrl(): string {\n const server = process.env['INFS_DIST_SERVER']?.trim();\n const base = server && server.length > 0\n ? server.replace(/\\/+$/, '')\n : DEFAULT_DIST_SERVER;\n return `${base}${RELEASES_PATH}`;\n}\n\n/**\n * Run the full installation flow.\n * Fetches manifest, downloads infs, extracts, runs `infs install`, verifies with `infs doctor`.\n * Throws on failure with a descriptive error message.\n */\nexport async function installToolchain(\n platform: PlatformInfo,\n onProgress?: InstallProgressCallback,\n): Promise {\n onProgress?.({\n stage: 'fetching-manifest',\n message: 'Fetching release manifest...',\n });\n\n const manifest = await fetchJson(manifestUrl());\n\n if (!Array.isArray(manifest)) {\n throw new Error('Invalid release manifest: expected an array.');\n }\n for (const entry of manifest) {\n if (\n typeof entry?.version !== 'string' ||\n typeof entry?.stable !== 'boolean' ||\n !Array.isArray(entry?.files)\n ) {\n throw new Error(\n `Invalid release manifest entry: ${JSON.stringify(entry)?.slice(0, 200)}`,\n );\n }\n }\n\n const match = findLatestRelease(manifest, platform);\n if (!match) {\n throw new Error(\n `No compatible infs release found for ${platform.id}.`,\n );\n }\n\n const { release, fileUrl, sha256 } = match;\n const version = release.version;\n\n onProgress?.({\n stage: 'downloading',\n message: `Downloading infs v${version}...`,\n });\n\n const destDir = path.join(inferenceHome(), 'bin');\n fs.mkdirSync(destDir, { recursive: true });\n\n const archiveName = `infs-${platform.id}${platform.archiveExtension}`;\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'infs-'));\n const archivePath = path.join(tmpDir, archiveName);\n\n try {\n await downloadFile(fileUrl, {\n destPath: archivePath,\n onProgress: (received, total) => {\n onProgress?.({\n stage: 'downloading',\n message: `Downloading infs v${version}...`,\n bytesReceived: received,\n bytesTotal: total,\n });\n },\n });\n\n const actualHash = await sha256File(archivePath);\n if (actualHash !== sha256) {\n throw new Error(\n `SHA-256 verification failed for infs v${version}. Expected ${sha256}, got ${actualHash}.`,\n );\n }\n\n onProgress?.({\n stage: 'extracting',\n message: 'Extracting archive...',\n });\n\n await extractArchive({ archivePath, destDir });\n } finally {\n try {\n fs.rmSync(tmpDir, { recursive: true, force: true });\n } catch {\n // best-effort cleanup\n }\n }\n\n const infsPath = path.join(destDir, platform.binaryName);\n if (!fs.existsSync(infsPath)) {\n throw new Error(\n `infs binary not found at ${infsPath} after extraction.`,\n );\n }\n\n onProgress?.({\n stage: 'installing',\n message: 'Running infs install...',\n });\n\n const binDir = path.join(inferenceHome(), 'bin');\n const sep = process.platform === 'win32' ? ';' : ':';\n const augmentedPath = `${binDir}${sep}${process.env['PATH'] ?? ''}`;\n\n const installResult = await exec(infsPath, ['install'], {\n timeoutMs: 120_000,\n env: { PATH: augmentedPath },\n });\n if (installResult.exitCode !== 0) {\n throw new Error(\n `infs install failed (exit ${installResult.exitCode}): ${installResult.stderr || installResult.stdout}`,\n );\n }\n\n onProgress?.({\n stage: 'verifying',\n message: 'Verifying installation...',\n });\n\n let doctorWarnings = false;\n try {\n const doctorResult = await exec(infsPath, ['doctor'], {\n timeoutMs: 30_000,\n env: { PATH: augmentedPath },\n });\n if (doctorResult.exitCode !== 0) {\n doctorWarnings = true;\n } else {\n const { parseDoctorOutput } = await import('./doctor');\n const parsed = parseDoctorOutput(doctorResult.stdout);\n if (parsed.hasErrors || parsed.hasWarnings) {\n doctorWarnings = true;\n }\n }\n } catch {\n doctorWarnings = true;\n }\n\n return { infsPath, version, doctorWarnings };\n}\n", "import * as https from 'https';\nimport * as http from 'http';\nimport * as fs from 'fs';\nimport * as crypto from 'crypto';\n\n/** Callback invoked during download with bytes received and total (if known). */\nexport type ProgressCallback = (\n received: number,\n total: number | undefined,\n) => void;\n\nexport interface DownloadOptions {\n /** Absolute path where the downloaded file will be saved. */\n destPath: string;\n /** Optional progress callback. */\n onProgress?: ProgressCallback;\n /** Connection timeout in milliseconds (default: 15000). */\n timeoutMs?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 15_000;\nconst MAX_REDIRECTS = 5;\n\nconst SOCKET_TIMEOUT_MS = 15_000;\nconst MAX_JSON_RESPONSE_BYTES = 10 * 1024 * 1024;\n\n/**\n * Perform an HTTPS GET request following redirects.\n * Rejects HTTPS-to-HTTP downgrades.\n */\nfunction followRedirects(\n url: string,\n remaining: number,\n): Promise {\n return new Promise((resolve, reject) => {\n const parsed = new URL(url);\n const requester = parsed.protocol === 'https:' ? https : http;\n\n const req = requester.get(url, (res) => {\n const status = res.statusCode ?? 0;\n\n if (status >= 300 && status < 400 && res.headers.location) {\n if (remaining <= 0) {\n res.resume();\n reject(new Error(`Too many redirects fetching ${url}`));\n return;\n }\n const target = new URL(res.headers.location, url).href;\n const targetProtocol = new URL(target).protocol;\n if (parsed.protocol === 'https:' && targetProtocol === 'http:') {\n res.resume();\n reject(\n new Error(\n `Refusing HTTPS-to-HTTP redirect: ${url} -> ${target}`,\n ),\n );\n return;\n }\n res.resume();\n followRedirects(target, remaining - 1).then(resolve, reject);\n return;\n }\n\n if (status < 200 || status >= 300) {\n res.resume();\n reject(new Error(`HTTP ${status} fetching ${url}`));\n return;\n }\n\n resolve(res);\n });\n\n req.setTimeout(SOCKET_TIMEOUT_MS, () => {\n req.destroy(new Error(`Connection timed out for ${url}`));\n });\n\n req.on('error', (err) =>\n reject(new Error(`Network error fetching ${url}: ${err.message}`)),\n );\n });\n}\n\n/**\n * Fetch a JSON document from a URL via HTTPS GET.\n * Follows up to 5 redirects. Rejects HTTPS-to-HTTP downgrades.\n */\nexport function fetchJson(url: string): Promise {\n return new Promise((resolve, reject) => {\n followRedirects(url, MAX_REDIRECTS).then(\n (res) => {\n const chunks: Buffer[] = [];\n let totalBytes = 0;\n res.on('data', (chunk: Buffer) => {\n totalBytes += chunk.length;\n if (totalBytes > MAX_JSON_RESPONSE_BYTES) {\n res.destroy();\n reject(new Error(`Response too large (>${MAX_JSON_RESPONSE_BYTES} bytes) from ${url}`));\n return;\n }\n chunks.push(chunk);\n });\n res.on('end', () => {\n try {\n const text = Buffer.concat(chunks).toString('utf-8');\n resolve(JSON.parse(text) as T);\n } catch (err) {\n reject(\n new Error(\n `Failed to parse JSON from ${url}: ${err instanceof Error ? err.message : err}`,\n ),\n );\n }\n });\n res.on('error', (err) =>\n reject(\n new Error(\n `Error reading response from ${url}: ${err.message}`,\n ),\n ),\n );\n },\n (err) => reject(err),\n );\n });\n}\n\n/**\n * Download a file from a URL to destPath using streaming.\n * Uses a temp file (.partial suffix) and renames on completion.\n * Follows redirects (GitHub releases redirect to CDN).\n */\nexport function downloadFile(\n url: string,\n options: DownloadOptions,\n): Promise {\n const timeout = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const partialPath = options.destPath + '.partial';\n\n return new Promise((resolve, reject) => {\n let settled = false;\n const settle = (fn: (...args: T) => void, ...args: T) => {\n if (!settled) {\n settled = true;\n fn(...args);\n }\n };\n\n followRedirects(url, MAX_REDIRECTS).then(\n (res) => {\n const totalStr = res.headers['content-length'];\n const total = totalStr ? parseInt(totalStr, 10) : undefined;\n let received = 0;\n\n const ws = fs.createWriteStream(partialPath);\n\n res.on('data', (chunk: Buffer) => {\n received += chunk.length;\n options.onProgress?.(received, total);\n });\n\n res.pipe(ws);\n\n const cleanup = () => {\n try {\n fs.unlinkSync(partialPath);\n } catch {\n // ignore\n }\n };\n\n // No-data timeout: if no bytes arrive for `timeout` ms, abort\n let dataTimer: ReturnType | undefined;\n const clearDataTimer = () => {\n if (dataTimer) {\n clearTimeout(dataTimer);\n dataTimer = undefined;\n }\n };\n const resetTimer = () => {\n clearDataTimer();\n dataTimer = setTimeout(() => {\n res.destroy();\n ws.destroy();\n cleanup();\n settle(reject, new Error(`Download timed out for ${url}`));\n }, timeout);\n };\n resetTimer();\n res.on('data', resetTimer);\n res.on('end', clearDataTimer);\n\n ws.on('finish', () => {\n clearDataTimer();\n try {\n fs.renameSync(partialPath, options.destPath);\n settle(resolve);\n } catch (err) {\n cleanup();\n settle(\n reject,\n new Error(\n `Failed to save download to ${options.destPath}: ${err instanceof Error ? err.message : err}`,\n ),\n );\n }\n });\n\n ws.on('error', (err) => {\n clearDataTimer();\n res.destroy();\n cleanup();\n settle(\n reject,\n new Error(\n `Failed to write download: ${err.message}`,\n ),\n );\n });\n\n res.on('error', (err) => {\n clearDataTimer();\n ws.destroy();\n cleanup();\n settle(\n reject,\n new Error(\n `Download stream error from ${url}: ${err.message}`,\n ),\n );\n });\n },\n (err) => settle(reject, err),\n );\n });\n}\n\n/**\n * Compute SHA-256 hash of a file.\n * Returns lowercase hex string.\n */\nexport function sha256File(filePath: string): Promise {\n return new Promise((resolve, reject) => {\n const hash = crypto.createHash('sha256');\n const stream = fs.createReadStream(filePath);\n stream.on('data', (chunk) => hash.update(chunk));\n stream.on('end', () => resolve(hash.digest('hex')));\n stream.on('error', (err) =>\n reject(\n new Error(\n `Failed to compute SHA-256 for ${filePath}: ${err.message}`,\n ),\n ),\n );\n });\n}\n", "import * as fs from 'fs';\nimport * as path from 'path';\nimport { exec } from './exec';\n\nexport interface ExtractOptions {\n /** Path to the archive file. */\n archivePath: string;\n /** Directory to extract into (created if it doesn't exist). */\n destDir: string;\n}\n\n/**\n * Extract an archive to the destination directory.\n * Detects format from file extension (.tar.gz or .zip).\n * On Unix, sets executable permission on extracted binaries.\n */\nexport async function extractArchive(options: ExtractOptions): Promise {\n fs.mkdirSync(options.destDir, { recursive: true });\n\n if (\n options.archivePath.endsWith('.tar.gz') ||\n options.archivePath.endsWith('.tgz')\n ) {\n await extractTarGz(options.archivePath, options.destDir);\n } else if (options.archivePath.endsWith('.zip')) {\n await extractZip(options.archivePath, options.destDir);\n } else {\n throw new Error(\n `Unsupported archive format: ${path.basename(options.archivePath)}`,\n );\n }\n\n if (process.platform !== 'win32') {\n setExecutablePermissions(options.destDir);\n }\n}\n\nasync function extractTarGz(\n archivePath: string,\n destDir: string,\n): Promise {\n const result = await exec('tar', ['-xzf', archivePath, '-C', destDir]);\n if (result.exitCode !== 0) {\n throw new Error(\n `tar extraction failed (exit ${result.exitCode}): ${result.stderr}`,\n );\n }\n}\n\n/** Escape a string for use inside a PowerShell single-quoted literal. */\nfunction escapePowerShellSingleQuote(value: string): string {\n return value.replace(/'/g, \"''\");\n}\n\nasync function extractZip(\n archivePath: string,\n destDir: string,\n): Promise {\n const safePath = escapePowerShellSingleQuote(archivePath);\n const safeDest = escapePowerShellSingleQuote(destDir);\n const result = await exec('powershell', [\n '-NoProfile',\n '-Command',\n `Expand-Archive -LiteralPath '${safePath}' -DestinationPath '${safeDest}' -Force`,\n ]);\n if (result.exitCode !== 0) {\n throw new Error(\n `zip extraction failed (exit ${result.exitCode}): ${result.stderr}`,\n );\n }\n}\n\n/** Set executable permissions on files in the directory (non-recursive, top level only). */\nfunction setExecutablePermissions(dir: string): void {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (entry.isFile()) {\n try {\n fs.chmodSync(path.join(dir, entry.name), 0o755);\n } catch {\n // best-effort per file\n }\n }\n }\n}\n", "import { compareSemver } from '../utils/semver';\n\n/** A platform-specific file entry from the manifest. */\nexport interface FileEntry {\n url: string;\n sha256: string;\n}\n\n/** A single release entry from the manifest. */\nexport interface ReleaseEntry {\n version: string;\n stable: boolean;\n files: FileEntry[];\n}\n\n/** Minimal platform info needed for manifest matching. */\nexport interface ManifestPlatform {\n id: string;\n}\n\n/**\n * Extract tool name from a manifest file URL.\n * URL format: `https://.../tool-os-arch.ext` (e.g., `infs-linux-x64.tar.gz`).\n */\nexport function toolFromUrl(url: string): string {\n const filename = url.split('/').pop() ?? '';\n return filename.split('-')[0] ?? '';\n}\n\n/**\n * Extract OS name from a manifest file URL.\n * URL format: `https://.../tool-os-arch.ext` (e.g., `infs-linux-x64.tar.gz`).\n */\nexport function osFromUrl(url: string): string {\n const filename = url.split('/').pop() ?? '';\n const parts = filename.split('-');\n return parts.length > 1 ? parts[1] : '';\n}\n\n/** Map platform ID to the OS string used in manifest URLs. */\nexport function platformOs(platform: ManifestPlatform): string {\n if (platform.id === 'linux-x64') {\n return 'linux';\n }\n if (platform.id === 'macos-arm64') {\n return 'macos';\n }\n if (platform.id === 'windows-x64') {\n return 'windows';\n }\n return '';\n}\n\n/**\n * Find the latest release from the manifest for the given platform.\n * Matches the `infs` tool artifact for the platform's OS.\n * Returns the release entry, file URL, and sha256, or null if not found.\n */\nexport function findLatestRelease(\n manifest: ReleaseEntry[],\n platform: ManifestPlatform,\n): { release: ReleaseEntry; fileUrl: string; sha256: string } | null {\n if (manifest.length === 0) {\n return null;\n }\n\n const sorted = [...manifest].sort((a, b) =>\n compareSemver(b.version, a.version),\n );\n\n const os = platformOs(platform);\n\n for (const release of sorted) {\n const file = release.files.find(\n (f) => toolFromUrl(f.url) === 'infs' && osFromUrl(f.url) === os,\n );\n if (file) {\n return { release, fileUrl: file.url, sha256: file.sha256 };\n }\n }\n\n return null;\n}\n", "import * as vscode from 'vscode';\nimport { DoctorResult } from '../toolchain/doctor';\nimport { determineStatusBarState, StatusBarIcon } from './statusBarState';\n\nconst ICON_MAP: Record = {\n loading: '$(loading~spin)',\n dash: '$(dash)',\n check: '$(check)',\n warning: '$(warning)',\n error: '$(error)',\n};\n\nconst BACKGROUND_MAP: Record = {\n none: undefined,\n warning: new vscode.ThemeColor('statusBarItem.warningBackground'),\n error: new vscode.ThemeColor('statusBarItem.errorBackground'),\n};\n\n/**\n * Create the Inference status bar item.\n * Positioned on the left side with low priority.\n * Clicking triggers the inference.runDoctor command.\n */\nexport function createStatusBar(): vscode.StatusBarItem {\n const item = vscode.window.createStatusBarItem(\n vscode.StatusBarAlignment.Left,\n 0,\n );\n item.command = 'inference.runDoctor';\n item.text = '$(loading~spin) Inference';\n item.tooltip = 'Inference: Checking toolchain...';\n item.show();\n return item;\n}\n\n/**\n * Update the status bar to reflect doctor results.\n *\n * - null: toolchain not found (grey dash icon)\n * - hasErrors: red error icon\n * - hasWarnings: yellow warning icon\n * - all OK: green check icon\n */\nexport function updateStatusBar(\n item: vscode.StatusBarItem,\n result: DoctorResult | null,\n): void {\n const state = determineStatusBarState(result);\n item.text = `${ICON_MAP[state.icon]} ${state.label}`;\n item.tooltip = state.tooltip;\n item.backgroundColor = BACKGROUND_MAP[state.background];\n}\n", "import { DoctorResult } from '../toolchain/doctor';\n\nexport type StatusBarIcon = 'loading' | 'dash' | 'check' | 'warning' | 'error';\nexport type StatusBarBackground = 'none' | 'warning' | 'error';\n\nexport interface StatusBarState {\n icon: StatusBarIcon;\n label: string;\n tooltip: string;\n background: StatusBarBackground;\n}\n\n/**\n * Determine the status bar display state from a doctor result.\n *\n * - null: toolchain not found (dash icon)\n * - hasErrors: red error icon\n * - hasWarnings: yellow warning icon\n * - all OK: green check icon\n */\nexport function determineStatusBarState(result: DoctorResult | null): StatusBarState {\n if (result === null) {\n return {\n icon: 'dash',\n label: 'Inference',\n tooltip: 'Inference: Toolchain not found. Click to run doctor.',\n background: 'none',\n };\n }\n\n if (result.hasErrors) {\n return {\n icon: 'error',\n label: 'Inference',\n tooltip: `Inference: ${result.summary || 'Toolchain errors detected'}`,\n background: 'error',\n };\n }\n\n if (result.hasWarnings) {\n return {\n icon: 'warning',\n label: 'Inference',\n tooltip: `Inference: ${result.summary || 'Toolchain warnings detected'}`,\n background: 'warning',\n };\n }\n\n return {\n icon: 'check',\n label: 'Inference',\n tooltip: 'Inference: Toolchain healthy',\n background: 'none',\n };\n}\n", "import * as vscode from 'vscode';\nimport { detectInfs } from '../toolchain/detection';\nimport { exec, ExecResult } from '../utils/exec';\nimport {\n ComponentName,\n KNOWN_COMPONENTS,\n componentAddArgs,\n} from '../toolchain/components';\n\n/** Guard against concurrent component install attempts. */\nlet installing = false;\n\n/**\n * Timeout for a component install. Managed downloads can be ~100 MB, far\n * beyond the default exec timeout, so allow up to ten minutes.\n */\nconst INSTALL_TIMEOUT_MS = 600_000;\n\n/**\n * Register the inference.installComponent command.\n * Returns the Disposable to add to context.subscriptions.\n */\nexport function registerInstallComponentCommand(\n outputChannel: vscode.OutputChannel,\n): vscode.Disposable {\n return vscode.commands.registerCommand(\n 'inference.installComponent',\n async (component: string = 'wasm-opt') => {\n if (installing) {\n vscode.window.showInformationMessage(\n 'Inference component installation is already in progress.',\n );\n return;\n }\n\n if (!isKnownComponent(component)) {\n vscode.window.showErrorMessage(\n `Inference: unknown component '${component}'.`,\n );\n return;\n }\n\n const detection = detectInfs();\n if (!detection) {\n vscode.window\n .showWarningMessage(\n 'Inference toolchain not found. Install it first.',\n 'Install',\n )\n .then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand(\n 'inference.installToolchain',\n );\n }\n });\n return;\n }\n\n installing = true;\n try {\n const result = await installWithProgress(\n detection.path,\n component,\n outputChannel,\n );\n if (result.stdout) {\n outputChannel.appendLine(result.stdout);\n }\n if (result.stderr) {\n outputChannel.appendLine(result.stderr);\n }\n\n if (result.exitCode === 0) {\n vscode.window.showInformationMessage(\n `Inference: component '${component}' installed.`,\n );\n vscode.commands.executeCommand('inference.runDoctor');\n } else {\n notifyInstallError(component);\n }\n } catch (err) {\n const message =\n err instanceof Error ? err.message : String(err);\n outputChannel.appendLine(\n `Component installation failed: ${message}`,\n );\n notifyInstallError(component);\n } finally {\n installing = false;\n }\n },\n );\n}\n\n/** Type guard: whether a string is a known component name. */\nfunction isKnownComponent(name: string): name is ComponentName {\n return (KNOWN_COMPONENTS as readonly string[]).includes(name);\n}\n\n/** Run `infs component add ` with a VS Code progress notification. */\nfunction installWithProgress(\n infsPath: string,\n component: ComponentName,\n outputChannel: vscode.OutputChannel,\n): Promise {\n return vscode.window.withProgress(\n {\n location: vscode.ProgressLocation.Notification,\n title: 'Inference Component',\n cancellable: false,\n },\n async (progress) => {\n progress.report({ message: `Installing ${component}...` });\n outputChannel.appendLine(`Installing component '${component}'...`);\n return exec(infsPath, componentAddArgs(component), {\n timeoutMs: INSTALL_TIMEOUT_MS,\n });\n },\n );\n}\n\n/** Show an error notification for component installation failure. */\nfunction notifyInstallError(component: ComponentName): void {\n vscode.window\n .showErrorMessage(\n `Inference: failed to install component '${component}'. See output for details.`,\n 'Show Output',\n 'Retry',\n )\n .then((action) => {\n if (action === 'Show Output') {\n vscode.commands.executeCommand('inference.showOutput');\n } else if (action === 'Retry') {\n vscode.commands.executeCommand(\n 'inference.installComponent',\n component,\n );\n }\n });\n}\n", "import { DoctorResult } from './doctor';\n\n/**\n * Toolchain components the CLI can provision via `infs component add`.\n *\n * Mirrors the `KNOWN_COMPONENTS` list in the `infs component` command\n * (`apps/infs/src/commands/component.rs`); keep the two in sync.\n */\nexport const KNOWN_COMPONENTS = ['wasm-opt'] as const;\n\n/** A component name understood by `infs component`. */\nexport type ComponentName = (typeof KNOWN_COMPONENTS)[number];\n\n/** Build the argv for `infs component add `. */\nexport function componentAddArgs(component: ComponentName): string[] {\n return ['component', 'add', component];\n}\n\n/**\n * Whether a doctor result indicates the wasm-opt component needs attention,\n * i.e. any check named `wasm-opt` reported a warning or failure.\n */\nexport function wasmOptNeedsAttention(result: DoctorResult): boolean {\n return result.checks.some(\n (check) =>\n check.name === 'wasm-opt' &&\n (check.status === 'warn' || check.status === 'fail'),\n );\n}\n", "import * as vscode from 'vscode';\nimport { detectInfs } from '../toolchain/detection';\nimport { runDoctor, DoctorResult } from '../toolchain/doctor';\nimport { formatDoctorChecks } from '../toolchain/doctorFormat';\nimport { wasmOptNeedsAttention } from '../toolchain/components';\nimport { updateStatusBar } from '../ui/statusBar';\n\n/** Guard against concurrent doctor runs. */\nlet running = false;\n\n/**\n * Register the inference.runDoctor command.\n *\n * When invoked: detect infs \u2192 run doctor \u2192 display results in output\n * channel \u2192 update status bar \u2192 show notification summary.\n */\nexport function registerDoctorCommand(\n outputChannel: vscode.OutputChannel,\n statusBarItem: vscode.StatusBarItem,\n): vscode.Disposable {\n return vscode.commands.registerCommand(\n 'inference.runDoctor',\n async () => {\n if (running) {\n return;\n }\n\n const detection = detectInfs();\n if (!detection) {\n outputChannel.appendLine('Doctor: infs binary not found.');\n updateStatusBar(statusBarItem, null);\n vscode.window\n .showWarningMessage(\n 'Inference toolchain not found. Install it first.',\n 'Install',\n )\n .then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand(\n 'inference.installToolchain',\n );\n }\n });\n return;\n }\n\n running = true;\n try {\n outputChannel.appendLine(\n `Running infs doctor (${detection.path})...`,\n );\n const result = await runDoctor(detection.path);\n\n if (!result) {\n outputChannel.appendLine(\n 'Doctor: failed to execute infs doctor.',\n );\n updateStatusBar(statusBarItem, null);\n vscode.window.showErrorMessage(\n 'Inference: Failed to run doctor. See output for details.',\n );\n return;\n }\n\n for (const line of formatDoctorChecks(result)) {\n outputChannel.appendLine(line);\n }\n updateStatusBar(statusBarItem, result);\n vscode.commands.executeCommand('inference.refreshConfigView');\n\n if (result.hasErrors) {\n const actions = ['Show Output'];\n if (wasmOptNeedsAttention(result)) {\n actions.push('Install wasm-opt');\n }\n vscode.window\n .showErrorMessage(\n `Inference doctor: ${result.summary}`,\n ...actions,\n )\n .then((action) => {\n if (action === 'Show Output') {\n outputChannel.show();\n } else if (action === 'Install wasm-opt') {\n vscode.commands.executeCommand(\n 'inference.installComponent',\n 'wasm-opt',\n );\n }\n });\n } else if (result.hasWarnings) {\n const actions = ['Show Output'];\n if (wasmOptNeedsAttention(result)) {\n actions.push('Install wasm-opt');\n }\n vscode.window\n .showWarningMessage(\n `Inference doctor: ${result.summary}`,\n ...actions,\n )\n .then((action) => {\n if (action === 'Show Output') {\n outputChannel.show();\n } else if (action === 'Install wasm-opt') {\n vscode.commands.executeCommand(\n 'inference.installComponent',\n 'wasm-opt',\n );\n }\n });\n } else {\n vscode.window.showInformationMessage(\n 'Inference: Toolchain is healthy.',\n );\n }\n } finally {\n running = false;\n }\n },\n );\n}\n\n", "import { DoctorResult } from './doctor';\n\nconst STATUS_TAGS: Record = {\n ok: '[OK] ',\n warn: '[WARN]',\n fail: '[FAIL]',\n};\n\n/**\n * Format doctor check results into display lines.\n *\n * Each check is formatted as: ` [TAG] name: message`\n * If a summary is present, it is appended after a blank line.\n * Separator lines wrap the output.\n */\nexport function formatDoctorChecks(result: DoctorResult): string[] {\n const lines: string[] = [];\n lines.push('--- Doctor Report ---');\n for (const check of result.checks) {\n const tag = STATUS_TAGS[check.status] ?? `[${check.status.toUpperCase()}]`;\n lines.push(` ${tag} ${check.name}: ${check.message}`);\n }\n if (result.summary) {\n lines.push('');\n lines.push(result.summary);\n }\n lines.push('---------------------');\n return lines;\n}\n", "import * as vscode from 'vscode';\nimport { detectInfs } from '../toolchain/detection';\nimport { fetchVersions, getCurrentVersion } from '../toolchain/versions';\nimport { buildVersionPickItems } from '../toolchain/versionPicker';\nimport { performVersionChange } from './versionChange';\n\n/** Guard against concurrent select operations. */\nlet selecting = false;\n\n/**\n * Register the inference.selectVersion command.\n * Shows a QuickPick with available toolchain versions and switches to the selected one.\n */\nexport function registerSelectVersionCommand(\n outputChannel: vscode.OutputChannel,\n): vscode.Disposable {\n return vscode.commands.registerCommand(\n 'inference.selectVersion',\n async () => {\n if (selecting) {\n vscode.window.showInformationMessage(\n 'Version selection is already in progress.',\n );\n return;\n }\n\n const detection = detectInfs();\n if (!detection) {\n vscode.window\n .showWarningMessage(\n 'Inference toolchain not found. Install it first.',\n 'Install',\n )\n .then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand(\n 'inference.installToolchain',\n );\n }\n });\n return;\n }\n\n selecting = true;\n try {\n const versions = await fetchVersions(detection.path);\n if (!versions) {\n vscode.window.showErrorMessage(\n 'Inference: Failed to fetch available versions.',\n );\n return;\n }\n\n const currentVersion = await getCurrentVersion(detection.path);\n\n const items = buildVersionPickItems(versions, currentVersion);\n\n if (items.length === 0) {\n vscode.window.showInformationMessage(\n 'No toolchain versions available for this platform.',\n );\n return;\n }\n\n const picked = await vscode.window.showQuickPick(items, {\n placeHolder: 'Select toolchain version',\n matchOnDescription: true,\n });\n\n if (!picked) {\n return;\n }\n\n const selectedVersion = picked.label;\n if (selectedVersion === currentVersion) {\n vscode.window.showInformationMessage(\n `Already using toolchain v${selectedVersion}.`,\n );\n return;\n }\n\n await performVersionChange(detection.path, selectedVersion, outputChannel, 'Switching to');\n } finally {\n selecting = false;\n }\n },\n );\n}\n", "import { exec } from '../utils/exec';\n\n/** Version info returned by `infs versions --json`. */\nexport interface VersionInfo {\n version: string;\n stable: boolean;\n platforms: string[];\n available_for_current: boolean;\n}\n\n/**\n * Parse the JSON output of `infs versions --json`.\n * Returns an empty array if the output is invalid.\n */\nexport function parseVersionsOutput(stdout: string): VersionInfo[] {\n try {\n const parsed = JSON.parse(stdout);\n if (!Array.isArray(parsed)) {\n return [];\n }\n return parsed;\n } catch {\n return [];\n }\n}\n\n/**\n * Parse the version string from `infs version` output.\n * Expected format: \"infs X.Y.Z\"\n * Returns the version string or null on parse failure.\n */\nexport function parseCurrentVersion(stdout: string): string | null {\n const match = stdout.match(/^infs\\s+(\\S+)/);\n return match ? match[1] : null;\n}\n\n/**\n * Run `infs versions --json` and parse the output.\n * Returns null if the command fails.\n */\nexport async function fetchVersions(\n infsPath: string,\n): Promise {\n try {\n const result = await exec(infsPath, ['versions', '--json'], {\n timeoutMs: 30_000,\n });\n if (result.exitCode !== 0) {\n return null;\n }\n return parseVersionsOutput(result.stdout);\n } catch {\n return null;\n }\n}\n\n/**\n * Run `infs version` and parse the current version.\n * Returns null if the command fails or the output is unexpected.\n */\nexport async function getCurrentVersion(\n infsPath: string,\n): Promise {\n try {\n const result = await exec(infsPath, ['version'], {\n timeoutMs: 10_000,\n });\n if (result.exitCode !== 0) {\n return null;\n }\n return parseCurrentVersion(result.stdout);\n } catch {\n return null;\n }\n}\n\n/** Result of an install-and-set-default operation. */\nexport interface SwitchResult {\n success: boolean;\n installedButNotDefault: boolean;\n error?: string;\n}\n\n/**\n * Install a toolchain version and set it as default.\n *\n * Runs `infs install VERSION` followed by `infs default VERSION`.\n * Handles the partial-success case where install succeeds but setting default fails.\n */\nexport async function installAndSetDefault(\n infsPath: string,\n version: string,\n): Promise {\n const installResult = await exec(infsPath, ['install', version], {\n timeoutMs: 120_000,\n });\n if (installResult.exitCode !== 0) {\n const detail = installResult.stderr || installResult.stdout;\n return { success: false, installedButNotDefault: false, error: detail };\n }\n\n const defaultResult = await exec(infsPath, ['default', version], {\n timeoutMs: 30_000,\n });\n if (defaultResult.exitCode !== 0) {\n const detail = defaultResult.stderr || defaultResult.stdout;\n return { success: false, installedButNotDefault: true, error: detail };\n }\n\n return { success: true, installedButNotDefault: false };\n}\n", "import { VersionInfo } from './versions';\nimport { compareSemver } from '../utils/semver';\n\nexport interface PickItem {\n label: string;\n description?: string;\n}\n\n/**\n * Build QuickPick items from available versions.\n *\n * - Filters to `available_for_current` versions only\n * - Sorts descending by semver\n * - Tags the current version with \"(current)\" and stable versions with \"(stable)\"\n * - Moves the current version to the top of the list\n */\nexport function buildVersionPickItems(\n versions: VersionInfo[],\n currentVersion: string | null,\n): PickItem[] {\n const available = versions\n .filter((v) => v.available_for_current)\n .sort((a, b) => compareSemver(b.version, a.version));\n\n const items: PickItem[] = available.map((v) => {\n const tags: string[] = [];\n if (v.version === currentVersion) {\n tags.push('current');\n }\n if (v.stable) {\n tags.push('stable');\n }\n return {\n label: v.version,\n description: tags.length > 0 ? `(${tags.join(', ')})` : undefined,\n };\n });\n\n if (currentVersion) {\n const idx = items.findIndex((i) => i.label === currentVersion);\n if (idx > 0) {\n const [item] = items.splice(idx, 1);\n items.unshift(item);\n }\n }\n\n return items;\n}\n", "import * as vscode from 'vscode';\nimport { installAndSetDefault } from '../toolchain/versions';\n\n/**\n * Perform a version change (install + set default) with progress UI.\n *\n * Shared by both the \"Select Version\" and \"Update Toolchain\" commands.\n */\nexport async function performVersionChange(\n infsPath: string,\n version: string,\n outputChannel: vscode.OutputChannel,\n actionVerb: string,\n): Promise {\n await vscode.window.withProgress(\n {\n location: vscode.ProgressLocation.Notification,\n title: 'Inference Toolchain',\n cancellable: false,\n },\n async (progress) => {\n progress.report({ message: `${actionVerb} v${version}...` });\n outputChannel.appendLine(`${actionVerb} toolchain v${version}...`);\n\n const result = await installAndSetDefault(infsPath, version);\n\n if (result.success) {\n outputChannel.appendLine(\n `${actionVerb} toolchain v${version} complete.`,\n );\n vscode.commands.executeCommand(\n 'setContext', 'inference.toolchainInstalled', true,\n );\n vscode.commands.executeCommand('inference.applyTerminalPath');\n vscode.commands.executeCommand('inference.runDoctor');\n vscode.window\n .showInformationMessage(\n `Inference toolchain ${actionVerb.toLowerCase()} to v${version}.`,\n 'Show Output',\n )\n .then((action) => {\n if (action === 'Show Output') {\n outputChannel.show();\n }\n });\n return;\n }\n\n outputChannel.appendLine(\n `${actionVerb} failed: ${result.error}`,\n );\n\n if (result.installedButNotDefault) {\n vscode.window\n .showWarningMessage(\n `Inference: v${version} was installed but could not be set as default. Run \\`infs default ${version}\\` manually.`,\n 'Show Output',\n )\n .then((action) => {\n if (action === 'Show Output') {\n outputChannel.show();\n }\n });\n } else {\n vscode.window.showErrorMessage(\n `Inference: Failed to install v${version}: ${result.error}`,\n );\n }\n },\n );\n}\n", "import * as vscode from 'vscode';\nimport { detectInfs } from '../toolchain/detection';\nimport { fetchVersions, getCurrentVersion } from '../toolchain/versions';\nimport { checkUpdateAvailable } from '../toolchain/updateCheck';\nimport { getSettings } from '../config/settings';\nimport { performVersionChange } from './versionChange';\n\n/** Guard against concurrent update operations. */\nlet updating = false;\n\n/**\n * Register the inference.updateToolchain command.\n * Checks for updates and prompts the user to install if available.\n */\nexport function registerUpdateCommand(\n outputChannel: vscode.OutputChannel,\n): vscode.Disposable {\n return vscode.commands.registerCommand(\n 'inference.updateToolchain',\n async () => {\n if (updating) {\n vscode.window.showInformationMessage(\n 'Update check is already in progress.',\n );\n return;\n }\n\n const detection = detectInfs();\n if (!detection) {\n vscode.window\n .showWarningMessage(\n 'Inference toolchain not found. Install it first.',\n 'Install',\n )\n .then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand(\n 'inference.installToolchain',\n );\n }\n });\n return;\n }\n\n updating = true;\n try {\n await checkForUpdatesImpl(detection.path, outputChannel, true);\n } finally {\n updating = false;\n }\n },\n );\n}\n\n/**\n * Check for toolchain updates on activation.\n * Respects the `inference.checkForUpdates` setting.\n * This is a no-op if checks are disabled.\n */\nexport async function checkForUpdates(\n infsPath: string,\n outputChannel: vscode.OutputChannel,\n): Promise {\n if (updating) {\n return;\n }\n const settings = getSettings();\n if (!settings.checkForUpdates) {\n return;\n }\n updating = true;\n try {\n await checkForUpdatesImpl(infsPath, outputChannel, false);\n } finally {\n updating = false;\n }\n}\n\nasync function checkForUpdatesImpl(\n infsPath: string,\n outputChannel: vscode.OutputChannel,\n userInitiated: boolean,\n): Promise {\n const currentVersion = await getCurrentVersion(infsPath);\n if (!currentVersion) {\n outputChannel.appendLine('Update check: could not determine current version.');\n if (userInitiated) {\n vscode.window.showErrorMessage(\n 'Inference: Could not determine the current toolchain version.',\n );\n }\n return;\n }\n\n outputChannel.appendLine(`Update check: current version is ${currentVersion}.`);\n\n const versions = await fetchVersions(infsPath);\n if (!versions) {\n outputChannel.appendLine('Update check: failed to fetch available versions.');\n if (userInitiated) {\n vscode.window.showErrorMessage(\n 'Inference: Failed to check for updates.',\n );\n }\n return;\n }\n\n const result = checkUpdateAvailable(currentVersion, versions);\n\n switch (result.status) {\n case 'no-current-version':\n outputChannel.appendLine('Update check: could not determine current version.');\n if (userInitiated) {\n vscode.window.showErrorMessage(\n 'Inference: Could not determine the current toolchain version.',\n );\n }\n return;\n\n case 'no-versions':\n outputChannel.appendLine('Update check: no versions available for this platform.');\n if (userInitiated) {\n vscode.window.showInformationMessage(\n 'Inference: No toolchain versions available for this platform.',\n );\n }\n return;\n\n case 'up-to-date':\n outputChannel.appendLine(\n `Update check: toolchain is up to date (v${result.version}).`,\n );\n if (userInitiated) {\n vscode.window.showInformationMessage(\n `Inference toolchain is up to date (v${result.version}).`,\n );\n }\n return;\n\n case 'update-available': {\n outputChannel.appendLine(\n `Update check: v${result.latest} available (current: v${result.current}).`,\n );\n\n const action = await vscode.window.showInformationMessage(\n `Inference toolchain update available: v${result.latest} (current: v${result.current})`,\n 'Update',\n 'Release Notes',\n );\n\n if (action === 'Update') {\n await performVersionChange(infsPath, result.latest, outputChannel, 'Updating to');\n } else if (action === 'Release Notes') {\n vscode.env.openExternal(\n vscode.Uri.parse(\n `https://github.com/Inferara/inference/releases/tag/v${result.latest}`,\n ),\n );\n }\n return;\n }\n }\n}\n", "import { VersionInfo } from './versions';\nimport { compareSemver } from '../utils/semver';\n\nexport type UpdateCheckResult =\n | { status: 'up-to-date'; version: string }\n | { status: 'update-available'; current: string; latest: string }\n | { status: 'no-versions' }\n | { status: 'no-current-version' };\n\n/**\n * Determine whether an update is available based on current version and available versions.\n *\n * Filters to `available_for_current` versions and compares the highest against current.\n */\nexport function checkUpdateAvailable(\n currentVersion: string | null,\n versions: VersionInfo[] | null,\n): UpdateCheckResult {\n if (!currentVersion) {\n return { status: 'no-current-version' };\n }\n\n if (!versions) {\n return { status: 'no-versions' };\n }\n\n const candidates = versions.filter((v) => v.available_for_current);\n\n if (candidates.length === 0) {\n return { status: 'no-versions' };\n }\n\n const sorted = [...candidates].sort((a, b) =>\n compareSemver(b.version, a.version),\n );\n const latest = sorted[0];\n\n if (compareSemver(currentVersion, latest.version) >= 0) {\n return { status: 'up-to-date', version: currentVersion };\n }\n\n return {\n status: 'update-available',\n current: currentVersion,\n latest: latest.version,\n };\n}\n", "import * as vscode from 'vscode';\nimport { detectInfs, InfsDetection } from '../toolchain/detection';\nimport { inferenceHome } from '../toolchain/home';\nimport { detectPlatform } from '../toolchain/platform';\nimport { getSettings } from '../config/settings';\nimport { exec } from '../utils/exec';\nimport { DoctorResult } from '../toolchain/doctor';\n\ntype GroupId = 'toolchain' | 'settings';\n\nexport class ConfigItem extends vscode.TreeItem {\n constructor(\n label: string,\n public readonly kind: 'group' | 'property',\n collapsible: vscode.TreeItemCollapsibleState,\n public readonly groupId?: GroupId,\n public readonly settingKey?: string,\n public readonly copyValue?: string,\n ) {\n super(label, collapsible);\n\n if (kind === 'group') {\n this.iconPath = new vscode.ThemeIcon(\n groupId === 'toolchain' ? 'tools' : 'gear',\n );\n }\n\n if (settingKey) {\n this.command = {\n title: 'Open Setting',\n command: 'workbench.action.openSettings',\n arguments: [settingKey],\n };\n }\n\n if (copyValue) {\n this.contextValue = 'inference.configPath';\n }\n }\n}\n\nexport class InferenceConfigProvider\n implements vscode.TreeDataProvider\n{\n private _onDidChangeTreeData = new vscode.EventEmitter<\n ConfigItem | undefined | null\n >();\n readonly onDidChangeTreeData = this._onDidChangeTreeData.event;\n\n private detection: InfsDetection | null = null;\n private version: string | null = null;\n private doctorResult: DoctorResult | null = null;\n\n refresh(detection?: InfsDetection | null, doctorResult?: DoctorResult | null): void {\n if (detection !== undefined) {\n this.detection = detection;\n }\n if (doctorResult !== undefined) {\n this.doctorResult = doctorResult;\n }\n this._onDidChangeTreeData.fire(undefined);\n }\n\n getTreeItem(element: ConfigItem): vscode.TreeItem {\n return element;\n }\n\n async getChildren(element?: ConfigItem): Promise {\n if (!element) {\n return [\n new ConfigItem(\n 'Toolchain',\n 'group',\n vscode.TreeItemCollapsibleState.Expanded,\n 'toolchain',\n ),\n new ConfigItem(\n 'Settings',\n 'group',\n vscode.TreeItemCollapsibleState.Expanded,\n 'settings',\n ),\n ];\n }\n\n if (element.groupId === 'toolchain') {\n return this.getToolchainChildren();\n }\n\n if (element.groupId === 'settings') {\n return this.getSettingsChildren();\n }\n\n return [];\n }\n\n private async getToolchainChildren(): Promise {\n const detection = this.detection ?? detectInfs();\n const items: ConfigItem[] = [];\n\n if (!detection) {\n const item = new ConfigItem(\n 'infs: not found',\n 'property',\n vscode.TreeItemCollapsibleState.None,\n );\n item.iconPath = new vscode.ThemeIcon('error');\n item.command = {\n title: 'Install Toolchain',\n command: 'inference.installToolchain',\n arguments: [],\n };\n items.push(item);\n return items;\n }\n\n const infsItem = new ConfigItem(\n `infs: ${detection.path} (${detection.source})`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n undefined,\n undefined,\n detection.path,\n );\n infsItem.iconPath = new vscode.ThemeIcon('file-binary');\n items.push(infsItem);\n\n const version = await this.resolveVersion(detection.path);\n const versionItem = new ConfigItem(\n `Version: ${version ?? 'unknown'}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n );\n versionItem.iconPath = new vscode.ThemeIcon('tag');\n items.push(versionItem);\n\n const home = inferenceHome();\n const homeIsDefault = !process.env['INFERENCE_HOME'];\n const homeItem = new ConfigItem(\n `Home: ${home} (${homeIsDefault ? 'default' : 'env'})`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n undefined,\n undefined,\n home,\n );\n homeItem.iconPath = new vscode.ThemeIcon('home');\n items.push(homeItem);\n\n const platform = detectPlatform();\n const platformItem = new ConfigItem(\n `Platform: ${platform?.id ?? 'unknown'}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n );\n platformItem.iconPath = new vscode.ThemeIcon('device-desktop');\n items.push(platformItem);\n\n const status = this.doctorResult\n ? this.doctorResult.hasErrors\n ? 'errors'\n : this.doctorResult.hasWarnings\n ? 'warnings'\n : 'healthy'\n : 'unknown';\n const statusIcon = this.doctorResult\n ? this.doctorResult.hasErrors\n ? 'error'\n : this.doctorResult.hasWarnings\n ? 'warning'\n : 'pass'\n : 'question';\n const statusItem = new ConfigItem(\n `Status: ${status}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n );\n statusItem.iconPath = new vscode.ThemeIcon(statusIcon);\n statusItem.command = {\n title: 'Run Doctor',\n command: 'inference.runDoctor',\n arguments: [],\n };\n items.push(statusItem);\n\n return items;\n }\n\n private getSettingsChildren(): ConfigItem[] {\n const settings = getSettings();\n\n const pathItem = new ConfigItem(\n `Path: ${settings.path || '(auto-detect)'}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n undefined,\n 'inference.path',\n );\n pathItem.iconPath = new vscode.ThemeIcon('file-symlink-directory');\n\n const autoInstallItem = new ConfigItem(\n `Auto Install: ${settings.autoInstall ? 'enabled' : 'disabled'}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n undefined,\n 'inference.autoInstall',\n );\n autoInstallItem.iconPath = new vscode.ThemeIcon('cloud-download');\n\n const updateItem = new ConfigItem(\n `Check for Updates: ${settings.checkForUpdates ? 'enabled' : 'disabled'}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n undefined,\n 'inference.checkForUpdates',\n );\n updateItem.iconPath = new vscode.ThemeIcon('sync');\n\n return [pathItem, autoInstallItem, updateItem];\n }\n\n private async resolveVersion(infsPath: string): Promise {\n if (this.version) {\n return this.version;\n }\n try {\n const result = await exec(infsPath, ['version']);\n if (result.exitCode !== 0) {\n return null;\n }\n const match = result.stdout.match(/^infs\\s+(\\S+)/);\n if (match) {\n this.version = match[1];\n return this.version;\n }\n return null;\n } catch {\n return null;\n }\n }\n\n dispose(): void {\n this._onDidChangeTreeData.dispose();\n }\n}\n"], - "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIO,SAAS,gBAAwB;AACpC,SAAO,QAAQ,IA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AO,EAAE;AAE7C,QAAI,cAAc,SAAS,gBAAgB,IAAI,GAAG;AAC9C,oBAAc;AAAA,QACV,gBAAgB,OAAO,qBAAqB,gBAAgB;AAAA,MAChE;AACA,MAAO,gBACF;AAAA,QACG,2BAA2B,OAAO,0BAA0B,gBAAgB;AAAA,QAC5E;AAAA,MACJ,EACC,KAAK,CAAC,WAAW;AACd,YAAI,WAAW,UAAU;AACrB,UAAO,kBAAS,eAAe,2BAA2B;AAAA,QAC9D;AAAA,MACJ,CAAC;AACL,aAAO;AAAA,IACX;AACA,WAAO;AAAA,EACX,SAAS,KAAK;AACV,kBAAc,MAAM,+BAA+B,GAAG,EAAE;AACxD,WAAO;AAAA,EACX;AACJ;AAEA,SAAS,gBAAsB;AAC3B,EAAO,gBACF;AAAA,IACG;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ,EACC,KAAK,CAAC,WAAW;AACd,QAAI,WAAW,WAAW;AACtB,MAAO,kBAAS,eAAe,4BAA4B;AAAA,IAC/D,WAAW,WAAW,qBAAqB;AACvC,MAAO,aAAI;AAAA,QACA,aAAI;AAAA,UACP;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ,WAAW,WAAW,kBAAkB;AACpC,MAAO,kBAAS;AAAA,QACZ;AAAA,QACA;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ,CAAC;AACT;", - "names": ["os", "path", "vscode", "path", "path", "platform", "vscode", "fs", "os", "path", "fs", "DEFAULT_TIMEOUT_MS", "fs", "path", "platform", "os", "platform", "parseDoctorOutput", "vscode", "outputChannel", "platform", "vscode", "installing", "outputChannel", "installWithProgress", "notifyInstallError", "vscode", "outputChannel", "vscode", "vscode", "outputChannel", "outputChannel", "vscode", "outputChannel", "vscode", "platform", "env", "platform"] + "sources": ["../src/toolchain/home.ts", "../src/utils/exec.ts", "../src/toolchain/doctor.ts", "../node_modules/vscode-languageclient/lib/common/utils/is.js", "../node_modules/vscode-jsonrpc/lib/common/is.js", "../node_modules/vscode-jsonrpc/lib/common/messages.js", "../node_modules/vscode-jsonrpc/lib/common/linkedMap.js", "../node_modules/vscode-jsonrpc/lib/common/disposable.js", "../node_modules/vscode-jsonrpc/lib/common/ral.js", "../node_modules/vscode-jsonrpc/lib/common/events.js", "../node_modules/vscode-jsonrpc/lib/common/cancellation.js", "../node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js", "../node_modules/vscode-jsonrpc/lib/common/semaphore.js", "../node_modules/vscode-jsonrpc/lib/common/messageReader.js", "../node_modules/vscode-jsonrpc/lib/common/messageWriter.js", "../node_modules/vscode-jsonrpc/lib/common/messageBuffer.js", "../node_modules/vscode-jsonrpc/lib/common/connection.js", "../node_modules/vscode-jsonrpc/lib/common/api.js", "../node_modules/vscode-jsonrpc/lib/node/ril.js", "../node_modules/vscode-jsonrpc/lib/node/main.js", "../node_modules/vscode-jsonrpc/node.js", "../node_modules/vscode-languageserver-types/lib/umd/main.js", "../node_modules/vscode-languageserver-protocol/lib/common/messages.js", "../node_modules/vscode-languageserver-protocol/lib/common/utils/is.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolder.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.typeHierarchy.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineValue.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.inlayHint.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.diagnostic.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.notebook.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineCompletion.js", "../node_modules/vscode-languageserver-protocol/lib/common/protocol.js", "../node_modules/vscode-languageserver-protocol/lib/common/connection.js", "../node_modules/vscode-languageserver-protocol/lib/common/api.js", "../node_modules/vscode-languageserver-protocol/lib/node/main.js", "../node_modules/vscode-languageclient/lib/common/utils/async.js", "../node_modules/vscode-languageclient/lib/common/protocolCompletionItem.js", "../node_modules/vscode-languageclient/lib/common/protocolCodeLens.js", "../node_modules/vscode-languageclient/lib/common/protocolDocumentLink.js", "../node_modules/vscode-languageclient/lib/common/protocolCodeAction.js", "../node_modules/vscode-languageclient/lib/common/protocolDiagnostic.js", "../node_modules/vscode-languageclient/lib/common/protocolCallHierarchyItem.js", "../node_modules/vscode-languageclient/lib/common/protocolTypeHierarchyItem.js", "../node_modules/vscode-languageclient/lib/common/protocolWorkspaceSymbol.js", "../node_modules/vscode-languageclient/lib/common/protocolInlayHint.js", "../node_modules/vscode-languageclient/lib/common/codeConverter.js", "../node_modules/vscode-languageclient/lib/common/protocolConverter.js", "../node_modules/vscode-languageclient/lib/common/utils/uuid.js", "../node_modules/vscode-languageclient/lib/common/progressPart.js", "../node_modules/vscode-languageclient/lib/common/features.js", "../node_modules/vscode-languageclient/node_modules/minimatch/lib/path.js", "../node_modules/vscode-languageclient/node_modules/balanced-match/index.js", "../node_modules/vscode-languageclient/node_modules/brace-expansion/index.js", "../node_modules/vscode-languageclient/node_modules/minimatch/minimatch.js", "../node_modules/vscode-languageclient/lib/common/diagnostic.js", "../node_modules/vscode-languageclient/lib/common/notebook.js", "../node_modules/vscode-languageclient/lib/common/configuration.js", "../node_modules/vscode-languageclient/lib/common/textSynchronization.js", "../node_modules/vscode-languageclient/lib/common/completion.js", "../node_modules/vscode-languageclient/lib/common/hover.js", "../node_modules/vscode-languageclient/lib/common/definition.js", "../node_modules/vscode-languageclient/lib/common/signatureHelp.js", "../node_modules/vscode-languageclient/lib/common/documentHighlight.js", "../node_modules/vscode-languageclient/lib/common/documentSymbol.js", "../node_modules/vscode-languageclient/lib/common/workspaceSymbol.js", "../node_modules/vscode-languageclient/lib/common/reference.js", "../node_modules/vscode-languageclient/lib/common/codeAction.js", "../node_modules/vscode-languageclient/lib/common/codeLens.js", "../node_modules/vscode-languageclient/lib/common/formatting.js", "../node_modules/vscode-languageclient/lib/common/rename.js", "../node_modules/vscode-languageclient/lib/common/documentLink.js", "../node_modules/vscode-languageclient/lib/common/executeCommand.js", "../node_modules/vscode-languageclient/lib/common/fileSystemWatcher.js", "../node_modules/vscode-languageclient/lib/common/colorProvider.js", "../node_modules/vscode-languageclient/lib/common/implementation.js", "../node_modules/vscode-languageclient/lib/common/typeDefinition.js", "../node_modules/vscode-languageclient/lib/common/workspaceFolder.js", "../node_modules/vscode-languageclient/lib/common/foldingRange.js", "../node_modules/vscode-languageclient/lib/common/declaration.js", "../node_modules/vscode-languageclient/lib/common/selectionRange.js", "../node_modules/vscode-languageclient/lib/common/progress.js", "../node_modules/vscode-languageclient/lib/common/callHierarchy.js", "../node_modules/vscode-languageclient/lib/common/semanticTokens.js", "../node_modules/vscode-languageclient/lib/common/fileOperations.js", "../node_modules/vscode-languageclient/lib/common/linkedEditingRange.js", "../node_modules/vscode-languageclient/lib/common/typeHierarchy.js", "../node_modules/vscode-languageclient/lib/common/inlineValue.js", "../node_modules/vscode-languageclient/lib/common/inlayHint.js", "../node_modules/vscode-languageclient/lib/common/inlineCompletion.js", "../node_modules/vscode-languageclient/lib/common/client.js", "../node_modules/vscode-languageclient/lib/node/processes.js", "../node_modules/vscode-languageserver-protocol/node.js", "../node_modules/semver/internal/debug.js", "../node_modules/semver/internal/constants.js", "../node_modules/semver/internal/re.js", "../node_modules/semver/internal/parse-options.js", "../node_modules/semver/internal/identifiers.js", "../node_modules/semver/classes/semver.js", "../node_modules/semver/functions/parse.js", "../node_modules/semver/internal/lrucache.js", "../node_modules/semver/functions/compare.js", "../node_modules/semver/functions/eq.js", "../node_modules/semver/functions/neq.js", "../node_modules/semver/functions/gt.js", "../node_modules/semver/functions/gte.js", "../node_modules/semver/functions/lt.js", "../node_modules/semver/functions/lte.js", "../node_modules/semver/functions/cmp.js", "../node_modules/semver/classes/comparator.js", "../node_modules/semver/classes/range.js", "../node_modules/semver/functions/satisfies.js", "../node_modules/vscode-languageclient/lib/common/api.js", "../node_modules/vscode-languageclient/lib/node/main.js", "../node_modules/vscode-languageclient/node.js", "../src/extension.ts", "../src/toolchain/platform.ts", "../src/toolchain/detection.ts", "../src/config/settings.ts", "../src/utils/semver.ts", "../src/commands/install.ts", "../src/toolchain/installation.ts", "../src/utils/download.ts", "../src/utils/extract.ts", "../src/toolchain/manifest.ts", "../src/ui/statusBar.ts", "../src/ui/statusBarState.ts", "../src/lsp/client.ts", "../src/lsp/resolve.ts", "../src/commands/installComponent.ts", "../src/toolchain/components.ts", "../src/commands/doctor.ts", "../src/toolchain/doctorFormat.ts", "../src/commands/selectVersion.ts", "../src/toolchain/versions.ts", "../src/toolchain/versionPicker.ts", "../src/commands/versionChange.ts", "../src/commands/update.ts", "../src/toolchain/updateCheck.ts", "../src/ui/configTree.ts"], + "sourcesContent": ["import * as os from 'os';\nimport * as path from 'path';\n\n/** Resolve the INFERENCE_HOME directory (default: ~/.inference). */\nexport function inferenceHome(): string {\n return process.env['INFERENCE_HOME'] || path.join(os.homedir(), '.inference');\n}\n", "import * as cp from 'child_process';\n\nexport interface ExecResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/** Default timeout for child processes (30 seconds). */\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * Run a command and capture its output.\n *\n * Resolves with ExecResult on completion (including non-zero exit).\n * Rejects only on spawn failure or timeout.\n */\nexport function exec(\n command: string,\n args: string[],\n options?: { timeoutMs?: number; cwd?: string; env?: Record },\n): Promise {\n const timeout = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n return new Promise((resolve, reject) => {\n const child = cp.spawn(command, args, {\n cwd: options?.cwd,\n env: options?.env ? { ...process.env, ...options.env } : undefined,\n stdio: ['ignore', 'pipe', 'pipe'],\n timeout,\n });\n\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n\n child.stdout.on('data', (chunk: Buffer) => stdoutChunks.push(chunk));\n child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk));\n\n child.on('error', (err) => reject(err));\n\n child.on('close', (code) => {\n resolve({\n exitCode: code ?? 1,\n stdout: Buffer.concat(stdoutChunks).toString('utf-8'),\n stderr: Buffer.concat(stderrChunks).toString('utf-8'),\n });\n });\n });\n}\n", "import * as path from 'path';\nimport { exec } from '../utils/exec';\nimport { inferenceHome } from './home';\n\nexport type DoctorCheckStatus = 'ok' | 'warn' | 'fail';\n\nexport interface DoctorCheck {\n name: string;\n status: DoctorCheckStatus;\n message: string;\n}\n\nexport interface DoctorResult {\n checks: DoctorCheck[];\n hasErrors: boolean;\n hasWarnings: boolean;\n summary: string;\n}\n\nconst STATUS_MAP: Record = {\n OK: 'ok',\n WARN: 'warn',\n FAIL: 'fail',\n};\n\n/**\n * Check line format: ` [OK|WARN|FAIL] : `\n *\n * PATH conflict continuation lines (indented without a status prefix)\n * are intentionally not captured as individual checks.\n */\nconst CHECK_PATTERN = /^\\s+\\[(OK|WARN|FAIL)]\\s+(.+?):\\s+(.*)/;\n\n/**\n * Parse the stdout of `infs doctor` into a structured result.\n *\n * The output format is a public contract defined in\n * `apps/infs/src/commands/doctor.rs`.\n */\nexport function parseDoctorOutput(stdout: string): DoctorResult {\n const checks: DoctorCheck[] = [];\n const lines = stdout.split(/\\r?\\n/);\n\n for (const line of lines) {\n const match = line.match(CHECK_PATTERN);\n if (match) {\n checks.push({\n status: STATUS_MAP[match[1]],\n name: match[2].trim(),\n message: match[3].trim(),\n });\n }\n }\n\n let summary = '';\n for (let i = lines.length - 1; i >= 0; i--) {\n const trimmed = lines[i].trim();\n if (trimmed.length > 0 && !CHECK_PATTERN.test(lines[i])) {\n summary = trimmed;\n break;\n }\n }\n\n return {\n checks,\n hasErrors: checks.some((c) => c.status === 'fail'),\n hasWarnings: checks.some((c) => c.status === 'warn'),\n summary,\n };\n}\n\n/**\n * Execute `infs doctor` and return the parsed result.\n * Returns null if execution fails (e.g., binary not found or crash).\n */\nexport async function runDoctor(\n infsPath: string,\n): Promise {\n try {\n const binDir = path.join(inferenceHome(), 'bin');\n const sep = process.platform === 'win32' ? ';' : ':';\n const augmentedPath = `${binDir}${sep}${process.env['PATH'] ?? ''}`;\n\n const result = await exec(infsPath, ['doctor'], {\n env: { PATH: augmentedPath },\n });\n return parseDoctorOutput(result.stdout);\n } catch (err) {\n console.error('infs doctor failed:', err);\n return null;\n }\n}\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.asPromise = exports.thenable = exports.typedArray = exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;\nfunction boolean(value) {\n return value === true || value === false;\n}\nexports.boolean = boolean;\nfunction string(value) {\n return typeof value === 'string' || value instanceof String;\n}\nexports.string = string;\nfunction number(value) {\n return typeof value === 'number' || value instanceof Number;\n}\nexports.number = number;\nfunction error(value) {\n return value instanceof Error;\n}\nexports.error = error;\nfunction func(value) {\n return typeof value === 'function';\n}\nexports.func = func;\nfunction array(value) {\n return Array.isArray(value);\n}\nexports.array = array;\nfunction stringArray(value) {\n return array(value) && value.every(elem => string(elem));\n}\nexports.stringArray = stringArray;\nfunction typedArray(value, check) {\n return Array.isArray(value) && value.every(check);\n}\nexports.typedArray = typedArray;\nfunction thenable(value) {\n return value && func(value.then);\n}\nexports.thenable = thenable;\nfunction asPromise(value) {\n if (value instanceof Promise) {\n return value;\n }\n else if (thenable(value)) {\n return new Promise((resolve, reject) => {\n value.then((resolved) => resolve(resolved), (error) => reject(error));\n });\n }\n else {\n return Promise.resolve(value);\n }\n}\nexports.asPromise = asPromise;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;\nfunction boolean(value) {\n return value === true || value === false;\n}\nexports.boolean = boolean;\nfunction string(value) {\n return typeof value === 'string' || value instanceof String;\n}\nexports.string = string;\nfunction number(value) {\n return typeof value === 'number' || value instanceof Number;\n}\nexports.number = number;\nfunction error(value) {\n return value instanceof Error;\n}\nexports.error = error;\nfunction func(value) {\n return typeof value === 'function';\n}\nexports.func = func;\nfunction array(value) {\n return Array.isArray(value);\n}\nexports.array = array;\nfunction stringArray(value) {\n return array(value) && value.every(elem => string(elem));\n}\nexports.stringArray = stringArray;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Message = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType = exports.RequestType0 = exports.AbstractMessageSignature = exports.ParameterStructures = exports.ResponseError = exports.ErrorCodes = void 0;\nconst is = require(\"./is\");\n/**\n * Predefined error codes.\n */\nvar ErrorCodes;\n(function (ErrorCodes) {\n // Defined by JSON RPC\n ErrorCodes.ParseError = -32700;\n ErrorCodes.InvalidRequest = -32600;\n ErrorCodes.MethodNotFound = -32601;\n ErrorCodes.InvalidParams = -32602;\n ErrorCodes.InternalError = -32603;\n /**\n * This is the start range of JSON RPC reserved error codes.\n * It doesn't denote a real error code. No application error codes should\n * be defined between the start and end range. For backwards\n * compatibility the `ServerNotInitialized` and the `UnknownErrorCode`\n * are left in the range.\n *\n * @since 3.16.0\n */\n ErrorCodes.jsonrpcReservedErrorRangeStart = -32099;\n /** @deprecated use jsonrpcReservedErrorRangeStart */\n ErrorCodes.serverErrorStart = -32099;\n /**\n * An error occurred when write a message to the transport layer.\n */\n ErrorCodes.MessageWriteError = -32099;\n /**\n * An error occurred when reading a message from the transport layer.\n */\n ErrorCodes.MessageReadError = -32098;\n /**\n * The connection got disposed or lost and all pending responses got\n * rejected.\n */\n ErrorCodes.PendingResponseRejected = -32097;\n /**\n * The connection is inactive and a use of it failed.\n */\n ErrorCodes.ConnectionInactive = -32096;\n /**\n * Error code indicating that a server received a notification or\n * request before the server has received the `initialize` request.\n */\n ErrorCodes.ServerNotInitialized = -32002;\n ErrorCodes.UnknownErrorCode = -32001;\n /**\n * This is the end range of JSON RPC reserved error codes.\n * It doesn't denote a real error code.\n *\n * @since 3.16.0\n */\n ErrorCodes.jsonrpcReservedErrorRangeEnd = -32000;\n /** @deprecated use jsonrpcReservedErrorRangeEnd */\n ErrorCodes.serverErrorEnd = -32000;\n})(ErrorCodes || (exports.ErrorCodes = ErrorCodes = {}));\n/**\n * An error object return in a response in case a request\n * has failed.\n */\nclass ResponseError extends Error {\n constructor(code, message, data) {\n super(message);\n this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;\n this.data = data;\n Object.setPrototypeOf(this, ResponseError.prototype);\n }\n toJson() {\n const result = {\n code: this.code,\n message: this.message\n };\n if (this.data !== undefined) {\n result.data = this.data;\n }\n return result;\n }\n}\nexports.ResponseError = ResponseError;\nclass ParameterStructures {\n constructor(kind) {\n this.kind = kind;\n }\n static is(value) {\n return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition;\n }\n toString() {\n return this.kind;\n }\n}\nexports.ParameterStructures = ParameterStructures;\n/**\n * The parameter structure is automatically inferred on the number of parameters\n * and the parameter type in case of a single param.\n */\nParameterStructures.auto = new ParameterStructures('auto');\n/**\n * Forces `byPosition` parameter structure. This is useful if you have a single\n * parameter which has a literal type.\n */\nParameterStructures.byPosition = new ParameterStructures('byPosition');\n/**\n * Forces `byName` parameter structure. This is only useful when having a single\n * parameter. The library will report errors if used with a different number of\n * parameters.\n */\nParameterStructures.byName = new ParameterStructures('byName');\n/**\n * An abstract implementation of a MessageType.\n */\nclass AbstractMessageSignature {\n constructor(method, numberOfParams) {\n this.method = method;\n this.numberOfParams = numberOfParams;\n }\n get parameterStructures() {\n return ParameterStructures.auto;\n }\n}\nexports.AbstractMessageSignature = AbstractMessageSignature;\n/**\n * Classes to type request response pairs\n */\nclass RequestType0 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 0);\n }\n}\nexports.RequestType0 = RequestType0;\nclass RequestType extends AbstractMessageSignature {\n constructor(method, _parameterStructures = ParameterStructures.auto) {\n super(method, 1);\n this._parameterStructures = _parameterStructures;\n }\n get parameterStructures() {\n return this._parameterStructures;\n }\n}\nexports.RequestType = RequestType;\nclass RequestType1 extends AbstractMessageSignature {\n constructor(method, _parameterStructures = ParameterStructures.auto) {\n super(method, 1);\n this._parameterStructures = _parameterStructures;\n }\n get parameterStructures() {\n return this._parameterStructures;\n }\n}\nexports.RequestType1 = RequestType1;\nclass RequestType2 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 2);\n }\n}\nexports.RequestType2 = RequestType2;\nclass RequestType3 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 3);\n }\n}\nexports.RequestType3 = RequestType3;\nclass RequestType4 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 4);\n }\n}\nexports.RequestType4 = RequestType4;\nclass RequestType5 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 5);\n }\n}\nexports.RequestType5 = RequestType5;\nclass RequestType6 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 6);\n }\n}\nexports.RequestType6 = RequestType6;\nclass RequestType7 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 7);\n }\n}\nexports.RequestType7 = RequestType7;\nclass RequestType8 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 8);\n }\n}\nexports.RequestType8 = RequestType8;\nclass RequestType9 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 9);\n }\n}\nexports.RequestType9 = RequestType9;\nclass NotificationType extends AbstractMessageSignature {\n constructor(method, _parameterStructures = ParameterStructures.auto) {\n super(method, 1);\n this._parameterStructures = _parameterStructures;\n }\n get parameterStructures() {\n return this._parameterStructures;\n }\n}\nexports.NotificationType = NotificationType;\nclass NotificationType0 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 0);\n }\n}\nexports.NotificationType0 = NotificationType0;\nclass NotificationType1 extends AbstractMessageSignature {\n constructor(method, _parameterStructures = ParameterStructures.auto) {\n super(method, 1);\n this._parameterStructures = _parameterStructures;\n }\n get parameterStructures() {\n return this._parameterStructures;\n }\n}\nexports.NotificationType1 = NotificationType1;\nclass NotificationType2 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 2);\n }\n}\nexports.NotificationType2 = NotificationType2;\nclass NotificationType3 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 3);\n }\n}\nexports.NotificationType3 = NotificationType3;\nclass NotificationType4 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 4);\n }\n}\nexports.NotificationType4 = NotificationType4;\nclass NotificationType5 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 5);\n }\n}\nexports.NotificationType5 = NotificationType5;\nclass NotificationType6 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 6);\n }\n}\nexports.NotificationType6 = NotificationType6;\nclass NotificationType7 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 7);\n }\n}\nexports.NotificationType7 = NotificationType7;\nclass NotificationType8 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 8);\n }\n}\nexports.NotificationType8 = NotificationType8;\nclass NotificationType9 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 9);\n }\n}\nexports.NotificationType9 = NotificationType9;\nvar Message;\n(function (Message) {\n /**\n * Tests if the given message is a request message\n */\n function isRequest(message) {\n const candidate = message;\n return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));\n }\n Message.isRequest = isRequest;\n /**\n * Tests if the given message is a notification message\n */\n function isNotification(message) {\n const candidate = message;\n return candidate && is.string(candidate.method) && message.id === void 0;\n }\n Message.isNotification = isNotification;\n /**\n * Tests if the given message is a response message\n */\n function isResponse(message) {\n const candidate = message;\n return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);\n }\n Message.isResponse = isResponse;\n})(Message || (exports.Message = Message = {}));\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar _a;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LRUCache = exports.LinkedMap = exports.Touch = void 0;\nvar Touch;\n(function (Touch) {\n Touch.None = 0;\n Touch.First = 1;\n Touch.AsOld = Touch.First;\n Touch.Last = 2;\n Touch.AsNew = Touch.Last;\n})(Touch || (exports.Touch = Touch = {}));\nclass LinkedMap {\n constructor() {\n this[_a] = 'LinkedMap';\n this._map = new Map();\n this._head = undefined;\n this._tail = undefined;\n this._size = 0;\n this._state = 0;\n }\n clear() {\n this._map.clear();\n this._head = undefined;\n this._tail = undefined;\n this._size = 0;\n this._state++;\n }\n isEmpty() {\n return !this._head && !this._tail;\n }\n get size() {\n return this._size;\n }\n get first() {\n return this._head?.value;\n }\n get last() {\n return this._tail?.value;\n }\n has(key) {\n return this._map.has(key);\n }\n get(key, touch = Touch.None) {\n const item = this._map.get(key);\n if (!item) {\n return undefined;\n }\n if (touch !== Touch.None) {\n this.touch(item, touch);\n }\n return item.value;\n }\n set(key, value, touch = Touch.None) {\n let item = this._map.get(key);\n if (item) {\n item.value = value;\n if (touch !== Touch.None) {\n this.touch(item, touch);\n }\n }\n else {\n item = { key, value, next: undefined, previous: undefined };\n switch (touch) {\n case Touch.None:\n this.addItemLast(item);\n break;\n case Touch.First:\n this.addItemFirst(item);\n break;\n case Touch.Last:\n this.addItemLast(item);\n break;\n default:\n this.addItemLast(item);\n break;\n }\n this._map.set(key, item);\n this._size++;\n }\n return this;\n }\n delete(key) {\n return !!this.remove(key);\n }\n remove(key) {\n const item = this._map.get(key);\n if (!item) {\n return undefined;\n }\n this._map.delete(key);\n this.removeItem(item);\n this._size--;\n return item.value;\n }\n shift() {\n if (!this._head && !this._tail) {\n return undefined;\n }\n if (!this._head || !this._tail) {\n throw new Error('Invalid list');\n }\n const item = this._head;\n this._map.delete(item.key);\n this.removeItem(item);\n this._size--;\n return item.value;\n }\n forEach(callbackfn, thisArg) {\n const state = this._state;\n let current = this._head;\n while (current) {\n if (thisArg) {\n callbackfn.bind(thisArg)(current.value, current.key, this);\n }\n else {\n callbackfn(current.value, current.key, this);\n }\n if (this._state !== state) {\n throw new Error(`LinkedMap got modified during iteration.`);\n }\n current = current.next;\n }\n }\n keys() {\n const state = this._state;\n let current = this._head;\n const iterator = {\n [Symbol.iterator]: () => {\n return iterator;\n },\n next: () => {\n if (this._state !== state) {\n throw new Error(`LinkedMap got modified during iteration.`);\n }\n if (current) {\n const result = { value: current.key, done: false };\n current = current.next;\n return result;\n }\n else {\n return { value: undefined, done: true };\n }\n }\n };\n return iterator;\n }\n values() {\n const state = this._state;\n let current = this._head;\n const iterator = {\n [Symbol.iterator]: () => {\n return iterator;\n },\n next: () => {\n if (this._state !== state) {\n throw new Error(`LinkedMap got modified during iteration.`);\n }\n if (current) {\n const result = { value: current.value, done: false };\n current = current.next;\n return result;\n }\n else {\n return { value: undefined, done: true };\n }\n }\n };\n return iterator;\n }\n entries() {\n const state = this._state;\n let current = this._head;\n const iterator = {\n [Symbol.iterator]: () => {\n return iterator;\n },\n next: () => {\n if (this._state !== state) {\n throw new Error(`LinkedMap got modified during iteration.`);\n }\n if (current) {\n const result = { value: [current.key, current.value], done: false };\n current = current.next;\n return result;\n }\n else {\n return { value: undefined, done: true };\n }\n }\n };\n return iterator;\n }\n [(_a = Symbol.toStringTag, Symbol.iterator)]() {\n return this.entries();\n }\n trimOld(newSize) {\n if (newSize >= this.size) {\n return;\n }\n if (newSize === 0) {\n this.clear();\n return;\n }\n let current = this._head;\n let currentSize = this.size;\n while (current && currentSize > newSize) {\n this._map.delete(current.key);\n current = current.next;\n currentSize--;\n }\n this._head = current;\n this._size = currentSize;\n if (current) {\n current.previous = undefined;\n }\n this._state++;\n }\n addItemFirst(item) {\n // First time Insert\n if (!this._head && !this._tail) {\n this._tail = item;\n }\n else if (!this._head) {\n throw new Error('Invalid list');\n }\n else {\n item.next = this._head;\n this._head.previous = item;\n }\n this._head = item;\n this._state++;\n }\n addItemLast(item) {\n // First time Insert\n if (!this._head && !this._tail) {\n this._head = item;\n }\n else if (!this._tail) {\n throw new Error('Invalid list');\n }\n else {\n item.previous = this._tail;\n this._tail.next = item;\n }\n this._tail = item;\n this._state++;\n }\n removeItem(item) {\n if (item === this._head && item === this._tail) {\n this._head = undefined;\n this._tail = undefined;\n }\n else if (item === this._head) {\n // This can only happened if size === 1 which is handle\n // by the case above.\n if (!item.next) {\n throw new Error('Invalid list');\n }\n item.next.previous = undefined;\n this._head = item.next;\n }\n else if (item === this._tail) {\n // This can only happened if size === 1 which is handle\n // by the case above.\n if (!item.previous) {\n throw new Error('Invalid list');\n }\n item.previous.next = undefined;\n this._tail = item.previous;\n }\n else {\n const next = item.next;\n const previous = item.previous;\n if (!next || !previous) {\n throw new Error('Invalid list');\n }\n next.previous = previous;\n previous.next = next;\n }\n item.next = undefined;\n item.previous = undefined;\n this._state++;\n }\n touch(item, touch) {\n if (!this._head || !this._tail) {\n throw new Error('Invalid list');\n }\n if ((touch !== Touch.First && touch !== Touch.Last)) {\n return;\n }\n if (touch === Touch.First) {\n if (item === this._head) {\n return;\n }\n const next = item.next;\n const previous = item.previous;\n // Unlink the item\n if (item === this._tail) {\n // previous must be defined since item was not head but is tail\n // So there are more than on item in the map\n previous.next = undefined;\n this._tail = previous;\n }\n else {\n // Both next and previous are not undefined since item was neither head nor tail.\n next.previous = previous;\n previous.next = next;\n }\n // Insert the node at head\n item.previous = undefined;\n item.next = this._head;\n this._head.previous = item;\n this._head = item;\n this._state++;\n }\n else if (touch === Touch.Last) {\n if (item === this._tail) {\n return;\n }\n const next = item.next;\n const previous = item.previous;\n // Unlink the item.\n if (item === this._head) {\n // next must be defined since item was not tail but is head\n // So there are more than on item in the map\n next.previous = undefined;\n this._head = next;\n }\n else {\n // Both next and previous are not undefined since item was neither head nor tail.\n next.previous = previous;\n previous.next = next;\n }\n item.next = undefined;\n item.previous = this._tail;\n this._tail.next = item;\n this._tail = item;\n this._state++;\n }\n }\n toJSON() {\n const data = [];\n this.forEach((value, key) => {\n data.push([key, value]);\n });\n return data;\n }\n fromJSON(data) {\n this.clear();\n for (const [key, value] of data) {\n this.set(key, value);\n }\n }\n}\nexports.LinkedMap = LinkedMap;\nclass LRUCache extends LinkedMap {\n constructor(limit, ratio = 1) {\n super();\n this._limit = limit;\n this._ratio = Math.min(Math.max(0, ratio), 1);\n }\n get limit() {\n return this._limit;\n }\n set limit(limit) {\n this._limit = limit;\n this.checkTrim();\n }\n get ratio() {\n return this._ratio;\n }\n set ratio(ratio) {\n this._ratio = Math.min(Math.max(0, ratio), 1);\n this.checkTrim();\n }\n get(key, touch = Touch.AsNew) {\n return super.get(key, touch);\n }\n peek(key) {\n return super.get(key, Touch.None);\n }\n set(key, value) {\n super.set(key, value, Touch.Last);\n this.checkTrim();\n return this;\n }\n checkTrim() {\n if (this.size > this._limit) {\n this.trimOld(Math.round(this._limit * this._ratio));\n }\n }\n}\nexports.LRUCache = LRUCache;\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Disposable = void 0;\nvar Disposable;\n(function (Disposable) {\n function create(func) {\n return {\n dispose: func\n };\n }\n Disposable.create = create;\n})(Disposable || (exports.Disposable = Disposable = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nlet _ral;\nfunction RAL() {\n if (_ral === undefined) {\n throw new Error(`No runtime abstraction layer installed`);\n }\n return _ral;\n}\n(function (RAL) {\n function install(ral) {\n if (ral === undefined) {\n throw new Error(`No runtime abstraction layer provided`);\n }\n _ral = ral;\n }\n RAL.install = install;\n})(RAL || (RAL = {}));\nexports.default = RAL;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Emitter = exports.Event = void 0;\nconst ral_1 = require(\"./ral\");\nvar Event;\n(function (Event) {\n const _disposable = { dispose() { } };\n Event.None = function () { return _disposable; };\n})(Event || (exports.Event = Event = {}));\nclass CallbackList {\n add(callback, context = null, bucket) {\n if (!this._callbacks) {\n this._callbacks = [];\n this._contexts = [];\n }\n this._callbacks.push(callback);\n this._contexts.push(context);\n if (Array.isArray(bucket)) {\n bucket.push({ dispose: () => this.remove(callback, context) });\n }\n }\n remove(callback, context = null) {\n if (!this._callbacks) {\n return;\n }\n let foundCallbackWithDifferentContext = false;\n for (let i = 0, len = this._callbacks.length; i < len; i++) {\n if (this._callbacks[i] === callback) {\n if (this._contexts[i] === context) {\n // callback & context match => remove it\n this._callbacks.splice(i, 1);\n this._contexts.splice(i, 1);\n return;\n }\n else {\n foundCallbackWithDifferentContext = true;\n }\n }\n }\n if (foundCallbackWithDifferentContext) {\n throw new Error('When adding a listener with a context, you should remove it with the same context');\n }\n }\n invoke(...args) {\n if (!this._callbacks) {\n return [];\n }\n const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);\n for (let i = 0, len = callbacks.length; i < len; i++) {\n try {\n ret.push(callbacks[i].apply(contexts[i], args));\n }\n catch (e) {\n // eslint-disable-next-line no-console\n (0, ral_1.default)().console.error(e);\n }\n }\n return ret;\n }\n isEmpty() {\n return !this._callbacks || this._callbacks.length === 0;\n }\n dispose() {\n this._callbacks = undefined;\n this._contexts = undefined;\n }\n}\nclass Emitter {\n constructor(_options) {\n this._options = _options;\n }\n /**\n * For the public to allow to subscribe\n * to events from this Emitter\n */\n get event() {\n if (!this._event) {\n this._event = (listener, thisArgs, disposables) => {\n if (!this._callbacks) {\n this._callbacks = new CallbackList();\n }\n if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {\n this._options.onFirstListenerAdd(this);\n }\n this._callbacks.add(listener, thisArgs);\n const result = {\n dispose: () => {\n if (!this._callbacks) {\n // disposable is disposed after emitter is disposed.\n return;\n }\n this._callbacks.remove(listener, thisArgs);\n result.dispose = Emitter._noop;\n if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {\n this._options.onLastListenerRemove(this);\n }\n }\n };\n if (Array.isArray(disposables)) {\n disposables.push(result);\n }\n return result;\n };\n }\n return this._event;\n }\n /**\n * To be kept private to fire an event to\n * subscribers\n */\n fire(event) {\n if (this._callbacks) {\n this._callbacks.invoke.call(this._callbacks, event);\n }\n }\n dispose() {\n if (this._callbacks) {\n this._callbacks.dispose();\n this._callbacks = undefined;\n }\n }\n}\nexports.Emitter = Emitter;\nEmitter._noop = function () { };\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CancellationTokenSource = exports.CancellationToken = void 0;\nconst ral_1 = require(\"./ral\");\nconst Is = require(\"./is\");\nconst events_1 = require(\"./events\");\nvar CancellationToken;\n(function (CancellationToken) {\n CancellationToken.None = Object.freeze({\n isCancellationRequested: false,\n onCancellationRequested: events_1.Event.None\n });\n CancellationToken.Cancelled = Object.freeze({\n isCancellationRequested: true,\n onCancellationRequested: events_1.Event.None\n });\n function is(value) {\n const candidate = value;\n return candidate && (candidate === CancellationToken.None\n || candidate === CancellationToken.Cancelled\n || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));\n }\n CancellationToken.is = is;\n})(CancellationToken || (exports.CancellationToken = CancellationToken = {}));\nconst shortcutEvent = Object.freeze(function (callback, context) {\n const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);\n return { dispose() { handle.dispose(); } };\n});\nclass MutableToken {\n constructor() {\n this._isCancelled = false;\n }\n cancel() {\n if (!this._isCancelled) {\n this._isCancelled = true;\n if (this._emitter) {\n this._emitter.fire(undefined);\n this.dispose();\n }\n }\n }\n get isCancellationRequested() {\n return this._isCancelled;\n }\n get onCancellationRequested() {\n if (this._isCancelled) {\n return shortcutEvent;\n }\n if (!this._emitter) {\n this._emitter = new events_1.Emitter();\n }\n return this._emitter.event;\n }\n dispose() {\n if (this._emitter) {\n this._emitter.dispose();\n this._emitter = undefined;\n }\n }\n}\nclass CancellationTokenSource {\n get token() {\n if (!this._token) {\n // be lazy and create the token only when\n // actually needed\n this._token = new MutableToken();\n }\n return this._token;\n }\n cancel() {\n if (!this._token) {\n // save an object by returning the default\n // cancelled token when cancellation happens\n // before someone asks for the token\n this._token = CancellationToken.Cancelled;\n }\n else {\n this._token.cancel();\n }\n }\n dispose() {\n if (!this._token) {\n // ensure to initialize with an empty token if we had none\n this._token = CancellationToken.None;\n }\n else if (this._token instanceof MutableToken) {\n // actually dispose\n this._token.dispose();\n }\n }\n}\nexports.CancellationTokenSource = CancellationTokenSource;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = void 0;\nconst cancellation_1 = require(\"./cancellation\");\nvar CancellationState;\n(function (CancellationState) {\n CancellationState.Continue = 0;\n CancellationState.Cancelled = 1;\n})(CancellationState || (CancellationState = {}));\nclass SharedArraySenderStrategy {\n constructor() {\n this.buffers = new Map();\n }\n enableCancellation(request) {\n if (request.id === null) {\n return;\n }\n const buffer = new SharedArrayBuffer(4);\n const data = new Int32Array(buffer, 0, 1);\n data[0] = CancellationState.Continue;\n this.buffers.set(request.id, buffer);\n request.$cancellationData = buffer;\n }\n async sendCancellation(_conn, id) {\n const buffer = this.buffers.get(id);\n if (buffer === undefined) {\n return;\n }\n const data = new Int32Array(buffer, 0, 1);\n Atomics.store(data, 0, CancellationState.Cancelled);\n }\n cleanup(id) {\n this.buffers.delete(id);\n }\n dispose() {\n this.buffers.clear();\n }\n}\nexports.SharedArraySenderStrategy = SharedArraySenderStrategy;\nclass SharedArrayBufferCancellationToken {\n constructor(buffer) {\n this.data = new Int32Array(buffer, 0, 1);\n }\n get isCancellationRequested() {\n return Atomics.load(this.data, 0) === CancellationState.Cancelled;\n }\n get onCancellationRequested() {\n throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`);\n }\n}\nclass SharedArrayBufferCancellationTokenSource {\n constructor(buffer) {\n this.token = new SharedArrayBufferCancellationToken(buffer);\n }\n cancel() {\n }\n dispose() {\n }\n}\nclass SharedArrayReceiverStrategy {\n constructor() {\n this.kind = 'request';\n }\n createCancellationTokenSource(request) {\n const buffer = request.$cancellationData;\n if (buffer === undefined) {\n return new cancellation_1.CancellationTokenSource();\n }\n return new SharedArrayBufferCancellationTokenSource(buffer);\n }\n}\nexports.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Semaphore = void 0;\nconst ral_1 = require(\"./ral\");\nclass Semaphore {\n constructor(capacity = 1) {\n if (capacity <= 0) {\n throw new Error('Capacity must be greater than 0');\n }\n this._capacity = capacity;\n this._active = 0;\n this._waiting = [];\n }\n lock(thunk) {\n return new Promise((resolve, reject) => {\n this._waiting.push({ thunk, resolve, reject });\n this.runNext();\n });\n }\n get active() {\n return this._active;\n }\n runNext() {\n if (this._waiting.length === 0 || this._active === this._capacity) {\n return;\n }\n (0, ral_1.default)().timer.setImmediate(() => this.doRunNext());\n }\n doRunNext() {\n if (this._waiting.length === 0 || this._active === this._capacity) {\n return;\n }\n const next = this._waiting.shift();\n this._active++;\n if (this._active > this._capacity) {\n throw new Error(`To many thunks active`);\n }\n try {\n const result = next.thunk();\n if (result instanceof Promise) {\n result.then((value) => {\n this._active--;\n next.resolve(value);\n this.runNext();\n }, (err) => {\n this._active--;\n next.reject(err);\n this.runNext();\n });\n }\n else {\n this._active--;\n next.resolve(result);\n this.runNext();\n }\n }\n catch (err) {\n this._active--;\n next.reject(err);\n this.runNext();\n }\n }\n}\nexports.Semaphore = Semaphore;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = void 0;\nconst ral_1 = require(\"./ral\");\nconst Is = require(\"./is\");\nconst events_1 = require(\"./events\");\nconst semaphore_1 = require(\"./semaphore\");\nvar MessageReader;\n(function (MessageReader) {\n function is(value) {\n let candidate = value;\n return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&\n Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);\n }\n MessageReader.is = is;\n})(MessageReader || (exports.MessageReader = MessageReader = {}));\nclass AbstractMessageReader {\n constructor() {\n this.errorEmitter = new events_1.Emitter();\n this.closeEmitter = new events_1.Emitter();\n this.partialMessageEmitter = new events_1.Emitter();\n }\n dispose() {\n this.errorEmitter.dispose();\n this.closeEmitter.dispose();\n }\n get onError() {\n return this.errorEmitter.event;\n }\n fireError(error) {\n this.errorEmitter.fire(this.asError(error));\n }\n get onClose() {\n return this.closeEmitter.event;\n }\n fireClose() {\n this.closeEmitter.fire(undefined);\n }\n get onPartialMessage() {\n return this.partialMessageEmitter.event;\n }\n firePartialMessage(info) {\n this.partialMessageEmitter.fire(info);\n }\n asError(error) {\n if (error instanceof Error) {\n return error;\n }\n else {\n return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);\n }\n }\n}\nexports.AbstractMessageReader = AbstractMessageReader;\nvar ResolvedMessageReaderOptions;\n(function (ResolvedMessageReaderOptions) {\n function fromOptions(options) {\n let charset;\n let result;\n let contentDecoder;\n const contentDecoders = new Map();\n let contentTypeDecoder;\n const contentTypeDecoders = new Map();\n if (options === undefined || typeof options === 'string') {\n charset = options ?? 'utf-8';\n }\n else {\n charset = options.charset ?? 'utf-8';\n if (options.contentDecoder !== undefined) {\n contentDecoder = options.contentDecoder;\n contentDecoders.set(contentDecoder.name, contentDecoder);\n }\n if (options.contentDecoders !== undefined) {\n for (const decoder of options.contentDecoders) {\n contentDecoders.set(decoder.name, decoder);\n }\n }\n if (options.contentTypeDecoder !== undefined) {\n contentTypeDecoder = options.contentTypeDecoder;\n contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);\n }\n if (options.contentTypeDecoders !== undefined) {\n for (const decoder of options.contentTypeDecoders) {\n contentTypeDecoders.set(decoder.name, decoder);\n }\n }\n }\n if (contentTypeDecoder === undefined) {\n contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder;\n contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);\n }\n return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };\n }\n ResolvedMessageReaderOptions.fromOptions = fromOptions;\n})(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));\nclass ReadableStreamMessageReader extends AbstractMessageReader {\n constructor(readable, options) {\n super();\n this.readable = readable;\n this.options = ResolvedMessageReaderOptions.fromOptions(options);\n this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset);\n this._partialMessageTimeout = 10000;\n this.nextMessageLength = -1;\n this.messageToken = 0;\n this.readSemaphore = new semaphore_1.Semaphore(1);\n }\n set partialMessageTimeout(timeout) {\n this._partialMessageTimeout = timeout;\n }\n get partialMessageTimeout() {\n return this._partialMessageTimeout;\n }\n listen(callback) {\n this.nextMessageLength = -1;\n this.messageToken = 0;\n this.partialMessageTimer = undefined;\n this.callback = callback;\n const result = this.readable.onData((data) => {\n this.onData(data);\n });\n this.readable.onError((error) => this.fireError(error));\n this.readable.onClose(() => this.fireClose());\n return result;\n }\n onData(data) {\n try {\n this.buffer.append(data);\n while (true) {\n if (this.nextMessageLength === -1) {\n const headers = this.buffer.tryReadHeaders(true);\n if (!headers) {\n return;\n }\n const contentLength = headers.get('content-length');\n if (!contentLength) {\n this.fireError(new Error(`Header must provide a Content-Length property.\\n${JSON.stringify(Object.fromEntries(headers))}`));\n return;\n }\n const length = parseInt(contentLength);\n if (isNaN(length)) {\n this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`));\n return;\n }\n this.nextMessageLength = length;\n }\n const body = this.buffer.tryReadBody(this.nextMessageLength);\n if (body === undefined) {\n /** We haven't received the full message yet. */\n this.setPartialMessageTimer();\n return;\n }\n this.clearPartialMessageTimer();\n this.nextMessageLength = -1;\n // Make sure that we convert one received message after the\n // other. Otherwise it could happen that a decoding of a second\n // smaller message finished before the decoding of a first larger\n // message and then we would deliver the second message first.\n this.readSemaphore.lock(async () => {\n const bytes = this.options.contentDecoder !== undefined\n ? await this.options.contentDecoder.decode(body)\n : body;\n const message = await this.options.contentTypeDecoder.decode(bytes, this.options);\n this.callback(message);\n }).catch((error) => {\n this.fireError(error);\n });\n }\n }\n catch (error) {\n this.fireError(error);\n }\n }\n clearPartialMessageTimer() {\n if (this.partialMessageTimer) {\n this.partialMessageTimer.dispose();\n this.partialMessageTimer = undefined;\n }\n }\n setPartialMessageTimer() {\n this.clearPartialMessageTimer();\n if (this._partialMessageTimeout <= 0) {\n return;\n }\n this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => {\n this.partialMessageTimer = undefined;\n if (token === this.messageToken) {\n this.firePartialMessage({ messageToken: token, waitingTime: timeout });\n this.setPartialMessageTimer();\n }\n }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);\n }\n}\nexports.ReadableStreamMessageReader = ReadableStreamMessageReader;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = void 0;\nconst ral_1 = require(\"./ral\");\nconst Is = require(\"./is\");\nconst semaphore_1 = require(\"./semaphore\");\nconst events_1 = require(\"./events\");\nconst ContentLength = 'Content-Length: ';\nconst CRLF = '\\r\\n';\nvar MessageWriter;\n(function (MessageWriter) {\n function is(value) {\n let candidate = value;\n return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&\n Is.func(candidate.onError) && Is.func(candidate.write);\n }\n MessageWriter.is = is;\n})(MessageWriter || (exports.MessageWriter = MessageWriter = {}));\nclass AbstractMessageWriter {\n constructor() {\n this.errorEmitter = new events_1.Emitter();\n this.closeEmitter = new events_1.Emitter();\n }\n dispose() {\n this.errorEmitter.dispose();\n this.closeEmitter.dispose();\n }\n get onError() {\n return this.errorEmitter.event;\n }\n fireError(error, message, count) {\n this.errorEmitter.fire([this.asError(error), message, count]);\n }\n get onClose() {\n return this.closeEmitter.event;\n }\n fireClose() {\n this.closeEmitter.fire(undefined);\n }\n asError(error) {\n if (error instanceof Error) {\n return error;\n }\n else {\n return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);\n }\n }\n}\nexports.AbstractMessageWriter = AbstractMessageWriter;\nvar ResolvedMessageWriterOptions;\n(function (ResolvedMessageWriterOptions) {\n function fromOptions(options) {\n if (options === undefined || typeof options === 'string') {\n return { charset: options ?? 'utf-8', contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder };\n }\n else {\n return { charset: options.charset ?? 'utf-8', contentEncoder: options.contentEncoder, contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder };\n }\n }\n ResolvedMessageWriterOptions.fromOptions = fromOptions;\n})(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));\nclass WriteableStreamMessageWriter extends AbstractMessageWriter {\n constructor(writable, options) {\n super();\n this.writable = writable;\n this.options = ResolvedMessageWriterOptions.fromOptions(options);\n this.errorCount = 0;\n this.writeSemaphore = new semaphore_1.Semaphore(1);\n this.writable.onError((error) => this.fireError(error));\n this.writable.onClose(() => this.fireClose());\n }\n async write(msg) {\n return this.writeSemaphore.lock(async () => {\n const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {\n if (this.options.contentEncoder !== undefined) {\n return this.options.contentEncoder.encode(buffer);\n }\n else {\n return buffer;\n }\n });\n return payload.then((buffer) => {\n const headers = [];\n headers.push(ContentLength, buffer.byteLength.toString(), CRLF);\n headers.push(CRLF);\n return this.doWrite(msg, headers, buffer);\n }, (error) => {\n this.fireError(error);\n throw error;\n });\n });\n }\n async doWrite(msg, headers, data) {\n try {\n await this.writable.write(headers.join(''), 'ascii');\n return this.writable.write(data);\n }\n catch (error) {\n this.handleError(error, msg);\n return Promise.reject(error);\n }\n }\n handleError(error, msg) {\n this.errorCount++;\n this.fireError(error, msg, this.errorCount);\n }\n end() {\n this.writable.end();\n }\n}\nexports.WriteableStreamMessageWriter = WriteableStreamMessageWriter;\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AbstractMessageBuffer = void 0;\nconst CR = 13;\nconst LF = 10;\nconst CRLF = '\\r\\n';\nclass AbstractMessageBuffer {\n constructor(encoding = 'utf-8') {\n this._encoding = encoding;\n this._chunks = [];\n this._totalLength = 0;\n }\n get encoding() {\n return this._encoding;\n }\n append(chunk) {\n const toAppend = typeof chunk === 'string' ? this.fromString(chunk, this._encoding) : chunk;\n this._chunks.push(toAppend);\n this._totalLength += toAppend.byteLength;\n }\n tryReadHeaders(lowerCaseKeys = false) {\n if (this._chunks.length === 0) {\n return undefined;\n }\n let state = 0;\n let chunkIndex = 0;\n let offset = 0;\n let chunkBytesRead = 0;\n row: while (chunkIndex < this._chunks.length) {\n const chunk = this._chunks[chunkIndex];\n offset = 0;\n column: while (offset < chunk.length) {\n const value = chunk[offset];\n switch (value) {\n case CR:\n switch (state) {\n case 0:\n state = 1;\n break;\n case 2:\n state = 3;\n break;\n default:\n state = 0;\n }\n break;\n case LF:\n switch (state) {\n case 1:\n state = 2;\n break;\n case 3:\n state = 4;\n offset++;\n break row;\n default:\n state = 0;\n }\n break;\n default:\n state = 0;\n }\n offset++;\n }\n chunkBytesRead += chunk.byteLength;\n chunkIndex++;\n }\n if (state !== 4) {\n return undefined;\n }\n // The buffer contains the two CRLF at the end. So we will\n // have two empty lines after the split at the end as well.\n const buffer = this._read(chunkBytesRead + offset);\n const result = new Map();\n const headers = this.toString(buffer, 'ascii').split(CRLF);\n if (headers.length < 2) {\n return result;\n }\n for (let i = 0; i < headers.length - 2; i++) {\n const header = headers[i];\n const index = header.indexOf(':');\n if (index === -1) {\n throw new Error(`Message header must separate key and value using ':'\\n${header}`);\n }\n const key = header.substr(0, index);\n const value = header.substr(index + 1).trim();\n result.set(lowerCaseKeys ? key.toLowerCase() : key, value);\n }\n return result;\n }\n tryReadBody(length) {\n if (this._totalLength < length) {\n return undefined;\n }\n return this._read(length);\n }\n get numberOfBytes() {\n return this._totalLength;\n }\n _read(byteCount) {\n if (byteCount === 0) {\n return this.emptyBuffer();\n }\n if (byteCount > this._totalLength) {\n throw new Error(`Cannot read so many bytes!`);\n }\n if (this._chunks[0].byteLength === byteCount) {\n // super fast path, precisely first chunk must be returned\n const chunk = this._chunks[0];\n this._chunks.shift();\n this._totalLength -= byteCount;\n return this.asNative(chunk);\n }\n if (this._chunks[0].byteLength > byteCount) {\n // fast path, the reading is entirely within the first chunk\n const chunk = this._chunks[0];\n const result = this.asNative(chunk, byteCount);\n this._chunks[0] = chunk.slice(byteCount);\n this._totalLength -= byteCount;\n return result;\n }\n const result = this.allocNative(byteCount);\n let resultOffset = 0;\n let chunkIndex = 0;\n while (byteCount > 0) {\n const chunk = this._chunks[chunkIndex];\n if (chunk.byteLength > byteCount) {\n // this chunk will survive\n const chunkPart = chunk.slice(0, byteCount);\n result.set(chunkPart, resultOffset);\n resultOffset += byteCount;\n this._chunks[chunkIndex] = chunk.slice(byteCount);\n this._totalLength -= byteCount;\n byteCount -= byteCount;\n }\n else {\n // this chunk will be entirely read\n result.set(chunk, resultOffset);\n resultOffset += chunk.byteLength;\n this._chunks.shift();\n this._totalLength -= chunk.byteLength;\n byteCount -= chunk.byteLength;\n }\n }\n return result;\n }\n}\nexports.AbstractMessageBuffer = AbstractMessageBuffer;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createMessageConnection = exports.ConnectionOptions = exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.RequestCancellationReceiverStrategy = exports.IdCancellationReceiverStrategy = exports.ConnectionStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = exports.NullLogger = exports.ProgressType = exports.ProgressToken = void 0;\nconst ral_1 = require(\"./ral\");\nconst Is = require(\"./is\");\nconst messages_1 = require(\"./messages\");\nconst linkedMap_1 = require(\"./linkedMap\");\nconst events_1 = require(\"./events\");\nconst cancellation_1 = require(\"./cancellation\");\nvar CancelNotification;\n(function (CancelNotification) {\n CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');\n})(CancelNotification || (CancelNotification = {}));\nvar ProgressToken;\n(function (ProgressToken) {\n function is(value) {\n return typeof value === 'string' || typeof value === 'number';\n }\n ProgressToken.is = is;\n})(ProgressToken || (exports.ProgressToken = ProgressToken = {}));\nvar ProgressNotification;\n(function (ProgressNotification) {\n ProgressNotification.type = new messages_1.NotificationType('$/progress');\n})(ProgressNotification || (ProgressNotification = {}));\nclass ProgressType {\n constructor() {\n }\n}\nexports.ProgressType = ProgressType;\nvar StarRequestHandler;\n(function (StarRequestHandler) {\n function is(value) {\n return Is.func(value);\n }\n StarRequestHandler.is = is;\n})(StarRequestHandler || (StarRequestHandler = {}));\nexports.NullLogger = Object.freeze({\n error: () => { },\n warn: () => { },\n info: () => { },\n log: () => { }\n});\nvar Trace;\n(function (Trace) {\n Trace[Trace[\"Off\"] = 0] = \"Off\";\n Trace[Trace[\"Messages\"] = 1] = \"Messages\";\n Trace[Trace[\"Compact\"] = 2] = \"Compact\";\n Trace[Trace[\"Verbose\"] = 3] = \"Verbose\";\n})(Trace || (exports.Trace = Trace = {}));\nvar TraceValues;\n(function (TraceValues) {\n /**\n * Turn tracing off.\n */\n TraceValues.Off = 'off';\n /**\n * Trace messages only.\n */\n TraceValues.Messages = 'messages';\n /**\n * Compact message tracing.\n */\n TraceValues.Compact = 'compact';\n /**\n * Verbose message tracing.\n */\n TraceValues.Verbose = 'verbose';\n})(TraceValues || (exports.TraceValues = TraceValues = {}));\n(function (Trace) {\n function fromString(value) {\n if (!Is.string(value)) {\n return Trace.Off;\n }\n value = value.toLowerCase();\n switch (value) {\n case 'off':\n return Trace.Off;\n case 'messages':\n return Trace.Messages;\n case 'compact':\n return Trace.Compact;\n case 'verbose':\n return Trace.Verbose;\n default:\n return Trace.Off;\n }\n }\n Trace.fromString = fromString;\n function toString(value) {\n switch (value) {\n case Trace.Off:\n return 'off';\n case Trace.Messages:\n return 'messages';\n case Trace.Compact:\n return 'compact';\n case Trace.Verbose:\n return 'verbose';\n default:\n return 'off';\n }\n }\n Trace.toString = toString;\n})(Trace || (exports.Trace = Trace = {}));\nvar TraceFormat;\n(function (TraceFormat) {\n TraceFormat[\"Text\"] = \"text\";\n TraceFormat[\"JSON\"] = \"json\";\n})(TraceFormat || (exports.TraceFormat = TraceFormat = {}));\n(function (TraceFormat) {\n function fromString(value) {\n if (!Is.string(value)) {\n return TraceFormat.Text;\n }\n value = value.toLowerCase();\n if (value === 'json') {\n return TraceFormat.JSON;\n }\n else {\n return TraceFormat.Text;\n }\n }\n TraceFormat.fromString = fromString;\n})(TraceFormat || (exports.TraceFormat = TraceFormat = {}));\nvar SetTraceNotification;\n(function (SetTraceNotification) {\n SetTraceNotification.type = new messages_1.NotificationType('$/setTrace');\n})(SetTraceNotification || (exports.SetTraceNotification = SetTraceNotification = {}));\nvar LogTraceNotification;\n(function (LogTraceNotification) {\n LogTraceNotification.type = new messages_1.NotificationType('$/logTrace');\n})(LogTraceNotification || (exports.LogTraceNotification = LogTraceNotification = {}));\nvar ConnectionErrors;\n(function (ConnectionErrors) {\n /**\n * The connection is closed.\n */\n ConnectionErrors[ConnectionErrors[\"Closed\"] = 1] = \"Closed\";\n /**\n * The connection got disposed.\n */\n ConnectionErrors[ConnectionErrors[\"Disposed\"] = 2] = \"Disposed\";\n /**\n * The connection is already in listening mode.\n */\n ConnectionErrors[ConnectionErrors[\"AlreadyListening\"] = 3] = \"AlreadyListening\";\n})(ConnectionErrors || (exports.ConnectionErrors = ConnectionErrors = {}));\nclass ConnectionError extends Error {\n constructor(code, message) {\n super(message);\n this.code = code;\n Object.setPrototypeOf(this, ConnectionError.prototype);\n }\n}\nexports.ConnectionError = ConnectionError;\nvar ConnectionStrategy;\n(function (ConnectionStrategy) {\n function is(value) {\n const candidate = value;\n return candidate && Is.func(candidate.cancelUndispatched);\n }\n ConnectionStrategy.is = is;\n})(ConnectionStrategy || (exports.ConnectionStrategy = ConnectionStrategy = {}));\nvar IdCancellationReceiverStrategy;\n(function (IdCancellationReceiverStrategy) {\n function is(value) {\n const candidate = value;\n return candidate && (candidate.kind === undefined || candidate.kind === 'id') && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));\n }\n IdCancellationReceiverStrategy.is = is;\n})(IdCancellationReceiverStrategy || (exports.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {}));\nvar RequestCancellationReceiverStrategy;\n(function (RequestCancellationReceiverStrategy) {\n function is(value) {\n const candidate = value;\n return candidate && candidate.kind === 'request' && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));\n }\n RequestCancellationReceiverStrategy.is = is;\n})(RequestCancellationReceiverStrategy || (exports.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {}));\nvar CancellationReceiverStrategy;\n(function (CancellationReceiverStrategy) {\n CancellationReceiverStrategy.Message = Object.freeze({\n createCancellationTokenSource(_) {\n return new cancellation_1.CancellationTokenSource();\n }\n });\n function is(value) {\n return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value);\n }\n CancellationReceiverStrategy.is = is;\n})(CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = CancellationReceiverStrategy = {}));\nvar CancellationSenderStrategy;\n(function (CancellationSenderStrategy) {\n CancellationSenderStrategy.Message = Object.freeze({\n sendCancellation(conn, id) {\n return conn.sendNotification(CancelNotification.type, { id });\n },\n cleanup(_) { }\n });\n function is(value) {\n const candidate = value;\n return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);\n }\n CancellationSenderStrategy.is = is;\n})(CancellationSenderStrategy || (exports.CancellationSenderStrategy = CancellationSenderStrategy = {}));\nvar CancellationStrategy;\n(function (CancellationStrategy) {\n CancellationStrategy.Message = Object.freeze({\n receiver: CancellationReceiverStrategy.Message,\n sender: CancellationSenderStrategy.Message\n });\n function is(value) {\n const candidate = value;\n return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);\n }\n CancellationStrategy.is = is;\n})(CancellationStrategy || (exports.CancellationStrategy = CancellationStrategy = {}));\nvar MessageStrategy;\n(function (MessageStrategy) {\n function is(value) {\n const candidate = value;\n return candidate && Is.func(candidate.handleMessage);\n }\n MessageStrategy.is = is;\n})(MessageStrategy || (exports.MessageStrategy = MessageStrategy = {}));\nvar ConnectionOptions;\n(function (ConnectionOptions) {\n function is(value) {\n const candidate = value;\n return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy));\n }\n ConnectionOptions.is = is;\n})(ConnectionOptions || (exports.ConnectionOptions = ConnectionOptions = {}));\nvar ConnectionState;\n(function (ConnectionState) {\n ConnectionState[ConnectionState[\"New\"] = 1] = \"New\";\n ConnectionState[ConnectionState[\"Listening\"] = 2] = \"Listening\";\n ConnectionState[ConnectionState[\"Closed\"] = 3] = \"Closed\";\n ConnectionState[ConnectionState[\"Disposed\"] = 4] = \"Disposed\";\n})(ConnectionState || (ConnectionState = {}));\nfunction createMessageConnection(messageReader, messageWriter, _logger, options) {\n const logger = _logger !== undefined ? _logger : exports.NullLogger;\n let sequenceNumber = 0;\n let notificationSequenceNumber = 0;\n let unknownResponseSequenceNumber = 0;\n const version = '2.0';\n let starRequestHandler = undefined;\n const requestHandlers = new Map();\n let starNotificationHandler = undefined;\n const notificationHandlers = new Map();\n const progressHandlers = new Map();\n let timer;\n let messageQueue = new linkedMap_1.LinkedMap();\n let responsePromises = new Map();\n let knownCanceledRequests = new Set();\n let requestTokens = new Map();\n let trace = Trace.Off;\n let traceFormat = TraceFormat.Text;\n let tracer;\n let state = ConnectionState.New;\n const errorEmitter = new events_1.Emitter();\n const closeEmitter = new events_1.Emitter();\n const unhandledNotificationEmitter = new events_1.Emitter();\n const unhandledProgressEmitter = new events_1.Emitter();\n const disposeEmitter = new events_1.Emitter();\n const cancellationStrategy = (options && options.cancellationStrategy) ? options.cancellationStrategy : CancellationStrategy.Message;\n function createRequestQueueKey(id) {\n if (id === null) {\n throw new Error(`Can't send requests with id null since the response can't be correlated.`);\n }\n return 'req-' + id.toString();\n }\n function createResponseQueueKey(id) {\n if (id === null) {\n return 'res-unknown-' + (++unknownResponseSequenceNumber).toString();\n }\n else {\n return 'res-' + id.toString();\n }\n }\n function createNotificationQueueKey() {\n return 'not-' + (++notificationSequenceNumber).toString();\n }\n function addMessageToQueue(queue, message) {\n if (messages_1.Message.isRequest(message)) {\n queue.set(createRequestQueueKey(message.id), message);\n }\n else if (messages_1.Message.isResponse(message)) {\n queue.set(createResponseQueueKey(message.id), message);\n }\n else {\n queue.set(createNotificationQueueKey(), message);\n }\n }\n function cancelUndispatched(_message) {\n return undefined;\n }\n function isListening() {\n return state === ConnectionState.Listening;\n }\n function isClosed() {\n return state === ConnectionState.Closed;\n }\n function isDisposed() {\n return state === ConnectionState.Disposed;\n }\n function closeHandler() {\n if (state === ConnectionState.New || state === ConnectionState.Listening) {\n state = ConnectionState.Closed;\n closeEmitter.fire(undefined);\n }\n // If the connection is disposed don't sent close events.\n }\n function readErrorHandler(error) {\n errorEmitter.fire([error, undefined, undefined]);\n }\n function writeErrorHandler(data) {\n errorEmitter.fire(data);\n }\n messageReader.onClose(closeHandler);\n messageReader.onError(readErrorHandler);\n messageWriter.onClose(closeHandler);\n messageWriter.onError(writeErrorHandler);\n function triggerMessageQueue() {\n if (timer || messageQueue.size === 0) {\n return;\n }\n timer = (0, ral_1.default)().timer.setImmediate(() => {\n timer = undefined;\n processMessageQueue();\n });\n }\n function handleMessage(message) {\n if (messages_1.Message.isRequest(message)) {\n handleRequest(message);\n }\n else if (messages_1.Message.isNotification(message)) {\n handleNotification(message);\n }\n else if (messages_1.Message.isResponse(message)) {\n handleResponse(message);\n }\n else {\n handleInvalidMessage(message);\n }\n }\n function processMessageQueue() {\n if (messageQueue.size === 0) {\n return;\n }\n const message = messageQueue.shift();\n try {\n const messageStrategy = options?.messageStrategy;\n if (MessageStrategy.is(messageStrategy)) {\n messageStrategy.handleMessage(message, handleMessage);\n }\n else {\n handleMessage(message);\n }\n }\n finally {\n triggerMessageQueue();\n }\n }\n const callback = (message) => {\n try {\n // We have received a cancellation message. Check if the message is still in the queue\n // and cancel it if allowed to do so.\n if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) {\n const cancelId = message.params.id;\n const key = createRequestQueueKey(cancelId);\n const toCancel = messageQueue.get(key);\n if (messages_1.Message.isRequest(toCancel)) {\n const strategy = options?.connectionStrategy;\n const response = (strategy && strategy.cancelUndispatched) ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);\n if (response && (response.error !== undefined || response.result !== undefined)) {\n messageQueue.delete(key);\n requestTokens.delete(cancelId);\n response.id = toCancel.id;\n traceSendingResponse(response, message.method, Date.now());\n messageWriter.write(response).catch(() => logger.error(`Sending response for canceled message failed.`));\n return;\n }\n }\n const cancellationToken = requestTokens.get(cancelId);\n // The request is already running. Cancel the token\n if (cancellationToken !== undefined) {\n cancellationToken.cancel();\n traceReceivedNotification(message);\n return;\n }\n else {\n // Remember the cancel but still queue the message to\n // clean up state in process message.\n knownCanceledRequests.add(cancelId);\n }\n }\n addMessageToQueue(messageQueue, message);\n }\n finally {\n triggerMessageQueue();\n }\n };\n function handleRequest(requestMessage) {\n if (isDisposed()) {\n // we return here silently since we fired an event when the\n // connection got disposed.\n return;\n }\n function reply(resultOrError, method, startTime) {\n const message = {\n jsonrpc: version,\n id: requestMessage.id\n };\n if (resultOrError instanceof messages_1.ResponseError) {\n message.error = resultOrError.toJson();\n }\n else {\n message.result = resultOrError === undefined ? null : resultOrError;\n }\n traceSendingResponse(message, method, startTime);\n messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));\n }\n function replyError(error, method, startTime) {\n const message = {\n jsonrpc: version,\n id: requestMessage.id,\n error: error.toJson()\n };\n traceSendingResponse(message, method, startTime);\n messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));\n }\n function replySuccess(result, method, startTime) {\n // The JSON RPC defines that a response must either have a result or an error\n // So we can't treat undefined as a valid response result.\n if (result === undefined) {\n result = null;\n }\n const message = {\n jsonrpc: version,\n id: requestMessage.id,\n result: result\n };\n traceSendingResponse(message, method, startTime);\n messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));\n }\n traceReceivedRequest(requestMessage);\n const element = requestHandlers.get(requestMessage.method);\n let type;\n let requestHandler;\n if (element) {\n type = element.type;\n requestHandler = element.handler;\n }\n const startTime = Date.now();\n if (requestHandler || starRequestHandler) {\n const tokenKey = requestMessage.id ?? String(Date.now()); //\n const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver)\n ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey)\n : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);\n if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) {\n cancellationSource.cancel();\n }\n if (requestMessage.id !== null) {\n requestTokens.set(tokenKey, cancellationSource);\n }\n try {\n let handlerResult;\n if (requestHandler) {\n if (requestMessage.params === undefined) {\n if (type !== undefined && type.numberOfParams !== 0) {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime);\n return;\n }\n handlerResult = requestHandler(cancellationSource.token);\n }\n else if (Array.isArray(requestMessage.params)) {\n if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byName) {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);\n return;\n }\n handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);\n }\n else {\n if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);\n return;\n }\n handlerResult = requestHandler(requestMessage.params, cancellationSource.token);\n }\n }\n else if (starRequestHandler) {\n handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);\n }\n const promise = handlerResult;\n if (!handlerResult) {\n requestTokens.delete(tokenKey);\n replySuccess(handlerResult, requestMessage.method, startTime);\n }\n else if (promise.then) {\n promise.then((resultOrError) => {\n requestTokens.delete(tokenKey);\n reply(resultOrError, requestMessage.method, startTime);\n }, error => {\n requestTokens.delete(tokenKey);\n if (error instanceof messages_1.ResponseError) {\n replyError(error, requestMessage.method, startTime);\n }\n else if (error && Is.string(error.message)) {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);\n }\n else {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);\n }\n });\n }\n else {\n requestTokens.delete(tokenKey);\n reply(handlerResult, requestMessage.method, startTime);\n }\n }\n catch (error) {\n requestTokens.delete(tokenKey);\n if (error instanceof messages_1.ResponseError) {\n reply(error, requestMessage.method, startTime);\n }\n else if (error && Is.string(error.message)) {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);\n }\n else {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);\n }\n }\n }\n else {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);\n }\n }\n function handleResponse(responseMessage) {\n if (isDisposed()) {\n // See handle request.\n return;\n }\n if (responseMessage.id === null) {\n if (responseMessage.error) {\n logger.error(`Received response message without id: Error is: \\n${JSON.stringify(responseMessage.error, undefined, 4)}`);\n }\n else {\n logger.error(`Received response message without id. No further error information provided.`);\n }\n }\n else {\n const key = responseMessage.id;\n const responsePromise = responsePromises.get(key);\n traceReceivedResponse(responseMessage, responsePromise);\n if (responsePromise !== undefined) {\n responsePromises.delete(key);\n try {\n if (responseMessage.error) {\n const error = responseMessage.error;\n responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));\n }\n else if (responseMessage.result !== undefined) {\n responsePromise.resolve(responseMessage.result);\n }\n else {\n throw new Error('Should never happen.');\n }\n }\n catch (error) {\n if (error.message) {\n logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);\n }\n else {\n logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);\n }\n }\n }\n }\n }\n function handleNotification(message) {\n if (isDisposed()) {\n // See handle request.\n return;\n }\n let type = undefined;\n let notificationHandler;\n if (message.method === CancelNotification.type.method) {\n const cancelId = message.params.id;\n knownCanceledRequests.delete(cancelId);\n traceReceivedNotification(message);\n return;\n }\n else {\n const element = notificationHandlers.get(message.method);\n if (element) {\n notificationHandler = element.handler;\n type = element.type;\n }\n }\n if (notificationHandler || starNotificationHandler) {\n try {\n traceReceivedNotification(message);\n if (notificationHandler) {\n if (message.params === undefined) {\n if (type !== undefined) {\n if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) {\n logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`);\n }\n }\n notificationHandler();\n }\n else if (Array.isArray(message.params)) {\n // There are JSON-RPC libraries that send progress message as positional params although\n // specified as named. So convert them if this is the case.\n const params = message.params;\n if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) {\n notificationHandler({ token: params[0], value: params[1] });\n }\n else {\n if (type !== undefined) {\n if (type.parameterStructures === messages_1.ParameterStructures.byName) {\n logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`);\n }\n if (type.numberOfParams !== message.params.length) {\n logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`);\n }\n }\n notificationHandler(...params);\n }\n }\n else {\n if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {\n logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`);\n }\n notificationHandler(message.params);\n }\n }\n else if (starNotificationHandler) {\n starNotificationHandler(message.method, message.params);\n }\n }\n catch (error) {\n if (error.message) {\n logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);\n }\n else {\n logger.error(`Notification handler '${message.method}' failed unexpectedly.`);\n }\n }\n }\n else {\n unhandledNotificationEmitter.fire(message);\n }\n }\n function handleInvalidMessage(message) {\n if (!message) {\n logger.error('Received empty message.');\n return;\n }\n logger.error(`Received message which is neither a response nor a notification message:\\n${JSON.stringify(message, null, 4)}`);\n // Test whether we find an id to reject the promise\n const responseMessage = message;\n if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {\n const key = responseMessage.id;\n const responseHandler = responsePromises.get(key);\n if (responseHandler) {\n responseHandler.reject(new Error('The received response has neither a result nor an error property.'));\n }\n }\n }\n function stringifyTrace(params) {\n if (params === undefined || params === null) {\n return undefined;\n }\n switch (trace) {\n case Trace.Verbose:\n return JSON.stringify(params, null, 4);\n case Trace.Compact:\n return JSON.stringify(params);\n default:\n return undefined;\n }\n }\n function traceSendingRequest(message) {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {\n data = `Params: ${stringifyTrace(message.params)}\\n\\n`;\n }\n tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);\n }\n else {\n logLSPMessage('send-request', message);\n }\n }\n function traceSendingNotification(message) {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if (trace === Trace.Verbose || trace === Trace.Compact) {\n if (message.params) {\n data = `Params: ${stringifyTrace(message.params)}\\n\\n`;\n }\n else {\n data = 'No parameters provided.\\n\\n';\n }\n }\n tracer.log(`Sending notification '${message.method}'.`, data);\n }\n else {\n logLSPMessage('send-notification', message);\n }\n }\n function traceSendingResponse(message, method, startTime) {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if (trace === Trace.Verbose || trace === Trace.Compact) {\n if (message.error && message.error.data) {\n data = `Error data: ${stringifyTrace(message.error.data)}\\n\\n`;\n }\n else {\n if (message.result) {\n data = `Result: ${stringifyTrace(message.result)}\\n\\n`;\n }\n else if (message.error === undefined) {\n data = 'No result returned.\\n\\n';\n }\n }\n }\n tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);\n }\n else {\n logLSPMessage('send-response', message);\n }\n }\n function traceReceivedRequest(message) {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {\n data = `Params: ${stringifyTrace(message.params)}\\n\\n`;\n }\n tracer.log(`Received request '${message.method} - (${message.id})'.`, data);\n }\n else {\n logLSPMessage('receive-request', message);\n }\n }\n function traceReceivedNotification(message) {\n if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if (trace === Trace.Verbose || trace === Trace.Compact) {\n if (message.params) {\n data = `Params: ${stringifyTrace(message.params)}\\n\\n`;\n }\n else {\n data = 'No parameters provided.\\n\\n';\n }\n }\n tracer.log(`Received notification '${message.method}'.`, data);\n }\n else {\n logLSPMessage('receive-notification', message);\n }\n }\n function traceReceivedResponse(message, responsePromise) {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if (trace === Trace.Verbose || trace === Trace.Compact) {\n if (message.error && message.error.data) {\n data = `Error data: ${stringifyTrace(message.error.data)}\\n\\n`;\n }\n else {\n if (message.result) {\n data = `Result: ${stringifyTrace(message.result)}\\n\\n`;\n }\n else if (message.error === undefined) {\n data = 'No result returned.\\n\\n';\n }\n }\n }\n if (responsePromise) {\n const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';\n tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);\n }\n else {\n tracer.log(`Received response ${message.id} without active response promise.`, data);\n }\n }\n else {\n logLSPMessage('receive-response', message);\n }\n }\n function logLSPMessage(type, message) {\n if (!tracer || trace === Trace.Off) {\n return;\n }\n const lspMessage = {\n isLSPMessage: true,\n type,\n message,\n timestamp: Date.now()\n };\n tracer.log(lspMessage);\n }\n function throwIfClosedOrDisposed() {\n if (isClosed()) {\n throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');\n }\n if (isDisposed()) {\n throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');\n }\n }\n function throwIfListening() {\n if (isListening()) {\n throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');\n }\n }\n function throwIfNotListening() {\n if (!isListening()) {\n throw new Error('Call listen() first.');\n }\n }\n function undefinedToNull(param) {\n if (param === undefined) {\n return null;\n }\n else {\n return param;\n }\n }\n function nullToUndefined(param) {\n if (param === null) {\n return undefined;\n }\n else {\n return param;\n }\n }\n function isNamedParam(param) {\n return param !== undefined && param !== null && !Array.isArray(param) && typeof param === 'object';\n }\n function computeSingleParam(parameterStructures, param) {\n switch (parameterStructures) {\n case messages_1.ParameterStructures.auto:\n if (isNamedParam(param)) {\n return nullToUndefined(param);\n }\n else {\n return [undefinedToNull(param)];\n }\n case messages_1.ParameterStructures.byName:\n if (!isNamedParam(param)) {\n throw new Error(`Received parameters by name but param is not an object literal.`);\n }\n return nullToUndefined(param);\n case messages_1.ParameterStructures.byPosition:\n return [undefinedToNull(param)];\n default:\n throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);\n }\n }\n function computeMessageParams(type, params) {\n let result;\n const numberOfParams = type.numberOfParams;\n switch (numberOfParams) {\n case 0:\n result = undefined;\n break;\n case 1:\n result = computeSingleParam(type.parameterStructures, params[0]);\n break;\n default:\n result = [];\n for (let i = 0; i < params.length && i < numberOfParams; i++) {\n result.push(undefinedToNull(params[i]));\n }\n if (params.length < numberOfParams) {\n for (let i = params.length; i < numberOfParams; i++) {\n result.push(null);\n }\n }\n break;\n }\n return result;\n }\n const connection = {\n sendNotification: (type, ...args) => {\n throwIfClosedOrDisposed();\n let method;\n let messageParams;\n if (Is.string(type)) {\n method = type;\n const first = args[0];\n let paramStart = 0;\n let parameterStructures = messages_1.ParameterStructures.auto;\n if (messages_1.ParameterStructures.is(first)) {\n paramStart = 1;\n parameterStructures = first;\n }\n let paramEnd = args.length;\n const numberOfParams = paramEnd - paramStart;\n switch (numberOfParams) {\n case 0:\n messageParams = undefined;\n break;\n case 1:\n messageParams = computeSingleParam(parameterStructures, args[paramStart]);\n break;\n default:\n if (parameterStructures === messages_1.ParameterStructures.byName) {\n throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);\n }\n messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value));\n break;\n }\n }\n else {\n const params = args;\n method = type.method;\n messageParams = computeMessageParams(type, params);\n }\n const notificationMessage = {\n jsonrpc: version,\n method: method,\n params: messageParams\n };\n traceSendingNotification(notificationMessage);\n return messageWriter.write(notificationMessage).catch((error) => {\n logger.error(`Sending notification failed.`);\n throw error;\n });\n },\n onNotification: (type, handler) => {\n throwIfClosedOrDisposed();\n let method;\n if (Is.func(type)) {\n starNotificationHandler = type;\n }\n else if (handler) {\n if (Is.string(type)) {\n method = type;\n notificationHandlers.set(type, { type: undefined, handler });\n }\n else {\n method = type.method;\n notificationHandlers.set(type.method, { type, handler });\n }\n }\n return {\n dispose: () => {\n if (method !== undefined) {\n notificationHandlers.delete(method);\n }\n else {\n starNotificationHandler = undefined;\n }\n }\n };\n },\n onProgress: (_type, token, handler) => {\n if (progressHandlers.has(token)) {\n throw new Error(`Progress handler for token ${token} already registered`);\n }\n progressHandlers.set(token, handler);\n return {\n dispose: () => {\n progressHandlers.delete(token);\n }\n };\n },\n sendProgress: (_type, token, value) => {\n // This should not await but simple return to ensure that we don't have another\n // async scheduling. Otherwise one send could overtake another send.\n return connection.sendNotification(ProgressNotification.type, { token, value });\n },\n onUnhandledProgress: unhandledProgressEmitter.event,\n sendRequest: (type, ...args) => {\n throwIfClosedOrDisposed();\n throwIfNotListening();\n let method;\n let messageParams;\n let token = undefined;\n if (Is.string(type)) {\n method = type;\n const first = args[0];\n const last = args[args.length - 1];\n let paramStart = 0;\n let parameterStructures = messages_1.ParameterStructures.auto;\n if (messages_1.ParameterStructures.is(first)) {\n paramStart = 1;\n parameterStructures = first;\n }\n let paramEnd = args.length;\n if (cancellation_1.CancellationToken.is(last)) {\n paramEnd = paramEnd - 1;\n token = last;\n }\n const numberOfParams = paramEnd - paramStart;\n switch (numberOfParams) {\n case 0:\n messageParams = undefined;\n break;\n case 1:\n messageParams = computeSingleParam(parameterStructures, args[paramStart]);\n break;\n default:\n if (parameterStructures === messages_1.ParameterStructures.byName) {\n throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);\n }\n messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value));\n break;\n }\n }\n else {\n const params = args;\n method = type.method;\n messageParams = computeMessageParams(type, params);\n const numberOfParams = type.numberOfParams;\n token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;\n }\n const id = sequenceNumber++;\n let disposable;\n if (token) {\n disposable = token.onCancellationRequested(() => {\n const p = cancellationStrategy.sender.sendCancellation(connection, id);\n if (p === undefined) {\n logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`);\n return Promise.resolve();\n }\n else {\n return p.catch(() => {\n logger.log(`Sending cancellation messages for id ${id} failed`);\n });\n }\n });\n }\n const requestMessage = {\n jsonrpc: version,\n id: id,\n method: method,\n params: messageParams\n };\n traceSendingRequest(requestMessage);\n if (typeof cancellationStrategy.sender.enableCancellation === 'function') {\n cancellationStrategy.sender.enableCancellation(requestMessage);\n }\n return new Promise(async (resolve, reject) => {\n const resolveWithCleanup = (r) => {\n resolve(r);\n cancellationStrategy.sender.cleanup(id);\n disposable?.dispose();\n };\n const rejectWithCleanup = (r) => {\n reject(r);\n cancellationStrategy.sender.cleanup(id);\n disposable?.dispose();\n };\n const responsePromise = { method: method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };\n try {\n await messageWriter.write(requestMessage);\n responsePromises.set(id, responsePromise);\n }\n catch (error) {\n logger.error(`Sending request failed.`);\n // Writing the message failed. So we need to reject the promise.\n responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : 'Unknown reason'));\n throw error;\n }\n });\n },\n onRequest: (type, handler) => {\n throwIfClosedOrDisposed();\n let method = null;\n if (StarRequestHandler.is(type)) {\n method = undefined;\n starRequestHandler = type;\n }\n else if (Is.string(type)) {\n method = null;\n if (handler !== undefined) {\n method = type;\n requestHandlers.set(type, { handler: handler, type: undefined });\n }\n }\n else {\n if (handler !== undefined) {\n method = type.method;\n requestHandlers.set(type.method, { type, handler });\n }\n }\n return {\n dispose: () => {\n if (method === null) {\n return;\n }\n if (method !== undefined) {\n requestHandlers.delete(method);\n }\n else {\n starRequestHandler = undefined;\n }\n }\n };\n },\n hasPendingResponse: () => {\n return responsePromises.size > 0;\n },\n trace: async (_value, _tracer, sendNotificationOrTraceOptions) => {\n let _sendNotification = false;\n let _traceFormat = TraceFormat.Text;\n if (sendNotificationOrTraceOptions !== undefined) {\n if (Is.boolean(sendNotificationOrTraceOptions)) {\n _sendNotification = sendNotificationOrTraceOptions;\n }\n else {\n _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;\n _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;\n }\n }\n trace = _value;\n traceFormat = _traceFormat;\n if (trace === Trace.Off) {\n tracer = undefined;\n }\n else {\n tracer = _tracer;\n }\n if (_sendNotification && !isClosed() && !isDisposed()) {\n await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });\n }\n },\n onError: errorEmitter.event,\n onClose: closeEmitter.event,\n onUnhandledNotification: unhandledNotificationEmitter.event,\n onDispose: disposeEmitter.event,\n end: () => {\n messageWriter.end();\n },\n dispose: () => {\n if (isDisposed()) {\n return;\n }\n state = ConnectionState.Disposed;\n disposeEmitter.fire(undefined);\n const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, 'Pending response rejected since connection got disposed');\n for (const promise of responsePromises.values()) {\n promise.reject(error);\n }\n responsePromises = new Map();\n requestTokens = new Map();\n knownCanceledRequests = new Set();\n messageQueue = new linkedMap_1.LinkedMap();\n // Test for backwards compatibility\n if (Is.func(messageWriter.dispose)) {\n messageWriter.dispose();\n }\n if (Is.func(messageReader.dispose)) {\n messageReader.dispose();\n }\n },\n listen: () => {\n throwIfClosedOrDisposed();\n throwIfListening();\n state = ConnectionState.Listening;\n messageReader.listen(callback);\n },\n inspect: () => {\n // eslint-disable-next-line no-console\n (0, ral_1.default)().console.log('inspect');\n }\n };\n connection.onNotification(LogTraceNotification.type, (params) => {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n const verbose = trace === Trace.Verbose || trace === Trace.Compact;\n tracer.log(params.message, verbose ? params.verbose : undefined);\n });\n connection.onNotification(ProgressNotification.type, (params) => {\n const handler = progressHandlers.get(params.token);\n if (handler) {\n handler(params.value);\n }\n else {\n unhandledProgressEmitter.fire(params);\n }\n });\n return connection;\n}\nexports.createMessageConnection = createMessageConnection;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\n/// \nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ProgressType = exports.ProgressToken = exports.createMessageConnection = exports.NullLogger = exports.ConnectionOptions = exports.ConnectionStrategy = exports.AbstractMessageBuffer = exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = exports.CancellationToken = exports.CancellationTokenSource = exports.Emitter = exports.Event = exports.Disposable = exports.LRUCache = exports.Touch = exports.LinkedMap = exports.ParameterStructures = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.ErrorCodes = exports.ResponseError = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType0 = exports.RequestType = exports.Message = exports.RAL = void 0;\nexports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = void 0;\nconst messages_1 = require(\"./messages\");\nObject.defineProperty(exports, \"Message\", { enumerable: true, get: function () { return messages_1.Message; } });\nObject.defineProperty(exports, \"RequestType\", { enumerable: true, get: function () { return messages_1.RequestType; } });\nObject.defineProperty(exports, \"RequestType0\", { enumerable: true, get: function () { return messages_1.RequestType0; } });\nObject.defineProperty(exports, \"RequestType1\", { enumerable: true, get: function () { return messages_1.RequestType1; } });\nObject.defineProperty(exports, \"RequestType2\", { enumerable: true, get: function () { return messages_1.RequestType2; } });\nObject.defineProperty(exports, \"RequestType3\", { enumerable: true, get: function () { return messages_1.RequestType3; } });\nObject.defineProperty(exports, \"RequestType4\", { enumerable: true, get: function () { return messages_1.RequestType4; } });\nObject.defineProperty(exports, \"RequestType5\", { enumerable: true, get: function () { return messages_1.RequestType5; } });\nObject.defineProperty(exports, \"RequestType6\", { enumerable: true, get: function () { return messages_1.RequestType6; } });\nObject.defineProperty(exports, \"RequestType7\", { enumerable: true, get: function () { return messages_1.RequestType7; } });\nObject.defineProperty(exports, \"RequestType8\", { enumerable: true, get: function () { return messages_1.RequestType8; } });\nObject.defineProperty(exports, \"RequestType9\", { enumerable: true, get: function () { return messages_1.RequestType9; } });\nObject.defineProperty(exports, \"ResponseError\", { enumerable: true, get: function () { return messages_1.ResponseError; } });\nObject.defineProperty(exports, \"ErrorCodes\", { enumerable: true, get: function () { return messages_1.ErrorCodes; } });\nObject.defineProperty(exports, \"NotificationType\", { enumerable: true, get: function () { return messages_1.NotificationType; } });\nObject.defineProperty(exports, \"NotificationType0\", { enumerable: true, get: function () { return messages_1.NotificationType0; } });\nObject.defineProperty(exports, \"NotificationType1\", { enumerable: true, get: function () { return messages_1.NotificationType1; } });\nObject.defineProperty(exports, \"NotificationType2\", { enumerable: true, get: function () { return messages_1.NotificationType2; } });\nObject.defineProperty(exports, \"NotificationType3\", { enumerable: true, get: function () { return messages_1.NotificationType3; } });\nObject.defineProperty(exports, \"NotificationType4\", { enumerable: true, get: function () { return messages_1.NotificationType4; } });\nObject.defineProperty(exports, \"NotificationType5\", { enumerable: true, get: function () { return messages_1.NotificationType5; } });\nObject.defineProperty(exports, \"NotificationType6\", { enumerable: true, get: function () { return messages_1.NotificationType6; } });\nObject.defineProperty(exports, \"NotificationType7\", { enumerable: true, get: function () { return messages_1.NotificationType7; } });\nObject.defineProperty(exports, \"NotificationType8\", { enumerable: true, get: function () { return messages_1.NotificationType8; } });\nObject.defineProperty(exports, \"NotificationType9\", { enumerable: true, get: function () { return messages_1.NotificationType9; } });\nObject.defineProperty(exports, \"ParameterStructures\", { enumerable: true, get: function () { return messages_1.ParameterStructures; } });\nconst linkedMap_1 = require(\"./linkedMap\");\nObject.defineProperty(exports, \"LinkedMap\", { enumerable: true, get: function () { return linkedMap_1.LinkedMap; } });\nObject.defineProperty(exports, \"LRUCache\", { enumerable: true, get: function () { return linkedMap_1.LRUCache; } });\nObject.defineProperty(exports, \"Touch\", { enumerable: true, get: function () { return linkedMap_1.Touch; } });\nconst disposable_1 = require(\"./disposable\");\nObject.defineProperty(exports, \"Disposable\", { enumerable: true, get: function () { return disposable_1.Disposable; } });\nconst events_1 = require(\"./events\");\nObject.defineProperty(exports, \"Event\", { enumerable: true, get: function () { return events_1.Event; } });\nObject.defineProperty(exports, \"Emitter\", { enumerable: true, get: function () { return events_1.Emitter; } });\nconst cancellation_1 = require(\"./cancellation\");\nObject.defineProperty(exports, \"CancellationTokenSource\", { enumerable: true, get: function () { return cancellation_1.CancellationTokenSource; } });\nObject.defineProperty(exports, \"CancellationToken\", { enumerable: true, get: function () { return cancellation_1.CancellationToken; } });\nconst sharedArrayCancellation_1 = require(\"./sharedArrayCancellation\");\nObject.defineProperty(exports, \"SharedArraySenderStrategy\", { enumerable: true, get: function () { return sharedArrayCancellation_1.SharedArraySenderStrategy; } });\nObject.defineProperty(exports, \"SharedArrayReceiverStrategy\", { enumerable: true, get: function () { return sharedArrayCancellation_1.SharedArrayReceiverStrategy; } });\nconst messageReader_1 = require(\"./messageReader\");\nObject.defineProperty(exports, \"MessageReader\", { enumerable: true, get: function () { return messageReader_1.MessageReader; } });\nObject.defineProperty(exports, \"AbstractMessageReader\", { enumerable: true, get: function () { return messageReader_1.AbstractMessageReader; } });\nObject.defineProperty(exports, \"ReadableStreamMessageReader\", { enumerable: true, get: function () { return messageReader_1.ReadableStreamMessageReader; } });\nconst messageWriter_1 = require(\"./messageWriter\");\nObject.defineProperty(exports, \"MessageWriter\", { enumerable: true, get: function () { return messageWriter_1.MessageWriter; } });\nObject.defineProperty(exports, \"AbstractMessageWriter\", { enumerable: true, get: function () { return messageWriter_1.AbstractMessageWriter; } });\nObject.defineProperty(exports, \"WriteableStreamMessageWriter\", { enumerable: true, get: function () { return messageWriter_1.WriteableStreamMessageWriter; } });\nconst messageBuffer_1 = require(\"./messageBuffer\");\nObject.defineProperty(exports, \"AbstractMessageBuffer\", { enumerable: true, get: function () { return messageBuffer_1.AbstractMessageBuffer; } });\nconst connection_1 = require(\"./connection\");\nObject.defineProperty(exports, \"ConnectionStrategy\", { enumerable: true, get: function () { return connection_1.ConnectionStrategy; } });\nObject.defineProperty(exports, \"ConnectionOptions\", { enumerable: true, get: function () { return connection_1.ConnectionOptions; } });\nObject.defineProperty(exports, \"NullLogger\", { enumerable: true, get: function () { return connection_1.NullLogger; } });\nObject.defineProperty(exports, \"createMessageConnection\", { enumerable: true, get: function () { return connection_1.createMessageConnection; } });\nObject.defineProperty(exports, \"ProgressToken\", { enumerable: true, get: function () { return connection_1.ProgressToken; } });\nObject.defineProperty(exports, \"ProgressType\", { enumerable: true, get: function () { return connection_1.ProgressType; } });\nObject.defineProperty(exports, \"Trace\", { enumerable: true, get: function () { return connection_1.Trace; } });\nObject.defineProperty(exports, \"TraceValues\", { enumerable: true, get: function () { return connection_1.TraceValues; } });\nObject.defineProperty(exports, \"TraceFormat\", { enumerable: true, get: function () { return connection_1.TraceFormat; } });\nObject.defineProperty(exports, \"SetTraceNotification\", { enumerable: true, get: function () { return connection_1.SetTraceNotification; } });\nObject.defineProperty(exports, \"LogTraceNotification\", { enumerable: true, get: function () { return connection_1.LogTraceNotification; } });\nObject.defineProperty(exports, \"ConnectionErrors\", { enumerable: true, get: function () { return connection_1.ConnectionErrors; } });\nObject.defineProperty(exports, \"ConnectionError\", { enumerable: true, get: function () { return connection_1.ConnectionError; } });\nObject.defineProperty(exports, \"CancellationReceiverStrategy\", { enumerable: true, get: function () { return connection_1.CancellationReceiverStrategy; } });\nObject.defineProperty(exports, \"CancellationSenderStrategy\", { enumerable: true, get: function () { return connection_1.CancellationSenderStrategy; } });\nObject.defineProperty(exports, \"CancellationStrategy\", { enumerable: true, get: function () { return connection_1.CancellationStrategy; } });\nObject.defineProperty(exports, \"MessageStrategy\", { enumerable: true, get: function () { return connection_1.MessageStrategy; } });\nconst ral_1 = require(\"./ral\");\nexports.RAL = ral_1.default;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"util\");\nconst api_1 = require(\"../common/api\");\nclass MessageBuffer extends api_1.AbstractMessageBuffer {\n constructor(encoding = 'utf-8') {\n super(encoding);\n }\n emptyBuffer() {\n return MessageBuffer.emptyBuffer;\n }\n fromString(value, encoding) {\n return Buffer.from(value, encoding);\n }\n toString(value, encoding) {\n if (value instanceof Buffer) {\n return value.toString(encoding);\n }\n else {\n return new util_1.TextDecoder(encoding).decode(value);\n }\n }\n asNative(buffer, length) {\n if (length === undefined) {\n return buffer instanceof Buffer ? buffer : Buffer.from(buffer);\n }\n else {\n return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length);\n }\n }\n allocNative(length) {\n return Buffer.allocUnsafe(length);\n }\n}\nMessageBuffer.emptyBuffer = Buffer.allocUnsafe(0);\nclass ReadableStreamWrapper {\n constructor(stream) {\n this.stream = stream;\n }\n onClose(listener) {\n this.stream.on('close', listener);\n return api_1.Disposable.create(() => this.stream.off('close', listener));\n }\n onError(listener) {\n this.stream.on('error', listener);\n return api_1.Disposable.create(() => this.stream.off('error', listener));\n }\n onEnd(listener) {\n this.stream.on('end', listener);\n return api_1.Disposable.create(() => this.stream.off('end', listener));\n }\n onData(listener) {\n this.stream.on('data', listener);\n return api_1.Disposable.create(() => this.stream.off('data', listener));\n }\n}\nclass WritableStreamWrapper {\n constructor(stream) {\n this.stream = stream;\n }\n onClose(listener) {\n this.stream.on('close', listener);\n return api_1.Disposable.create(() => this.stream.off('close', listener));\n }\n onError(listener) {\n this.stream.on('error', listener);\n return api_1.Disposable.create(() => this.stream.off('error', listener));\n }\n onEnd(listener) {\n this.stream.on('end', listener);\n return api_1.Disposable.create(() => this.stream.off('end', listener));\n }\n write(data, encoding) {\n return new Promise((resolve, reject) => {\n const callback = (error) => {\n if (error === undefined || error === null) {\n resolve();\n }\n else {\n reject(error);\n }\n };\n if (typeof data === 'string') {\n this.stream.write(data, encoding, callback);\n }\n else {\n this.stream.write(data, callback);\n }\n });\n }\n end() {\n this.stream.end();\n }\n}\nconst _ril = Object.freeze({\n messageBuffer: Object.freeze({\n create: (encoding) => new MessageBuffer(encoding)\n }),\n applicationJson: Object.freeze({\n encoder: Object.freeze({\n name: 'application/json',\n encode: (msg, options) => {\n try {\n return Promise.resolve(Buffer.from(JSON.stringify(msg, undefined, 0), options.charset));\n }\n catch (err) {\n return Promise.reject(err);\n }\n }\n }),\n decoder: Object.freeze({\n name: 'application/json',\n decode: (buffer, options) => {\n try {\n if (buffer instanceof Buffer) {\n return Promise.resolve(JSON.parse(buffer.toString(options.charset)));\n }\n else {\n return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer)));\n }\n }\n catch (err) {\n return Promise.reject(err);\n }\n }\n })\n }),\n stream: Object.freeze({\n asReadableStream: (stream) => new ReadableStreamWrapper(stream),\n asWritableStream: (stream) => new WritableStreamWrapper(stream)\n }),\n console: console,\n timer: Object.freeze({\n setTimeout(callback, ms, ...args) {\n const handle = setTimeout(callback, ms, ...args);\n return { dispose: () => clearTimeout(handle) };\n },\n setImmediate(callback, ...args) {\n const handle = setImmediate(callback, ...args);\n return { dispose: () => clearImmediate(handle) };\n },\n setInterval(callback, ms, ...args) {\n const handle = setInterval(callback, ms, ...args);\n return { dispose: () => clearInterval(handle) };\n }\n })\n});\nfunction RIL() {\n return _ril;\n}\n(function (RIL) {\n function install() {\n api_1.RAL.install(_ril);\n }\n RIL.install = install;\n})(RIL || (RIL = {}));\nexports.default = RIL;\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createMessageConnection = exports.createServerSocketTransport = exports.createClientSocketTransport = exports.createServerPipeTransport = exports.createClientPipeTransport = exports.generateRandomPipeName = exports.StreamMessageWriter = exports.StreamMessageReader = exports.SocketMessageWriter = exports.SocketMessageReader = exports.PortMessageWriter = exports.PortMessageReader = exports.IPCMessageWriter = exports.IPCMessageReader = void 0;\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ----------------------------------------------------------------------------------------- */\nconst ril_1 = require(\"./ril\");\n// Install the node runtime abstract.\nril_1.default.install();\nconst path = require(\"path\");\nconst os = require(\"os\");\nconst crypto_1 = require(\"crypto\");\nconst net_1 = require(\"net\");\nconst api_1 = require(\"../common/api\");\n__exportStar(require(\"../common/api\"), exports);\nclass IPCMessageReader extends api_1.AbstractMessageReader {\n constructor(process) {\n super();\n this.process = process;\n let eventEmitter = this.process;\n eventEmitter.on('error', (error) => this.fireError(error));\n eventEmitter.on('close', () => this.fireClose());\n }\n listen(callback) {\n this.process.on('message', callback);\n return api_1.Disposable.create(() => this.process.off('message', callback));\n }\n}\nexports.IPCMessageReader = IPCMessageReader;\nclass IPCMessageWriter extends api_1.AbstractMessageWriter {\n constructor(process) {\n super();\n this.process = process;\n this.errorCount = 0;\n const eventEmitter = this.process;\n eventEmitter.on('error', (error) => this.fireError(error));\n eventEmitter.on('close', () => this.fireClose);\n }\n write(msg) {\n try {\n if (typeof this.process.send === 'function') {\n this.process.send(msg, undefined, undefined, (error) => {\n if (error) {\n this.errorCount++;\n this.handleError(error, msg);\n }\n else {\n this.errorCount = 0;\n }\n });\n }\n return Promise.resolve();\n }\n catch (error) {\n this.handleError(error, msg);\n return Promise.reject(error);\n }\n }\n handleError(error, msg) {\n this.errorCount++;\n this.fireError(error, msg, this.errorCount);\n }\n end() {\n }\n}\nexports.IPCMessageWriter = IPCMessageWriter;\nclass PortMessageReader extends api_1.AbstractMessageReader {\n constructor(port) {\n super();\n this.onData = new api_1.Emitter;\n port.on('close', () => this.fireClose);\n port.on('error', (error) => this.fireError(error));\n port.on('message', (message) => {\n this.onData.fire(message);\n });\n }\n listen(callback) {\n return this.onData.event(callback);\n }\n}\nexports.PortMessageReader = PortMessageReader;\nclass PortMessageWriter extends api_1.AbstractMessageWriter {\n constructor(port) {\n super();\n this.port = port;\n this.errorCount = 0;\n port.on('close', () => this.fireClose());\n port.on('error', (error) => this.fireError(error));\n }\n write(msg) {\n try {\n this.port.postMessage(msg);\n return Promise.resolve();\n }\n catch (error) {\n this.handleError(error, msg);\n return Promise.reject(error);\n }\n }\n handleError(error, msg) {\n this.errorCount++;\n this.fireError(error, msg, this.errorCount);\n }\n end() {\n }\n}\nexports.PortMessageWriter = PortMessageWriter;\nclass SocketMessageReader extends api_1.ReadableStreamMessageReader {\n constructor(socket, encoding = 'utf-8') {\n super((0, ril_1.default)().stream.asReadableStream(socket), encoding);\n }\n}\nexports.SocketMessageReader = SocketMessageReader;\nclass SocketMessageWriter extends api_1.WriteableStreamMessageWriter {\n constructor(socket, options) {\n super((0, ril_1.default)().stream.asWritableStream(socket), options);\n this.socket = socket;\n }\n dispose() {\n super.dispose();\n this.socket.destroy();\n }\n}\nexports.SocketMessageWriter = SocketMessageWriter;\nclass StreamMessageReader extends api_1.ReadableStreamMessageReader {\n constructor(readable, encoding) {\n super((0, ril_1.default)().stream.asReadableStream(readable), encoding);\n }\n}\nexports.StreamMessageReader = StreamMessageReader;\nclass StreamMessageWriter extends api_1.WriteableStreamMessageWriter {\n constructor(writable, options) {\n super((0, ril_1.default)().stream.asWritableStream(writable), options);\n }\n}\nexports.StreamMessageWriter = StreamMessageWriter;\nconst XDG_RUNTIME_DIR = process.env['XDG_RUNTIME_DIR'];\nconst safeIpcPathLengths = new Map([\n ['linux', 107],\n ['darwin', 103]\n]);\nfunction generateRandomPipeName() {\n const randomSuffix = (0, crypto_1.randomBytes)(21).toString('hex');\n if (process.platform === 'win32') {\n return `\\\\\\\\.\\\\pipe\\\\vscode-jsonrpc-${randomSuffix}-sock`;\n }\n let result;\n if (XDG_RUNTIME_DIR) {\n result = path.join(XDG_RUNTIME_DIR, `vscode-ipc-${randomSuffix}.sock`);\n }\n else {\n result = path.join(os.tmpdir(), `vscode-${randomSuffix}.sock`);\n }\n const limit = safeIpcPathLengths.get(process.platform);\n if (limit !== undefined && result.length > limit) {\n (0, ril_1.default)().console.warn(`WARNING: IPC handle \"${result}\" is longer than ${limit} characters.`);\n }\n return result;\n}\nexports.generateRandomPipeName = generateRandomPipeName;\nfunction createClientPipeTransport(pipeName, encoding = 'utf-8') {\n let connectResolve;\n const connected = new Promise((resolve, _reject) => {\n connectResolve = resolve;\n });\n return new Promise((resolve, reject) => {\n let server = (0, net_1.createServer)((socket) => {\n server.close();\n connectResolve([\n new SocketMessageReader(socket, encoding),\n new SocketMessageWriter(socket, encoding)\n ]);\n });\n server.on('error', reject);\n server.listen(pipeName, () => {\n server.removeListener('error', reject);\n resolve({\n onConnected: () => { return connected; }\n });\n });\n });\n}\nexports.createClientPipeTransport = createClientPipeTransport;\nfunction createServerPipeTransport(pipeName, encoding = 'utf-8') {\n const socket = (0, net_1.createConnection)(pipeName);\n return [\n new SocketMessageReader(socket, encoding),\n new SocketMessageWriter(socket, encoding)\n ];\n}\nexports.createServerPipeTransport = createServerPipeTransport;\nfunction createClientSocketTransport(port, encoding = 'utf-8') {\n let connectResolve;\n const connected = new Promise((resolve, _reject) => {\n connectResolve = resolve;\n });\n return new Promise((resolve, reject) => {\n const server = (0, net_1.createServer)((socket) => {\n server.close();\n connectResolve([\n new SocketMessageReader(socket, encoding),\n new SocketMessageWriter(socket, encoding)\n ]);\n });\n server.on('error', reject);\n server.listen(port, '127.0.0.1', () => {\n server.removeListener('error', reject);\n resolve({\n onConnected: () => { return connected; }\n });\n });\n });\n}\nexports.createClientSocketTransport = createClientSocketTransport;\nfunction createServerSocketTransport(port, encoding = 'utf-8') {\n const socket = (0, net_1.createConnection)(port, '127.0.0.1');\n return [\n new SocketMessageReader(socket, encoding),\n new SocketMessageWriter(socket, encoding)\n ];\n}\nexports.createServerSocketTransport = createServerSocketTransport;\nfunction isReadableStream(value) {\n const candidate = value;\n return candidate.read !== undefined && candidate.addListener !== undefined;\n}\nfunction isWritableStream(value) {\n const candidate = value;\n return candidate.write !== undefined && candidate.addListener !== undefined;\n}\nfunction createMessageConnection(input, output, logger, options) {\n if (!logger) {\n logger = api_1.NullLogger;\n }\n const reader = isReadableStream(input) ? new StreamMessageReader(input) : input;\n const writer = isWritableStream(output) ? new StreamMessageWriter(output) : output;\n if (api_1.ConnectionStrategy.is(options)) {\n options = { connectionStrategy: options };\n }\n return (0, api_1.createMessageConnection)(reader, writer, logger, options);\n}\nexports.createMessageConnection = createMessageConnection;\n", "/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ----------------------------------------------------------------------------------------- */\n'use strict';\n\nmodule.exports = require('./lib/node/main');", "(function (factory) {\n if (typeof module === \"object\" && typeof module.exports === \"object\") {\n var v = factory(require, exports);\n if (v !== undefined) module.exports = v;\n }\n else if (typeof define === \"function\" && define.amd) {\n define([\"require\", \"exports\"], factory);\n }\n})(function (require, exports) {\n /* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\n 'use strict';\n Object.defineProperty(exports, \"__esModule\", { value: true });\n exports.TextDocument = exports.EOL = exports.WorkspaceFolder = exports.InlineCompletionContext = exports.SelectedCompletionInfo = exports.InlineCompletionTriggerKind = exports.InlineCompletionList = exports.InlineCompletionItem = exports.StringValue = exports.InlayHint = exports.InlayHintLabelPart = exports.InlayHintKind = exports.InlineValueContext = exports.InlineValueEvaluatableExpression = exports.InlineValueVariableLookup = exports.InlineValueText = exports.SemanticTokens = exports.SemanticTokenModifiers = exports.SemanticTokenTypes = exports.SelectionRange = exports.DocumentLink = exports.FormattingOptions = exports.CodeLens = exports.CodeAction = exports.CodeActionContext = exports.CodeActionTriggerKind = exports.CodeActionKind = exports.DocumentSymbol = exports.WorkspaceSymbol = exports.SymbolInformation = exports.SymbolTag = exports.SymbolKind = exports.DocumentHighlight = exports.DocumentHighlightKind = exports.SignatureInformation = exports.ParameterInformation = exports.Hover = exports.MarkedString = exports.CompletionList = exports.CompletionItem = exports.CompletionItemLabelDetails = exports.InsertTextMode = exports.InsertReplaceEdit = exports.CompletionItemTag = exports.InsertTextFormat = exports.CompletionItemKind = exports.MarkupContent = exports.MarkupKind = exports.TextDocumentItem = exports.OptionalVersionedTextDocumentIdentifier = exports.VersionedTextDocumentIdentifier = exports.TextDocumentIdentifier = exports.WorkspaceChange = exports.WorkspaceEdit = exports.DeleteFile = exports.RenameFile = exports.CreateFile = exports.TextDocumentEdit = exports.AnnotatedTextEdit = exports.ChangeAnnotationIdentifier = exports.ChangeAnnotation = exports.TextEdit = exports.Command = exports.Diagnostic = exports.CodeDescription = exports.DiagnosticTag = exports.DiagnosticSeverity = exports.DiagnosticRelatedInformation = exports.FoldingRange = exports.FoldingRangeKind = exports.ColorPresentation = exports.ColorInformation = exports.Color = exports.LocationLink = exports.Location = exports.Range = exports.Position = exports.uinteger = exports.integer = exports.URI = exports.DocumentUri = void 0;\n var DocumentUri;\n (function (DocumentUri) {\n function is(value) {\n return typeof value === 'string';\n }\n DocumentUri.is = is;\n })(DocumentUri || (exports.DocumentUri = DocumentUri = {}));\n var URI;\n (function (URI) {\n function is(value) {\n return typeof value === 'string';\n }\n URI.is = is;\n })(URI || (exports.URI = URI = {}));\n var integer;\n (function (integer) {\n integer.MIN_VALUE = -2147483648;\n integer.MAX_VALUE = 2147483647;\n function is(value) {\n return typeof value === 'number' && integer.MIN_VALUE <= value && value <= integer.MAX_VALUE;\n }\n integer.is = is;\n })(integer || (exports.integer = integer = {}));\n var uinteger;\n (function (uinteger) {\n uinteger.MIN_VALUE = 0;\n uinteger.MAX_VALUE = 2147483647;\n function is(value) {\n return typeof value === 'number' && uinteger.MIN_VALUE <= value && value <= uinteger.MAX_VALUE;\n }\n uinteger.is = is;\n })(uinteger || (exports.uinteger = uinteger = {}));\n /**\n * The Position namespace provides helper functions to work with\n * {@link Position} literals.\n */\n var Position;\n (function (Position) {\n /**\n * Creates a new Position literal from the given line and character.\n * @param line The position's line.\n * @param character The position's character.\n */\n function create(line, character) {\n if (line === Number.MAX_VALUE) {\n line = uinteger.MAX_VALUE;\n }\n if (character === Number.MAX_VALUE) {\n character = uinteger.MAX_VALUE;\n }\n return { line: line, character: character };\n }\n Position.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Position} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character);\n }\n Position.is = is;\n })(Position || (exports.Position = Position = {}));\n /**\n * The Range namespace provides helper functions to work with\n * {@link Range} literals.\n */\n var Range;\n (function (Range) {\n function create(one, two, three, four) {\n if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) {\n return { start: Position.create(one, two), end: Position.create(three, four) };\n }\n else if (Position.is(one) && Position.is(two)) {\n return { start: one, end: two };\n }\n else {\n throw new Error(\"Range#create called with invalid arguments[\".concat(one, \", \").concat(two, \", \").concat(three, \", \").concat(four, \"]\"));\n }\n }\n Range.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Range} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);\n }\n Range.is = is;\n })(Range || (exports.Range = Range = {}));\n /**\n * The Location namespace provides helper functions to work with\n * {@link Location} literals.\n */\n var Location;\n (function (Location) {\n /**\n * Creates a Location literal.\n * @param uri The location's uri.\n * @param range The location's range.\n */\n function create(uri, range) {\n return { uri: uri, range: range };\n }\n Location.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Location} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));\n }\n Location.is = is;\n })(Location || (exports.Location = Location = {}));\n /**\n * The LocationLink namespace provides helper functions to work with\n * {@link LocationLink} literals.\n */\n var LocationLink;\n (function (LocationLink) {\n /**\n * Creates a LocationLink literal.\n * @param targetUri The definition's uri.\n * @param targetRange The full range of the definition.\n * @param targetSelectionRange The span of the symbol definition at the target.\n * @param originSelectionRange The span of the symbol being defined in the originating source file.\n */\n function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {\n return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };\n }\n LocationLink.create = create;\n /**\n * Checks whether the given literal conforms to the {@link LocationLink} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)\n && Range.is(candidate.targetSelectionRange)\n && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));\n }\n LocationLink.is = is;\n })(LocationLink || (exports.LocationLink = LocationLink = {}));\n /**\n * The Color namespace provides helper functions to work with\n * {@link Color} literals.\n */\n var Color;\n (function (Color) {\n /**\n * Creates a new Color literal.\n */\n function create(red, green, blue, alpha) {\n return {\n red: red,\n green: green,\n blue: blue,\n alpha: alpha,\n };\n }\n Color.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Color} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1)\n && Is.numberRange(candidate.green, 0, 1)\n && Is.numberRange(candidate.blue, 0, 1)\n && Is.numberRange(candidate.alpha, 0, 1);\n }\n Color.is = is;\n })(Color || (exports.Color = Color = {}));\n /**\n * The ColorInformation namespace provides helper functions to work with\n * {@link ColorInformation} literals.\n */\n var ColorInformation;\n (function (ColorInformation) {\n /**\n * Creates a new ColorInformation literal.\n */\n function create(range, color) {\n return {\n range: range,\n color: color,\n };\n }\n ColorInformation.create = create;\n /**\n * Checks whether the given literal conforms to the {@link ColorInformation} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color);\n }\n ColorInformation.is = is;\n })(ColorInformation || (exports.ColorInformation = ColorInformation = {}));\n /**\n * The Color namespace provides helper functions to work with\n * {@link ColorPresentation} literals.\n */\n var ColorPresentation;\n (function (ColorPresentation) {\n /**\n * Creates a new ColorInformation literal.\n */\n function create(label, textEdit, additionalTextEdits) {\n return {\n label: label,\n textEdit: textEdit,\n additionalTextEdits: additionalTextEdits,\n };\n }\n ColorPresentation.create = create;\n /**\n * Checks whether the given literal conforms to the {@link ColorInformation} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Is.string(candidate.label)\n && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))\n && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));\n }\n ColorPresentation.is = is;\n })(ColorPresentation || (exports.ColorPresentation = ColorPresentation = {}));\n /**\n * A set of predefined range kinds.\n */\n var FoldingRangeKind;\n (function (FoldingRangeKind) {\n /**\n * Folding range for a comment\n */\n FoldingRangeKind.Comment = 'comment';\n /**\n * Folding range for an import or include\n */\n FoldingRangeKind.Imports = 'imports';\n /**\n * Folding range for a region (e.g. `#region`)\n */\n FoldingRangeKind.Region = 'region';\n })(FoldingRangeKind || (exports.FoldingRangeKind = FoldingRangeKind = {}));\n /**\n * The folding range namespace provides helper functions to work with\n * {@link FoldingRange} literals.\n */\n var FoldingRange;\n (function (FoldingRange) {\n /**\n * Creates a new FoldingRange literal.\n */\n function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) {\n var result = {\n startLine: startLine,\n endLine: endLine\n };\n if (Is.defined(startCharacter)) {\n result.startCharacter = startCharacter;\n }\n if (Is.defined(endCharacter)) {\n result.endCharacter = endCharacter;\n }\n if (Is.defined(kind)) {\n result.kind = kind;\n }\n if (Is.defined(collapsedText)) {\n result.collapsedText = collapsedText;\n }\n return result;\n }\n FoldingRange.create = create;\n /**\n * Checks whether the given literal conforms to the {@link FoldingRange} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine)\n && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter))\n && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter))\n && (Is.undefined(candidate.kind) || Is.string(candidate.kind));\n }\n FoldingRange.is = is;\n })(FoldingRange || (exports.FoldingRange = FoldingRange = {}));\n /**\n * The DiagnosticRelatedInformation namespace provides helper functions to work with\n * {@link DiagnosticRelatedInformation} literals.\n */\n var DiagnosticRelatedInformation;\n (function (DiagnosticRelatedInformation) {\n /**\n * Creates a new DiagnosticRelatedInformation literal.\n */\n function create(location, message) {\n return {\n location: location,\n message: message\n };\n }\n DiagnosticRelatedInformation.create = create;\n /**\n * Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);\n }\n DiagnosticRelatedInformation.is = is;\n })(DiagnosticRelatedInformation || (exports.DiagnosticRelatedInformation = DiagnosticRelatedInformation = {}));\n /**\n * The diagnostic's severity.\n */\n var DiagnosticSeverity;\n (function (DiagnosticSeverity) {\n /**\n * Reports an error.\n */\n DiagnosticSeverity.Error = 1;\n /**\n * Reports a warning.\n */\n DiagnosticSeverity.Warning = 2;\n /**\n * Reports an information.\n */\n DiagnosticSeverity.Information = 3;\n /**\n * Reports a hint.\n */\n DiagnosticSeverity.Hint = 4;\n })(DiagnosticSeverity || (exports.DiagnosticSeverity = DiagnosticSeverity = {}));\n /**\n * The diagnostic tags.\n *\n * @since 3.15.0\n */\n var DiagnosticTag;\n (function (DiagnosticTag) {\n /**\n * Unused or unnecessary code.\n *\n * Clients are allowed to render diagnostics with this tag faded out instead of having\n * an error squiggle.\n */\n DiagnosticTag.Unnecessary = 1;\n /**\n * Deprecated or obsolete code.\n *\n * Clients are allowed to rendered diagnostics with this tag strike through.\n */\n DiagnosticTag.Deprecated = 2;\n })(DiagnosticTag || (exports.DiagnosticTag = DiagnosticTag = {}));\n /**\n * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes.\n *\n * @since 3.16.0\n */\n var CodeDescription;\n (function (CodeDescription) {\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Is.string(candidate.href);\n }\n CodeDescription.is = is;\n })(CodeDescription || (exports.CodeDescription = CodeDescription = {}));\n /**\n * The Diagnostic namespace provides helper functions to work with\n * {@link Diagnostic} literals.\n */\n var Diagnostic;\n (function (Diagnostic) {\n /**\n * Creates a new Diagnostic literal.\n */\n function create(range, message, severity, code, source, relatedInformation) {\n var result = { range: range, message: message };\n if (Is.defined(severity)) {\n result.severity = severity;\n }\n if (Is.defined(code)) {\n result.code = code;\n }\n if (Is.defined(source)) {\n result.source = source;\n }\n if (Is.defined(relatedInformation)) {\n result.relatedInformation = relatedInformation;\n }\n return result;\n }\n Diagnostic.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Diagnostic} interface.\n */\n function is(value) {\n var _a;\n var candidate = value;\n return Is.defined(candidate)\n && Range.is(candidate.range)\n && Is.string(candidate.message)\n && (Is.number(candidate.severity) || Is.undefined(candidate.severity))\n && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))\n && (Is.undefined(candidate.codeDescription) || (Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)))\n && (Is.string(candidate.source) || Is.undefined(candidate.source))\n && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));\n }\n Diagnostic.is = is;\n })(Diagnostic || (exports.Diagnostic = Diagnostic = {}));\n /**\n * The Command namespace provides helper functions to work with\n * {@link Command} literals.\n */\n var Command;\n (function (Command) {\n /**\n * Creates a new Command literal.\n */\n function create(title, command) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n var result = { title: title, command: command };\n if (Is.defined(args) && args.length > 0) {\n result.arguments = args;\n }\n return result;\n }\n Command.create = create;\n /**\n * Checks whether the given literal conforms to the {@link Command} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);\n }\n Command.is = is;\n })(Command || (exports.Command = Command = {}));\n /**\n * The TextEdit namespace provides helper function to create replace,\n * insert and delete edits more easily.\n */\n var TextEdit;\n (function (TextEdit) {\n /**\n * Creates a replace text edit.\n * @param range The range of text to be replaced.\n * @param newText The new text.\n */\n function replace(range, newText) {\n return { range: range, newText: newText };\n }\n TextEdit.replace = replace;\n /**\n * Creates an insert text edit.\n * @param position The position to insert the text at.\n * @param newText The text to be inserted.\n */\n function insert(position, newText) {\n return { range: { start: position, end: position }, newText: newText };\n }\n TextEdit.insert = insert;\n /**\n * Creates a delete text edit.\n * @param range The range of text to be deleted.\n */\n function del(range) {\n return { range: range, newText: '' };\n }\n TextEdit.del = del;\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate)\n && Is.string(candidate.newText)\n && Range.is(candidate.range);\n }\n TextEdit.is = is;\n })(TextEdit || (exports.TextEdit = TextEdit = {}));\n var ChangeAnnotation;\n (function (ChangeAnnotation) {\n function create(label, needsConfirmation, description) {\n var result = { label: label };\n if (needsConfirmation !== undefined) {\n result.needsConfirmation = needsConfirmation;\n }\n if (description !== undefined) {\n result.description = description;\n }\n return result;\n }\n ChangeAnnotation.create = create;\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Is.string(candidate.label) &&\n (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) &&\n (Is.string(candidate.description) || candidate.description === undefined);\n }\n ChangeAnnotation.is = is;\n })(ChangeAnnotation || (exports.ChangeAnnotation = ChangeAnnotation = {}));\n var ChangeAnnotationIdentifier;\n (function (ChangeAnnotationIdentifier) {\n function is(value) {\n var candidate = value;\n return Is.string(candidate);\n }\n ChangeAnnotationIdentifier.is = is;\n })(ChangeAnnotationIdentifier || (exports.ChangeAnnotationIdentifier = ChangeAnnotationIdentifier = {}));\n var AnnotatedTextEdit;\n (function (AnnotatedTextEdit) {\n /**\n * Creates an annotated replace text edit.\n *\n * @param range The range of text to be replaced.\n * @param newText The new text.\n * @param annotation The annotation.\n */\n function replace(range, newText, annotation) {\n return { range: range, newText: newText, annotationId: annotation };\n }\n AnnotatedTextEdit.replace = replace;\n /**\n * Creates an annotated insert text edit.\n *\n * @param position The position to insert the text at.\n * @param newText The text to be inserted.\n * @param annotation The annotation.\n */\n function insert(position, newText, annotation) {\n return { range: { start: position, end: position }, newText: newText, annotationId: annotation };\n }\n AnnotatedTextEdit.insert = insert;\n /**\n * Creates an annotated delete text edit.\n *\n * @param range The range of text to be deleted.\n * @param annotation The annotation.\n */\n function del(range, annotation) {\n return { range: range, newText: '', annotationId: annotation };\n }\n AnnotatedTextEdit.del = del;\n function is(value) {\n var candidate = value;\n return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId));\n }\n AnnotatedTextEdit.is = is;\n })(AnnotatedTextEdit || (exports.AnnotatedTextEdit = AnnotatedTextEdit = {}));\n /**\n * The TextDocumentEdit namespace provides helper function to create\n * an edit that manipulates a text document.\n */\n var TextDocumentEdit;\n (function (TextDocumentEdit) {\n /**\n * Creates a new `TextDocumentEdit`\n */\n function create(textDocument, edits) {\n return { textDocument: textDocument, edits: edits };\n }\n TextDocumentEdit.create = create;\n function is(value) {\n var candidate = value;\n return Is.defined(candidate)\n && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument)\n && Array.isArray(candidate.edits);\n }\n TextDocumentEdit.is = is;\n })(TextDocumentEdit || (exports.TextDocumentEdit = TextDocumentEdit = {}));\n var CreateFile;\n (function (CreateFile) {\n function create(uri, options, annotation) {\n var result = {\n kind: 'create',\n uri: uri\n };\n if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {\n result.options = options;\n }\n if (annotation !== undefined) {\n result.annotationId = annotation;\n }\n return result;\n }\n CreateFile.create = create;\n function is(value) {\n var candidate = value;\n return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === undefined ||\n ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));\n }\n CreateFile.is = is;\n })(CreateFile || (exports.CreateFile = CreateFile = {}));\n var RenameFile;\n (function (RenameFile) {\n function create(oldUri, newUri, options, annotation) {\n var result = {\n kind: 'rename',\n oldUri: oldUri,\n newUri: newUri\n };\n if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {\n result.options = options;\n }\n if (annotation !== undefined) {\n result.annotationId = annotation;\n }\n return result;\n }\n RenameFile.create = create;\n function is(value) {\n var candidate = value;\n return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined ||\n ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));\n }\n RenameFile.is = is;\n })(RenameFile || (exports.RenameFile = RenameFile = {}));\n var DeleteFile;\n (function (DeleteFile) {\n function create(uri, options, annotation) {\n var result = {\n kind: 'delete',\n uri: uri\n };\n if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) {\n result.options = options;\n }\n if (annotation !== undefined) {\n result.annotationId = annotation;\n }\n return result;\n }\n DeleteFile.create = create;\n function is(value) {\n var candidate = value;\n return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === undefined ||\n ((candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));\n }\n DeleteFile.is = is;\n })(DeleteFile || (exports.DeleteFile = DeleteFile = {}));\n var WorkspaceEdit;\n (function (WorkspaceEdit) {\n function is(value) {\n var candidate = value;\n return candidate &&\n (candidate.changes !== undefined || candidate.documentChanges !== undefined) &&\n (candidate.documentChanges === undefined || candidate.documentChanges.every(function (change) {\n if (Is.string(change.kind)) {\n return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);\n }\n else {\n return TextDocumentEdit.is(change);\n }\n }));\n }\n WorkspaceEdit.is = is;\n })(WorkspaceEdit || (exports.WorkspaceEdit = WorkspaceEdit = {}));\n var TextEditChangeImpl = /** @class */ (function () {\n function TextEditChangeImpl(edits, changeAnnotations) {\n this.edits = edits;\n this.changeAnnotations = changeAnnotations;\n }\n TextEditChangeImpl.prototype.insert = function (position, newText, annotation) {\n var edit;\n var id;\n if (annotation === undefined) {\n edit = TextEdit.insert(position, newText);\n }\n else if (ChangeAnnotationIdentifier.is(annotation)) {\n id = annotation;\n edit = AnnotatedTextEdit.insert(position, newText, annotation);\n }\n else {\n this.assertChangeAnnotations(this.changeAnnotations);\n id = this.changeAnnotations.manage(annotation);\n edit = AnnotatedTextEdit.insert(position, newText, id);\n }\n this.edits.push(edit);\n if (id !== undefined) {\n return id;\n }\n };\n TextEditChangeImpl.prototype.replace = function (range, newText, annotation) {\n var edit;\n var id;\n if (annotation === undefined) {\n edit = TextEdit.replace(range, newText);\n }\n else if (ChangeAnnotationIdentifier.is(annotation)) {\n id = annotation;\n edit = AnnotatedTextEdit.replace(range, newText, annotation);\n }\n else {\n this.assertChangeAnnotations(this.changeAnnotations);\n id = this.changeAnnotations.manage(annotation);\n edit = AnnotatedTextEdit.replace(range, newText, id);\n }\n this.edits.push(edit);\n if (id !== undefined) {\n return id;\n }\n };\n TextEditChangeImpl.prototype.delete = function (range, annotation) {\n var edit;\n var id;\n if (annotation === undefined) {\n edit = TextEdit.del(range);\n }\n else if (ChangeAnnotationIdentifier.is(annotation)) {\n id = annotation;\n edit = AnnotatedTextEdit.del(range, annotation);\n }\n else {\n this.assertChangeAnnotations(this.changeAnnotations);\n id = this.changeAnnotations.manage(annotation);\n edit = AnnotatedTextEdit.del(range, id);\n }\n this.edits.push(edit);\n if (id !== undefined) {\n return id;\n }\n };\n TextEditChangeImpl.prototype.add = function (edit) {\n this.edits.push(edit);\n };\n TextEditChangeImpl.prototype.all = function () {\n return this.edits;\n };\n TextEditChangeImpl.prototype.clear = function () {\n this.edits.splice(0, this.edits.length);\n };\n TextEditChangeImpl.prototype.assertChangeAnnotations = function (value) {\n if (value === undefined) {\n throw new Error(\"Text edit change is not configured to manage change annotations.\");\n }\n };\n return TextEditChangeImpl;\n }());\n /**\n * A helper class\n */\n var ChangeAnnotations = /** @class */ (function () {\n function ChangeAnnotations(annotations) {\n this._annotations = annotations === undefined ? Object.create(null) : annotations;\n this._counter = 0;\n this._size = 0;\n }\n ChangeAnnotations.prototype.all = function () {\n return this._annotations;\n };\n Object.defineProperty(ChangeAnnotations.prototype, \"size\", {\n get: function () {\n return this._size;\n },\n enumerable: false,\n configurable: true\n });\n ChangeAnnotations.prototype.manage = function (idOrAnnotation, annotation) {\n var id;\n if (ChangeAnnotationIdentifier.is(idOrAnnotation)) {\n id = idOrAnnotation;\n }\n else {\n id = this.nextId();\n annotation = idOrAnnotation;\n }\n if (this._annotations[id] !== undefined) {\n throw new Error(\"Id \".concat(id, \" is already in use.\"));\n }\n if (annotation === undefined) {\n throw new Error(\"No annotation provided for id \".concat(id));\n }\n this._annotations[id] = annotation;\n this._size++;\n return id;\n };\n ChangeAnnotations.prototype.nextId = function () {\n this._counter++;\n return this._counter.toString();\n };\n return ChangeAnnotations;\n }());\n /**\n * A workspace change helps constructing changes to a workspace.\n */\n var WorkspaceChange = /** @class */ (function () {\n function WorkspaceChange(workspaceEdit) {\n var _this = this;\n this._textEditChanges = Object.create(null);\n if (workspaceEdit !== undefined) {\n this._workspaceEdit = workspaceEdit;\n if (workspaceEdit.documentChanges) {\n this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations);\n workspaceEdit.changeAnnotations = this._changeAnnotations.all();\n workspaceEdit.documentChanges.forEach(function (change) {\n if (TextDocumentEdit.is(change)) {\n var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations);\n _this._textEditChanges[change.textDocument.uri] = textEditChange;\n }\n });\n }\n else if (workspaceEdit.changes) {\n Object.keys(workspaceEdit.changes).forEach(function (key) {\n var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);\n _this._textEditChanges[key] = textEditChange;\n });\n }\n }\n else {\n this._workspaceEdit = {};\n }\n }\n Object.defineProperty(WorkspaceChange.prototype, \"edit\", {\n /**\n * Returns the underlying {@link WorkspaceEdit} literal\n * use to be returned from a workspace edit operation like rename.\n */\n get: function () {\n this.initDocumentChanges();\n if (this._changeAnnotations !== undefined) {\n if (this._changeAnnotations.size === 0) {\n this._workspaceEdit.changeAnnotations = undefined;\n }\n else {\n this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();\n }\n }\n return this._workspaceEdit;\n },\n enumerable: false,\n configurable: true\n });\n WorkspaceChange.prototype.getTextEditChange = function (key) {\n if (OptionalVersionedTextDocumentIdentifier.is(key)) {\n this.initDocumentChanges();\n if (this._workspaceEdit.documentChanges === undefined) {\n throw new Error('Workspace edit is not configured for document changes.');\n }\n var textDocument = { uri: key.uri, version: key.version };\n var result = this._textEditChanges[textDocument.uri];\n if (!result) {\n var edits = [];\n var textDocumentEdit = {\n textDocument: textDocument,\n edits: edits\n };\n this._workspaceEdit.documentChanges.push(textDocumentEdit);\n result = new TextEditChangeImpl(edits, this._changeAnnotations);\n this._textEditChanges[textDocument.uri] = result;\n }\n return result;\n }\n else {\n this.initChanges();\n if (this._workspaceEdit.changes === undefined) {\n throw new Error('Workspace edit is not configured for normal text edit changes.');\n }\n var result = this._textEditChanges[key];\n if (!result) {\n var edits = [];\n this._workspaceEdit.changes[key] = edits;\n result = new TextEditChangeImpl(edits);\n this._textEditChanges[key] = result;\n }\n return result;\n }\n };\n WorkspaceChange.prototype.initDocumentChanges = function () {\n if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {\n this._changeAnnotations = new ChangeAnnotations();\n this._workspaceEdit.documentChanges = [];\n this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();\n }\n };\n WorkspaceChange.prototype.initChanges = function () {\n if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {\n this._workspaceEdit.changes = Object.create(null);\n }\n };\n WorkspaceChange.prototype.createFile = function (uri, optionsOrAnnotation, options) {\n this.initDocumentChanges();\n if (this._workspaceEdit.documentChanges === undefined) {\n throw new Error('Workspace edit is not configured for document changes.');\n }\n var annotation;\n if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {\n annotation = optionsOrAnnotation;\n }\n else {\n options = optionsOrAnnotation;\n }\n var operation;\n var id;\n if (annotation === undefined) {\n operation = CreateFile.create(uri, options);\n }\n else {\n id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);\n operation = CreateFile.create(uri, options, id);\n }\n this._workspaceEdit.documentChanges.push(operation);\n if (id !== undefined) {\n return id;\n }\n };\n WorkspaceChange.prototype.renameFile = function (oldUri, newUri, optionsOrAnnotation, options) {\n this.initDocumentChanges();\n if (this._workspaceEdit.documentChanges === undefined) {\n throw new Error('Workspace edit is not configured for document changes.');\n }\n var annotation;\n if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {\n annotation = optionsOrAnnotation;\n }\n else {\n options = optionsOrAnnotation;\n }\n var operation;\n var id;\n if (annotation === undefined) {\n operation = RenameFile.create(oldUri, newUri, options);\n }\n else {\n id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);\n operation = RenameFile.create(oldUri, newUri, options, id);\n }\n this._workspaceEdit.documentChanges.push(operation);\n if (id !== undefined) {\n return id;\n }\n };\n WorkspaceChange.prototype.deleteFile = function (uri, optionsOrAnnotation, options) {\n this.initDocumentChanges();\n if (this._workspaceEdit.documentChanges === undefined) {\n throw new Error('Workspace edit is not configured for document changes.');\n }\n var annotation;\n if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {\n annotation = optionsOrAnnotation;\n }\n else {\n options = optionsOrAnnotation;\n }\n var operation;\n var id;\n if (annotation === undefined) {\n operation = DeleteFile.create(uri, options);\n }\n else {\n id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);\n operation = DeleteFile.create(uri, options, id);\n }\n this._workspaceEdit.documentChanges.push(operation);\n if (id !== undefined) {\n return id;\n }\n };\n return WorkspaceChange;\n }());\n exports.WorkspaceChange = WorkspaceChange;\n /**\n * The TextDocumentIdentifier namespace provides helper functions to work with\n * {@link TextDocumentIdentifier} literals.\n */\n var TextDocumentIdentifier;\n (function (TextDocumentIdentifier) {\n /**\n * Creates a new TextDocumentIdentifier literal.\n * @param uri The document's uri.\n */\n function create(uri) {\n return { uri: uri };\n }\n TextDocumentIdentifier.create = create;\n /**\n * Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Is.string(candidate.uri);\n }\n TextDocumentIdentifier.is = is;\n })(TextDocumentIdentifier || (exports.TextDocumentIdentifier = TextDocumentIdentifier = {}));\n /**\n * The VersionedTextDocumentIdentifier namespace provides helper functions to work with\n * {@link VersionedTextDocumentIdentifier} literals.\n */\n var VersionedTextDocumentIdentifier;\n (function (VersionedTextDocumentIdentifier) {\n /**\n * Creates a new VersionedTextDocumentIdentifier literal.\n * @param uri The document's uri.\n * @param version The document's version.\n */\n function create(uri, version) {\n return { uri: uri, version: version };\n }\n VersionedTextDocumentIdentifier.create = create;\n /**\n * Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version);\n }\n VersionedTextDocumentIdentifier.is = is;\n })(VersionedTextDocumentIdentifier || (exports.VersionedTextDocumentIdentifier = VersionedTextDocumentIdentifier = {}));\n /**\n * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with\n * {@link OptionalVersionedTextDocumentIdentifier} literals.\n */\n var OptionalVersionedTextDocumentIdentifier;\n (function (OptionalVersionedTextDocumentIdentifier) {\n /**\n * Creates a new OptionalVersionedTextDocumentIdentifier literal.\n * @param uri The document's uri.\n * @param version The document's version.\n */\n function create(uri, version) {\n return { uri: uri, version: version };\n }\n OptionalVersionedTextDocumentIdentifier.create = create;\n /**\n * Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version));\n }\n OptionalVersionedTextDocumentIdentifier.is = is;\n })(OptionalVersionedTextDocumentIdentifier || (exports.OptionalVersionedTextDocumentIdentifier = OptionalVersionedTextDocumentIdentifier = {}));\n /**\n * The TextDocumentItem namespace provides helper functions to work with\n * {@link TextDocumentItem} literals.\n */\n var TextDocumentItem;\n (function (TextDocumentItem) {\n /**\n * Creates a new TextDocumentItem literal.\n * @param uri The document's uri.\n * @param languageId The document's language identifier.\n * @param version The document's version number.\n * @param text The document's text.\n */\n function create(uri, languageId, version, text) {\n return { uri: uri, languageId: languageId, version: version, text: text };\n }\n TextDocumentItem.create = create;\n /**\n * Checks whether the given literal conforms to the {@link TextDocumentItem} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text);\n }\n TextDocumentItem.is = is;\n })(TextDocumentItem || (exports.TextDocumentItem = TextDocumentItem = {}));\n /**\n * Describes the content type that a client supports in various\n * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n *\n * Please note that `MarkupKinds` must not start with a `$`. This kinds\n * are reserved for internal usage.\n */\n var MarkupKind;\n (function (MarkupKind) {\n /**\n * Plain text is supported as a content format\n */\n MarkupKind.PlainText = 'plaintext';\n /**\n * Markdown is supported as a content format\n */\n MarkupKind.Markdown = 'markdown';\n /**\n * Checks whether the given value is a value of the {@link MarkupKind} type.\n */\n function is(value) {\n var candidate = value;\n return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;\n }\n MarkupKind.is = is;\n })(MarkupKind || (exports.MarkupKind = MarkupKind = {}));\n var MarkupContent;\n (function (MarkupContent) {\n /**\n * Checks whether the given value conforms to the {@link MarkupContent} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);\n }\n MarkupContent.is = is;\n })(MarkupContent || (exports.MarkupContent = MarkupContent = {}));\n /**\n * The kind of a completion entry.\n */\n var CompletionItemKind;\n (function (CompletionItemKind) {\n CompletionItemKind.Text = 1;\n CompletionItemKind.Method = 2;\n CompletionItemKind.Function = 3;\n CompletionItemKind.Constructor = 4;\n CompletionItemKind.Field = 5;\n CompletionItemKind.Variable = 6;\n CompletionItemKind.Class = 7;\n CompletionItemKind.Interface = 8;\n CompletionItemKind.Module = 9;\n CompletionItemKind.Property = 10;\n CompletionItemKind.Unit = 11;\n CompletionItemKind.Value = 12;\n CompletionItemKind.Enum = 13;\n CompletionItemKind.Keyword = 14;\n CompletionItemKind.Snippet = 15;\n CompletionItemKind.Color = 16;\n CompletionItemKind.File = 17;\n CompletionItemKind.Reference = 18;\n CompletionItemKind.Folder = 19;\n CompletionItemKind.EnumMember = 20;\n CompletionItemKind.Constant = 21;\n CompletionItemKind.Struct = 22;\n CompletionItemKind.Event = 23;\n CompletionItemKind.Operator = 24;\n CompletionItemKind.TypeParameter = 25;\n })(CompletionItemKind || (exports.CompletionItemKind = CompletionItemKind = {}));\n /**\n * Defines whether the insert text in a completion item should be interpreted as\n * plain text or a snippet.\n */\n var InsertTextFormat;\n (function (InsertTextFormat) {\n /**\n * The primary text to be inserted is treated as a plain string.\n */\n InsertTextFormat.PlainText = 1;\n /**\n * The primary text to be inserted is treated as a snippet.\n *\n * A snippet can define tab stops and placeholders with `$1`, `$2`\n * and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n * the end of the snippet. Placeholders with equal identifiers are linked,\n * that is typing in one will update others too.\n *\n * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax\n */\n InsertTextFormat.Snippet = 2;\n })(InsertTextFormat || (exports.InsertTextFormat = InsertTextFormat = {}));\n /**\n * Completion item tags are extra annotations that tweak the rendering of a completion\n * item.\n *\n * @since 3.15.0\n */\n var CompletionItemTag;\n (function (CompletionItemTag) {\n /**\n * Render a completion as obsolete, usually using a strike-out.\n */\n CompletionItemTag.Deprecated = 1;\n })(CompletionItemTag || (exports.CompletionItemTag = CompletionItemTag = {}));\n /**\n * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits.\n *\n * @since 3.16.0\n */\n var InsertReplaceEdit;\n (function (InsertReplaceEdit) {\n /**\n * Creates a new insert / replace edit\n */\n function create(newText, insert, replace) {\n return { newText: newText, insert: insert, replace: replace };\n }\n InsertReplaceEdit.create = create;\n /**\n * Checks whether the given literal conforms to the {@link InsertReplaceEdit} interface.\n */\n function is(value) {\n var candidate = value;\n return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace);\n }\n InsertReplaceEdit.is = is;\n })(InsertReplaceEdit || (exports.InsertReplaceEdit = InsertReplaceEdit = {}));\n /**\n * How whitespace and indentation is handled during completion\n * item insertion.\n *\n * @since 3.16.0\n */\n var InsertTextMode;\n (function (InsertTextMode) {\n /**\n * The insertion or replace strings is taken as it is. If the\n * value is multi line the lines below the cursor will be\n * inserted using the indentation defined in the string value.\n * The client will not apply any kind of adjustments to the\n * string.\n */\n InsertTextMode.asIs = 1;\n /**\n * The editor adjusts leading whitespace of new lines so that\n * they match the indentation up to the cursor of the line for\n * which the item is accepted.\n *\n * Consider a line like this: <2tabs><3tabs>foo. Accepting a\n * multi line completion item is indented using 2 tabs and all\n * following lines inserted will be indented using 2 tabs as well.\n */\n InsertTextMode.adjustIndentation = 2;\n })(InsertTextMode || (exports.InsertTextMode = InsertTextMode = {}));\n var CompletionItemLabelDetails;\n (function (CompletionItemLabelDetails) {\n function is(value) {\n var candidate = value;\n return candidate && (Is.string(candidate.detail) || candidate.detail === undefined) &&\n (Is.string(candidate.description) || candidate.description === undefined);\n }\n CompletionItemLabelDetails.is = is;\n })(CompletionItemLabelDetails || (exports.CompletionItemLabelDetails = CompletionItemLabelDetails = {}));\n /**\n * The CompletionItem namespace provides functions to deal with\n * completion items.\n */\n var CompletionItem;\n (function (CompletionItem) {\n /**\n * Create a completion item and seed it with a label.\n * @param label The completion item's label\n */\n function create(label) {\n return { label: label };\n }\n CompletionItem.create = create;\n })(CompletionItem || (exports.CompletionItem = CompletionItem = {}));\n /**\n * The CompletionList namespace provides functions to deal with\n * completion lists.\n */\n var CompletionList;\n (function (CompletionList) {\n /**\n * Creates a new completion list.\n *\n * @param items The completion items.\n * @param isIncomplete The list is not complete.\n */\n function create(items, isIncomplete) {\n return { items: items ? items : [], isIncomplete: !!isIncomplete };\n }\n CompletionList.create = create;\n })(CompletionList || (exports.CompletionList = CompletionList = {}));\n var MarkedString;\n (function (MarkedString) {\n /**\n * Creates a marked string from plain text.\n *\n * @param plainText The plain text.\n */\n function fromPlainText(plainText) {\n return plainText.replace(/[\\\\`*_{}[\\]()#+\\-.!]/g, '\\\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash\n }\n MarkedString.fromPlainText = fromPlainText;\n /**\n * Checks whether the given value conforms to the {@link MarkedString} type.\n */\n function is(value) {\n var candidate = value;\n return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));\n }\n MarkedString.is = is;\n })(MarkedString || (exports.MarkedString = MarkedString = {}));\n var Hover;\n (function (Hover) {\n /**\n * Checks whether the given value conforms to the {@link Hover} interface.\n */\n function is(value) {\n var candidate = value;\n return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||\n MarkedString.is(candidate.contents) ||\n Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range));\n }\n Hover.is = is;\n })(Hover || (exports.Hover = Hover = {}));\n /**\n * The ParameterInformation namespace provides helper functions to work with\n * {@link ParameterInformation} literals.\n */\n var ParameterInformation;\n (function (ParameterInformation) {\n /**\n * Creates a new parameter information literal.\n *\n * @param label A label string.\n * @param documentation A doc string.\n */\n function create(label, documentation) {\n return documentation ? { label: label, documentation: documentation } : { label: label };\n }\n ParameterInformation.create = create;\n })(ParameterInformation || (exports.ParameterInformation = ParameterInformation = {}));\n /**\n * The SignatureInformation namespace provides helper functions to work with\n * {@link SignatureInformation} literals.\n */\n var SignatureInformation;\n (function (SignatureInformation) {\n function create(label, documentation) {\n var parameters = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n parameters[_i - 2] = arguments[_i];\n }\n var result = { label: label };\n if (Is.defined(documentation)) {\n result.documentation = documentation;\n }\n if (Is.defined(parameters)) {\n result.parameters = parameters;\n }\n else {\n result.parameters = [];\n }\n return result;\n }\n SignatureInformation.create = create;\n })(SignatureInformation || (exports.SignatureInformation = SignatureInformation = {}));\n /**\n * A document highlight kind.\n */\n var DocumentHighlightKind;\n (function (DocumentHighlightKind) {\n /**\n * A textual occurrence.\n */\n DocumentHighlightKind.Text = 1;\n /**\n * Read-access of a symbol, like reading a variable.\n */\n DocumentHighlightKind.Read = 2;\n /**\n * Write-access of a symbol, like writing to a variable.\n */\n DocumentHighlightKind.Write = 3;\n })(DocumentHighlightKind || (exports.DocumentHighlightKind = DocumentHighlightKind = {}));\n /**\n * DocumentHighlight namespace to provide helper functions to work with\n * {@link DocumentHighlight} literals.\n */\n var DocumentHighlight;\n (function (DocumentHighlight) {\n /**\n * Create a DocumentHighlight object.\n * @param range The range the highlight applies to.\n * @param kind The highlight kind\n */\n function create(range, kind) {\n var result = { range: range };\n if (Is.number(kind)) {\n result.kind = kind;\n }\n return result;\n }\n DocumentHighlight.create = create;\n })(DocumentHighlight || (exports.DocumentHighlight = DocumentHighlight = {}));\n /**\n * A symbol kind.\n */\n var SymbolKind;\n (function (SymbolKind) {\n SymbolKind.File = 1;\n SymbolKind.Module = 2;\n SymbolKind.Namespace = 3;\n SymbolKind.Package = 4;\n SymbolKind.Class = 5;\n SymbolKind.Method = 6;\n SymbolKind.Property = 7;\n SymbolKind.Field = 8;\n SymbolKind.Constructor = 9;\n SymbolKind.Enum = 10;\n SymbolKind.Interface = 11;\n SymbolKind.Function = 12;\n SymbolKind.Variable = 13;\n SymbolKind.Constant = 14;\n SymbolKind.String = 15;\n SymbolKind.Number = 16;\n SymbolKind.Boolean = 17;\n SymbolKind.Array = 18;\n SymbolKind.Object = 19;\n SymbolKind.Key = 20;\n SymbolKind.Null = 21;\n SymbolKind.EnumMember = 22;\n SymbolKind.Struct = 23;\n SymbolKind.Event = 24;\n SymbolKind.Operator = 25;\n SymbolKind.TypeParameter = 26;\n })(SymbolKind || (exports.SymbolKind = SymbolKind = {}));\n /**\n * Symbol tags are extra annotations that tweak the rendering of a symbol.\n *\n * @since 3.16\n */\n var SymbolTag;\n (function (SymbolTag) {\n /**\n * Render a symbol as obsolete, usually using a strike-out.\n */\n SymbolTag.Deprecated = 1;\n })(SymbolTag || (exports.SymbolTag = SymbolTag = {}));\n var SymbolInformation;\n (function (SymbolInformation) {\n /**\n * Creates a new symbol information literal.\n *\n * @param name The name of the symbol.\n * @param kind The kind of the symbol.\n * @param range The range of the location of the symbol.\n * @param uri The resource of the location of symbol.\n * @param containerName The name of the symbol containing the symbol.\n */\n function create(name, kind, range, uri, containerName) {\n var result = {\n name: name,\n kind: kind,\n location: { uri: uri, range: range }\n };\n if (containerName) {\n result.containerName = containerName;\n }\n return result;\n }\n SymbolInformation.create = create;\n })(SymbolInformation || (exports.SymbolInformation = SymbolInformation = {}));\n var WorkspaceSymbol;\n (function (WorkspaceSymbol) {\n /**\n * Create a new workspace symbol.\n *\n * @param name The name of the symbol.\n * @param kind The kind of the symbol.\n * @param uri The resource of the location of the symbol.\n * @param range An options range of the location.\n * @returns A WorkspaceSymbol.\n */\n function create(name, kind, uri, range) {\n return range !== undefined\n ? { name: name, kind: kind, location: { uri: uri, range: range } }\n : { name: name, kind: kind, location: { uri: uri } };\n }\n WorkspaceSymbol.create = create;\n })(WorkspaceSymbol || (exports.WorkspaceSymbol = WorkspaceSymbol = {}));\n var DocumentSymbol;\n (function (DocumentSymbol) {\n /**\n * Creates a new symbol information literal.\n *\n * @param name The name of the symbol.\n * @param detail The detail of the symbol.\n * @param kind The kind of the symbol.\n * @param range The range of the symbol.\n * @param selectionRange The selectionRange of the symbol.\n * @param children Children of the symbol.\n */\n function create(name, detail, kind, range, selectionRange, children) {\n var result = {\n name: name,\n detail: detail,\n kind: kind,\n range: range,\n selectionRange: selectionRange\n };\n if (children !== undefined) {\n result.children = children;\n }\n return result;\n }\n DocumentSymbol.create = create;\n /**\n * Checks whether the given literal conforms to the {@link DocumentSymbol} interface.\n */\n function is(value) {\n var candidate = value;\n return candidate &&\n Is.string(candidate.name) && Is.number(candidate.kind) &&\n Range.is(candidate.range) && Range.is(candidate.selectionRange) &&\n (candidate.detail === undefined || Is.string(candidate.detail)) &&\n (candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) &&\n (candidate.children === undefined || Array.isArray(candidate.children)) &&\n (candidate.tags === undefined || Array.isArray(candidate.tags));\n }\n DocumentSymbol.is = is;\n })(DocumentSymbol || (exports.DocumentSymbol = DocumentSymbol = {}));\n /**\n * A set of predefined code action kinds\n */\n var CodeActionKind;\n (function (CodeActionKind) {\n /**\n * Empty kind.\n */\n CodeActionKind.Empty = '';\n /**\n * Base kind for quickfix actions: 'quickfix'\n */\n CodeActionKind.QuickFix = 'quickfix';\n /**\n * Base kind for refactoring actions: 'refactor'\n */\n CodeActionKind.Refactor = 'refactor';\n /**\n * Base kind for refactoring extraction actions: 'refactor.extract'\n *\n * Example extract actions:\n *\n * - Extract method\n * - Extract function\n * - Extract variable\n * - Extract interface from class\n * - ...\n */\n CodeActionKind.RefactorExtract = 'refactor.extract';\n /**\n * Base kind for refactoring inline actions: 'refactor.inline'\n *\n * Example inline actions:\n *\n * - Inline function\n * - Inline variable\n * - Inline constant\n * - ...\n */\n CodeActionKind.RefactorInline = 'refactor.inline';\n /**\n * Base kind for refactoring rewrite actions: 'refactor.rewrite'\n *\n * Example rewrite actions:\n *\n * - Convert JavaScript function to class\n * - Add or remove parameter\n * - Encapsulate field\n * - Make method static\n * - Move method to base class\n * - ...\n */\n CodeActionKind.RefactorRewrite = 'refactor.rewrite';\n /**\n * Base kind for source actions: `source`\n *\n * Source code actions apply to the entire file.\n */\n CodeActionKind.Source = 'source';\n /**\n * Base kind for an organize imports source action: `source.organizeImports`\n */\n CodeActionKind.SourceOrganizeImports = 'source.organizeImports';\n /**\n * Base kind for auto-fix source actions: `source.fixAll`.\n *\n * Fix all actions automatically fix errors that have a clear fix that do not require user input.\n * They should not suppress errors or perform unsafe fixes such as generating new types or classes.\n *\n * @since 3.15.0\n */\n CodeActionKind.SourceFixAll = 'source.fixAll';\n })(CodeActionKind || (exports.CodeActionKind = CodeActionKind = {}));\n /**\n * The reason why code actions were requested.\n *\n * @since 3.17.0\n */\n var CodeActionTriggerKind;\n (function (CodeActionTriggerKind) {\n /**\n * Code actions were explicitly requested by the user or by an extension.\n */\n CodeActionTriggerKind.Invoked = 1;\n /**\n * Code actions were requested automatically.\n *\n * This typically happens when current selection in a file changes, but can\n * also be triggered when file content changes.\n */\n CodeActionTriggerKind.Automatic = 2;\n })(CodeActionTriggerKind || (exports.CodeActionTriggerKind = CodeActionTriggerKind = {}));\n /**\n * The CodeActionContext namespace provides helper functions to work with\n * {@link CodeActionContext} literals.\n */\n var CodeActionContext;\n (function (CodeActionContext) {\n /**\n * Creates a new CodeActionContext literal.\n */\n function create(diagnostics, only, triggerKind) {\n var result = { diagnostics: diagnostics };\n if (only !== undefined && only !== null) {\n result.only = only;\n }\n if (triggerKind !== undefined && triggerKind !== null) {\n result.triggerKind = triggerKind;\n }\n return result;\n }\n CodeActionContext.create = create;\n /**\n * Checks whether the given literal conforms to the {@link CodeActionContext} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is)\n && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string))\n && (candidate.triggerKind === undefined || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic);\n }\n CodeActionContext.is = is;\n })(CodeActionContext || (exports.CodeActionContext = CodeActionContext = {}));\n var CodeAction;\n (function (CodeAction) {\n function create(title, kindOrCommandOrEdit, kind) {\n var result = { title: title };\n var checkKind = true;\n if (typeof kindOrCommandOrEdit === 'string') {\n checkKind = false;\n result.kind = kindOrCommandOrEdit;\n }\n else if (Command.is(kindOrCommandOrEdit)) {\n result.command = kindOrCommandOrEdit;\n }\n else {\n result.edit = kindOrCommandOrEdit;\n }\n if (checkKind && kind !== undefined) {\n result.kind = kind;\n }\n return result;\n }\n CodeAction.create = create;\n function is(value) {\n var candidate = value;\n return candidate && Is.string(candidate.title) &&\n (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&\n (candidate.kind === undefined || Is.string(candidate.kind)) &&\n (candidate.edit !== undefined || candidate.command !== undefined) &&\n (candidate.command === undefined || Command.is(candidate.command)) &&\n (candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) &&\n (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit));\n }\n CodeAction.is = is;\n })(CodeAction || (exports.CodeAction = CodeAction = {}));\n /**\n * The CodeLens namespace provides helper functions to work with\n * {@link CodeLens} literals.\n */\n var CodeLens;\n (function (CodeLens) {\n /**\n * Creates a new CodeLens literal.\n */\n function create(range, data) {\n var result = { range: range };\n if (Is.defined(data)) {\n result.data = data;\n }\n return result;\n }\n CodeLens.create = create;\n /**\n * Checks whether the given literal conforms to the {@link CodeLens} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));\n }\n CodeLens.is = is;\n })(CodeLens || (exports.CodeLens = CodeLens = {}));\n /**\n * The FormattingOptions namespace provides helper functions to work with\n * {@link FormattingOptions} literals.\n */\n var FormattingOptions;\n (function (FormattingOptions) {\n /**\n * Creates a new FormattingOptions literal.\n */\n function create(tabSize, insertSpaces) {\n return { tabSize: tabSize, insertSpaces: insertSpaces };\n }\n FormattingOptions.create = create;\n /**\n * Checks whether the given literal conforms to the {@link FormattingOptions} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces);\n }\n FormattingOptions.is = is;\n })(FormattingOptions || (exports.FormattingOptions = FormattingOptions = {}));\n /**\n * The DocumentLink namespace provides helper functions to work with\n * {@link DocumentLink} literals.\n */\n var DocumentLink;\n (function (DocumentLink) {\n /**\n * Creates a new DocumentLink literal.\n */\n function create(range, target, data) {\n return { range: range, target: target, data: data };\n }\n DocumentLink.create = create;\n /**\n * Checks whether the given literal conforms to the {@link DocumentLink} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));\n }\n DocumentLink.is = is;\n })(DocumentLink || (exports.DocumentLink = DocumentLink = {}));\n /**\n * The SelectionRange namespace provides helper function to work with\n * SelectionRange literals.\n */\n var SelectionRange;\n (function (SelectionRange) {\n /**\n * Creates a new SelectionRange\n * @param range the range.\n * @param parent an optional parent.\n */\n function create(range, parent) {\n return { range: range, parent: parent };\n }\n SelectionRange.create = create;\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));\n }\n SelectionRange.is = is;\n })(SelectionRange || (exports.SelectionRange = SelectionRange = {}));\n /**\n * A set of predefined token types. This set is not fixed\n * an clients can specify additional token types via the\n * corresponding client capabilities.\n *\n * @since 3.16.0\n */\n var SemanticTokenTypes;\n (function (SemanticTokenTypes) {\n SemanticTokenTypes[\"namespace\"] = \"namespace\";\n /**\n * Represents a generic type. Acts as a fallback for types which can't be mapped to\n * a specific type like class or enum.\n */\n SemanticTokenTypes[\"type\"] = \"type\";\n SemanticTokenTypes[\"class\"] = \"class\";\n SemanticTokenTypes[\"enum\"] = \"enum\";\n SemanticTokenTypes[\"interface\"] = \"interface\";\n SemanticTokenTypes[\"struct\"] = \"struct\";\n SemanticTokenTypes[\"typeParameter\"] = \"typeParameter\";\n SemanticTokenTypes[\"parameter\"] = \"parameter\";\n SemanticTokenTypes[\"variable\"] = \"variable\";\n SemanticTokenTypes[\"property\"] = \"property\";\n SemanticTokenTypes[\"enumMember\"] = \"enumMember\";\n SemanticTokenTypes[\"event\"] = \"event\";\n SemanticTokenTypes[\"function\"] = \"function\";\n SemanticTokenTypes[\"method\"] = \"method\";\n SemanticTokenTypes[\"macro\"] = \"macro\";\n SemanticTokenTypes[\"keyword\"] = \"keyword\";\n SemanticTokenTypes[\"modifier\"] = \"modifier\";\n SemanticTokenTypes[\"comment\"] = \"comment\";\n SemanticTokenTypes[\"string\"] = \"string\";\n SemanticTokenTypes[\"number\"] = \"number\";\n SemanticTokenTypes[\"regexp\"] = \"regexp\";\n SemanticTokenTypes[\"operator\"] = \"operator\";\n /**\n * @since 3.17.0\n */\n SemanticTokenTypes[\"decorator\"] = \"decorator\";\n })(SemanticTokenTypes || (exports.SemanticTokenTypes = SemanticTokenTypes = {}));\n /**\n * A set of predefined token modifiers. This set is not fixed\n * an clients can specify additional token types via the\n * corresponding client capabilities.\n *\n * @since 3.16.0\n */\n var SemanticTokenModifiers;\n (function (SemanticTokenModifiers) {\n SemanticTokenModifiers[\"declaration\"] = \"declaration\";\n SemanticTokenModifiers[\"definition\"] = \"definition\";\n SemanticTokenModifiers[\"readonly\"] = \"readonly\";\n SemanticTokenModifiers[\"static\"] = \"static\";\n SemanticTokenModifiers[\"deprecated\"] = \"deprecated\";\n SemanticTokenModifiers[\"abstract\"] = \"abstract\";\n SemanticTokenModifiers[\"async\"] = \"async\";\n SemanticTokenModifiers[\"modification\"] = \"modification\";\n SemanticTokenModifiers[\"documentation\"] = \"documentation\";\n SemanticTokenModifiers[\"defaultLibrary\"] = \"defaultLibrary\";\n })(SemanticTokenModifiers || (exports.SemanticTokenModifiers = SemanticTokenModifiers = {}));\n /**\n * @since 3.16.0\n */\n var SemanticTokens;\n (function (SemanticTokens) {\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&\n Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');\n }\n SemanticTokens.is = is;\n })(SemanticTokens || (exports.SemanticTokens = SemanticTokens = {}));\n /**\n * The InlineValueText namespace provides functions to deal with InlineValueTexts.\n *\n * @since 3.17.0\n */\n var InlineValueText;\n (function (InlineValueText) {\n /**\n * Creates a new InlineValueText literal.\n */\n function create(range, text) {\n return { range: range, text: text };\n }\n InlineValueText.create = create;\n function is(value) {\n var candidate = value;\n return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text);\n }\n InlineValueText.is = is;\n })(InlineValueText || (exports.InlineValueText = InlineValueText = {}));\n /**\n * The InlineValueVariableLookup namespace provides functions to deal with InlineValueVariableLookups.\n *\n * @since 3.17.0\n */\n var InlineValueVariableLookup;\n (function (InlineValueVariableLookup) {\n /**\n * Creates a new InlineValueText literal.\n */\n function create(range, variableName, caseSensitiveLookup) {\n return { range: range, variableName: variableName, caseSensitiveLookup: caseSensitiveLookup };\n }\n InlineValueVariableLookup.create = create;\n function is(value) {\n var candidate = value;\n return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup)\n && (Is.string(candidate.variableName) || candidate.variableName === undefined);\n }\n InlineValueVariableLookup.is = is;\n })(InlineValueVariableLookup || (exports.InlineValueVariableLookup = InlineValueVariableLookup = {}));\n /**\n * The InlineValueEvaluatableExpression namespace provides functions to deal with InlineValueEvaluatableExpression.\n *\n * @since 3.17.0\n */\n var InlineValueEvaluatableExpression;\n (function (InlineValueEvaluatableExpression) {\n /**\n * Creates a new InlineValueEvaluatableExpression literal.\n */\n function create(range, expression) {\n return { range: range, expression: expression };\n }\n InlineValueEvaluatableExpression.create = create;\n function is(value) {\n var candidate = value;\n return candidate !== undefined && candidate !== null && Range.is(candidate.range)\n && (Is.string(candidate.expression) || candidate.expression === undefined);\n }\n InlineValueEvaluatableExpression.is = is;\n })(InlineValueEvaluatableExpression || (exports.InlineValueEvaluatableExpression = InlineValueEvaluatableExpression = {}));\n /**\n * The InlineValueContext namespace provides helper functions to work with\n * {@link InlineValueContext} literals.\n *\n * @since 3.17.0\n */\n var InlineValueContext;\n (function (InlineValueContext) {\n /**\n * Creates a new InlineValueContext literal.\n */\n function create(frameId, stoppedLocation) {\n return { frameId: frameId, stoppedLocation: stoppedLocation };\n }\n InlineValueContext.create = create;\n /**\n * Checks whether the given literal conforms to the {@link InlineValueContext} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Range.is(value.stoppedLocation);\n }\n InlineValueContext.is = is;\n })(InlineValueContext || (exports.InlineValueContext = InlineValueContext = {}));\n /**\n * Inlay hint kinds.\n *\n * @since 3.17.0\n */\n var InlayHintKind;\n (function (InlayHintKind) {\n /**\n * An inlay hint that for a type annotation.\n */\n InlayHintKind.Type = 1;\n /**\n * An inlay hint that is for a parameter.\n */\n InlayHintKind.Parameter = 2;\n function is(value) {\n return value === 1 || value === 2;\n }\n InlayHintKind.is = is;\n })(InlayHintKind || (exports.InlayHintKind = InlayHintKind = {}));\n var InlayHintLabelPart;\n (function (InlayHintLabelPart) {\n function create(value) {\n return { value: value };\n }\n InlayHintLabelPart.create = create;\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate)\n && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip))\n && (candidate.location === undefined || Location.is(candidate.location))\n && (candidate.command === undefined || Command.is(candidate.command));\n }\n InlayHintLabelPart.is = is;\n })(InlayHintLabelPart || (exports.InlayHintLabelPart = InlayHintLabelPart = {}));\n var InlayHint;\n (function (InlayHint) {\n function create(position, label, kind) {\n var result = { position: position, label: label };\n if (kind !== undefined) {\n result.kind = kind;\n }\n return result;\n }\n InlayHint.create = create;\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && Position.is(candidate.position)\n && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is))\n && (candidate.kind === undefined || InlayHintKind.is(candidate.kind))\n && (candidate.textEdits === undefined) || Is.typedArray(candidate.textEdits, TextEdit.is)\n && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip))\n && (candidate.paddingLeft === undefined || Is.boolean(candidate.paddingLeft))\n && (candidate.paddingRight === undefined || Is.boolean(candidate.paddingRight));\n }\n InlayHint.is = is;\n })(InlayHint || (exports.InlayHint = InlayHint = {}));\n var StringValue;\n (function (StringValue) {\n function createSnippet(value) {\n return { kind: 'snippet', value: value };\n }\n StringValue.createSnippet = createSnippet;\n })(StringValue || (exports.StringValue = StringValue = {}));\n var InlineCompletionItem;\n (function (InlineCompletionItem) {\n function create(insertText, filterText, range, command) {\n return { insertText: insertText, filterText: filterText, range: range, command: command };\n }\n InlineCompletionItem.create = create;\n })(InlineCompletionItem || (exports.InlineCompletionItem = InlineCompletionItem = {}));\n var InlineCompletionList;\n (function (InlineCompletionList) {\n function create(items) {\n return { items: items };\n }\n InlineCompletionList.create = create;\n })(InlineCompletionList || (exports.InlineCompletionList = InlineCompletionList = {}));\n /**\n * Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n *\n * @since 3.18.0\n * @proposed\n */\n var InlineCompletionTriggerKind;\n (function (InlineCompletionTriggerKind) {\n /**\n * Completion was triggered explicitly by a user gesture.\n */\n InlineCompletionTriggerKind.Invoked = 0;\n /**\n * Completion was triggered automatically while editing.\n */\n InlineCompletionTriggerKind.Automatic = 1;\n })(InlineCompletionTriggerKind || (exports.InlineCompletionTriggerKind = InlineCompletionTriggerKind = {}));\n var SelectedCompletionInfo;\n (function (SelectedCompletionInfo) {\n function create(range, text) {\n return { range: range, text: text };\n }\n SelectedCompletionInfo.create = create;\n })(SelectedCompletionInfo || (exports.SelectedCompletionInfo = SelectedCompletionInfo = {}));\n var InlineCompletionContext;\n (function (InlineCompletionContext) {\n function create(triggerKind, selectedCompletionInfo) {\n return { triggerKind: triggerKind, selectedCompletionInfo: selectedCompletionInfo };\n }\n InlineCompletionContext.create = create;\n })(InlineCompletionContext || (exports.InlineCompletionContext = InlineCompletionContext = {}));\n var WorkspaceFolder;\n (function (WorkspaceFolder) {\n function is(value) {\n var candidate = value;\n return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name);\n }\n WorkspaceFolder.is = is;\n })(WorkspaceFolder || (exports.WorkspaceFolder = WorkspaceFolder = {}));\n exports.EOL = ['\\n', '\\r\\n', '\\r'];\n /**\n * @deprecated Use the text document from the new vscode-languageserver-textdocument package.\n */\n var TextDocument;\n (function (TextDocument) {\n /**\n * Creates a new ITextDocument literal from the given uri and content.\n * @param uri The document's uri.\n * @param languageId The document's language Id.\n * @param version The document's version.\n * @param content The document's content.\n */\n function create(uri, languageId, version, content) {\n return new FullTextDocument(uri, languageId, version, content);\n }\n TextDocument.create = create;\n /**\n * Checks whether the given literal conforms to the {@link ITextDocument} interface.\n */\n function is(value) {\n var candidate = value;\n return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount)\n && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;\n }\n TextDocument.is = is;\n function applyEdits(document, edits) {\n var text = document.getText();\n var sortedEdits = mergeSort(edits, function (a, b) {\n var diff = a.range.start.line - b.range.start.line;\n if (diff === 0) {\n return a.range.start.character - b.range.start.character;\n }\n return diff;\n });\n var lastModifiedOffset = text.length;\n for (var i = sortedEdits.length - 1; i >= 0; i--) {\n var e = sortedEdits[i];\n var startOffset = document.offsetAt(e.range.start);\n var endOffset = document.offsetAt(e.range.end);\n if (endOffset <= lastModifiedOffset) {\n text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);\n }\n else {\n throw new Error('Overlapping edit');\n }\n lastModifiedOffset = startOffset;\n }\n return text;\n }\n TextDocument.applyEdits = applyEdits;\n function mergeSort(data, compare) {\n if (data.length <= 1) {\n // sorted\n return data;\n }\n var p = (data.length / 2) | 0;\n var left = data.slice(0, p);\n var right = data.slice(p);\n mergeSort(left, compare);\n mergeSort(right, compare);\n var leftIdx = 0;\n var rightIdx = 0;\n var i = 0;\n while (leftIdx < left.length && rightIdx < right.length) {\n var ret = compare(left[leftIdx], right[rightIdx]);\n if (ret <= 0) {\n // smaller_equal -> take left to preserve order\n data[i++] = left[leftIdx++];\n }\n else {\n // greater -> take right\n data[i++] = right[rightIdx++];\n }\n }\n while (leftIdx < left.length) {\n data[i++] = left[leftIdx++];\n }\n while (rightIdx < right.length) {\n data[i++] = right[rightIdx++];\n }\n return data;\n }\n })(TextDocument || (exports.TextDocument = TextDocument = {}));\n /**\n * @deprecated Use the text document from the new vscode-languageserver-textdocument package.\n */\n var FullTextDocument = /** @class */ (function () {\n function FullTextDocument(uri, languageId, version, content) {\n this._uri = uri;\n this._languageId = languageId;\n this._version = version;\n this._content = content;\n this._lineOffsets = undefined;\n }\n Object.defineProperty(FullTextDocument.prototype, \"uri\", {\n get: function () {\n return this._uri;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(FullTextDocument.prototype, \"languageId\", {\n get: function () {\n return this._languageId;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(FullTextDocument.prototype, \"version\", {\n get: function () {\n return this._version;\n },\n enumerable: false,\n configurable: true\n });\n FullTextDocument.prototype.getText = function (range) {\n if (range) {\n var start = this.offsetAt(range.start);\n var end = this.offsetAt(range.end);\n return this._content.substring(start, end);\n }\n return this._content;\n };\n FullTextDocument.prototype.update = function (event, version) {\n this._content = event.text;\n this._version = version;\n this._lineOffsets = undefined;\n };\n FullTextDocument.prototype.getLineOffsets = function () {\n if (this._lineOffsets === undefined) {\n var lineOffsets = [];\n var text = this._content;\n var isLineStart = true;\n for (var i = 0; i < text.length; i++) {\n if (isLineStart) {\n lineOffsets.push(i);\n isLineStart = false;\n }\n var ch = text.charAt(i);\n isLineStart = (ch === '\\r' || ch === '\\n');\n if (ch === '\\r' && i + 1 < text.length && text.charAt(i + 1) === '\\n') {\n i++;\n }\n }\n if (isLineStart && text.length > 0) {\n lineOffsets.push(text.length);\n }\n this._lineOffsets = lineOffsets;\n }\n return this._lineOffsets;\n };\n FullTextDocument.prototype.positionAt = function (offset) {\n offset = Math.max(Math.min(offset, this._content.length), 0);\n var lineOffsets = this.getLineOffsets();\n var low = 0, high = lineOffsets.length;\n if (high === 0) {\n return Position.create(0, offset);\n }\n while (low < high) {\n var mid = Math.floor((low + high) / 2);\n if (lineOffsets[mid] > offset) {\n high = mid;\n }\n else {\n low = mid + 1;\n }\n }\n // low is the least x for which the line offset is larger than the current offset\n // or array.length if no line offset is larger than the current offset\n var line = low - 1;\n return Position.create(line, offset - lineOffsets[line]);\n };\n FullTextDocument.prototype.offsetAt = function (position) {\n var lineOffsets = this.getLineOffsets();\n if (position.line >= lineOffsets.length) {\n return this._content.length;\n }\n else if (position.line < 0) {\n return 0;\n }\n var lineOffset = lineOffsets[position.line];\n var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;\n return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);\n };\n Object.defineProperty(FullTextDocument.prototype, \"lineCount\", {\n get: function () {\n return this.getLineOffsets().length;\n },\n enumerable: false,\n configurable: true\n });\n return FullTextDocument;\n }());\n var Is;\n (function (Is) {\n var toString = Object.prototype.toString;\n function defined(value) {\n return typeof value !== 'undefined';\n }\n Is.defined = defined;\n function undefined(value) {\n return typeof value === 'undefined';\n }\n Is.undefined = undefined;\n function boolean(value) {\n return value === true || value === false;\n }\n Is.boolean = boolean;\n function string(value) {\n return toString.call(value) === '[object String]';\n }\n Is.string = string;\n function number(value) {\n return toString.call(value) === '[object Number]';\n }\n Is.number = number;\n function numberRange(value, min, max) {\n return toString.call(value) === '[object Number]' && min <= value && value <= max;\n }\n Is.numberRange = numberRange;\n function integer(value) {\n return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647;\n }\n Is.integer = integer;\n function uinteger(value) {\n return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647;\n }\n Is.uinteger = uinteger;\n function func(value) {\n return toString.call(value) === '[object Function]';\n }\n Is.func = func;\n function objectLiteral(value) {\n // Strictly speaking class instances pass this check as well. Since the LSP\n // doesn't use classes we ignore this for now. If we do we need to add something\n // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`\n return value !== null && typeof value === 'object';\n }\n Is.objectLiteral = objectLiteral;\n function typedArray(value, check) {\n return Array.isArray(value) && value.every(check);\n }\n Is.typedArray = typedArray;\n })(Is || (Is = {}));\n});\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ProtocolNotificationType = exports.ProtocolNotificationType0 = exports.ProtocolRequestType = exports.ProtocolRequestType0 = exports.RegistrationType = exports.MessageDirection = void 0;\nconst vscode_jsonrpc_1 = require(\"vscode-jsonrpc\");\nvar MessageDirection;\n(function (MessageDirection) {\n MessageDirection[\"clientToServer\"] = \"clientToServer\";\n MessageDirection[\"serverToClient\"] = \"serverToClient\";\n MessageDirection[\"both\"] = \"both\";\n})(MessageDirection || (exports.MessageDirection = MessageDirection = {}));\nclass RegistrationType {\n constructor(method) {\n this.method = method;\n }\n}\nexports.RegistrationType = RegistrationType;\nclass ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {\n constructor(method) {\n super(method);\n }\n}\nexports.ProtocolRequestType0 = ProtocolRequestType0;\nclass ProtocolRequestType extends vscode_jsonrpc_1.RequestType {\n constructor(method) {\n super(method, vscode_jsonrpc_1.ParameterStructures.byName);\n }\n}\nexports.ProtocolRequestType = ProtocolRequestType;\nclass ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {\n constructor(method) {\n super(method);\n }\n}\nexports.ProtocolNotificationType0 = ProtocolNotificationType0;\nclass ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {\n constructor(method) {\n super(method, vscode_jsonrpc_1.ParameterStructures.byName);\n }\n}\nexports.ProtocolNotificationType = ProtocolNotificationType;\n", "/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\n'use strict';\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.objectLiteral = exports.typedArray = exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;\nfunction boolean(value) {\n return value === true || value === false;\n}\nexports.boolean = boolean;\nfunction string(value) {\n return typeof value === 'string' || value instanceof String;\n}\nexports.string = string;\nfunction number(value) {\n return typeof value === 'number' || value instanceof Number;\n}\nexports.number = number;\nfunction error(value) {\n return value instanceof Error;\n}\nexports.error = error;\nfunction func(value) {\n return typeof value === 'function';\n}\nexports.func = func;\nfunction array(value) {\n return Array.isArray(value);\n}\nexports.array = array;\nfunction stringArray(value) {\n return array(value) && value.every(elem => string(elem));\n}\nexports.stringArray = stringArray;\nfunction typedArray(value, check) {\n return Array.isArray(value) && value.every(check);\n}\nexports.typedArray = typedArray;\nfunction objectLiteral(value) {\n // Strictly speaking class instances pass this check as well. Since the LSP\n // doesn't use classes we ignore this for now. If we do we need to add something\n // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`\n return value !== null && typeof value === 'object';\n}\nexports.objectLiteral = objectLiteral;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ImplementationRequest = void 0;\nconst messages_1 = require(\"./messages\");\n// @ts-ignore: to avoid inlining LocationLink as dynamic import\nlet __noDynamicImport;\n/**\n * A request to resolve the implementation locations of a symbol at a given text\n * document position. The request's parameter is of type {@link TextDocumentPositionParams}\n * the response is of type {@link Definition} or a Thenable that resolves to such.\n */\nvar ImplementationRequest;\n(function (ImplementationRequest) {\n ImplementationRequest.method = 'textDocument/implementation';\n ImplementationRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);\n})(ImplementationRequest || (exports.ImplementationRequest = ImplementationRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TypeDefinitionRequest = void 0;\nconst messages_1 = require(\"./messages\");\n// @ts-ignore: to avoid inlining LocatioLink as dynamic import\nlet __noDynamicImport;\n/**\n * A request to resolve the type definition locations of a symbol at a given text\n * document position. The request's parameter is of type {@link TextDocumentPositionParams}\n * the response is of type {@link Definition} or a Thenable that resolves to such.\n */\nvar TypeDefinitionRequest;\n(function (TypeDefinitionRequest) {\n TypeDefinitionRequest.method = 'textDocument/typeDefinition';\n TypeDefinitionRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);\n})(TypeDefinitionRequest || (exports.TypeDefinitionRequest = TypeDefinitionRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DidChangeWorkspaceFoldersNotification = exports.WorkspaceFoldersRequest = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.\n */\nvar WorkspaceFoldersRequest;\n(function (WorkspaceFoldersRequest) {\n WorkspaceFoldersRequest.method = 'workspace/workspaceFolders';\n WorkspaceFoldersRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0(WorkspaceFoldersRequest.method);\n})(WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = WorkspaceFoldersRequest = {}));\n/**\n * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace\n * folder configuration changes.\n */\nvar DidChangeWorkspaceFoldersNotification;\n(function (DidChangeWorkspaceFoldersNotification) {\n DidChangeWorkspaceFoldersNotification.method = 'workspace/didChangeWorkspaceFolders';\n DidChangeWorkspaceFoldersNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType(DidChangeWorkspaceFoldersNotification.method);\n})(DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = DidChangeWorkspaceFoldersNotification = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ConfigurationRequest = void 0;\nconst messages_1 = require(\"./messages\");\n//---- Get Configuration request ----\n/**\n * The 'workspace/configuration' request is sent from the server to the client to fetch a certain\n * configuration setting.\n *\n * This pull model replaces the old push model were the client signaled configuration change via an\n * event. If the server still needs to react to configuration changes (since the server caches the\n * result of `workspace/configuration` requests) the server should register for an empty configuration\n * change event and empty the cache if such an event is received.\n */\nvar ConfigurationRequest;\n(function (ConfigurationRequest) {\n ConfigurationRequest.method = 'workspace/configuration';\n ConfigurationRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n ConfigurationRequest.type = new messages_1.ProtocolRequestType(ConfigurationRequest.method);\n})(ConfigurationRequest || (exports.ConfigurationRequest = ConfigurationRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ColorPresentationRequest = exports.DocumentColorRequest = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * A request to list all color symbols found in a given text document. The request's\n * parameter is of type {@link DocumentColorParams} the\n * response is of type {@link ColorInformation ColorInformation[]} or a Thenable\n * that resolves to such.\n */\nvar DocumentColorRequest;\n(function (DocumentColorRequest) {\n DocumentColorRequest.method = 'textDocument/documentColor';\n DocumentColorRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);\n})(DocumentColorRequest || (exports.DocumentColorRequest = DocumentColorRequest = {}));\n/**\n * A request to list all presentation for a color. The request's\n * parameter is of type {@link ColorPresentationParams} the\n * response is of type {@link ColorInformation ColorInformation[]} or a Thenable\n * that resolves to such.\n */\nvar ColorPresentationRequest;\n(function (ColorPresentationRequest) {\n ColorPresentationRequest.method = 'textDocument/colorPresentation';\n ColorPresentationRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n ColorPresentationRequest.type = new messages_1.ProtocolRequestType(ColorPresentationRequest.method);\n})(ColorPresentationRequest || (exports.ColorPresentationRequest = ColorPresentationRequest = {}));\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FoldingRangeRefreshRequest = exports.FoldingRangeRequest = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * A request to provide folding ranges in a document. The request's\n * parameter is of type {@link FoldingRangeParams}, the\n * response is of type {@link FoldingRangeList} or a Thenable\n * that resolves to such.\n */\nvar FoldingRangeRequest;\n(function (FoldingRangeRequest) {\n FoldingRangeRequest.method = 'textDocument/foldingRange';\n FoldingRangeRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);\n})(FoldingRangeRequest || (exports.FoldingRangeRequest = FoldingRangeRequest = {}));\n/**\n * @since 3.18.0\n * @proposed\n */\nvar FoldingRangeRefreshRequest;\n(function (FoldingRangeRefreshRequest) {\n FoldingRangeRefreshRequest.method = `workspace/foldingRange/refresh`;\n FoldingRangeRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n FoldingRangeRefreshRequest.type = new messages_1.ProtocolRequestType0(FoldingRangeRefreshRequest.method);\n})(FoldingRangeRefreshRequest || (exports.FoldingRangeRefreshRequest = FoldingRangeRefreshRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DeclarationRequest = void 0;\nconst messages_1 = require(\"./messages\");\n// @ts-ignore: to avoid inlining LocationLink as dynamic import\nlet __noDynamicImport;\n/**\n * A request to resolve the type definition locations of a symbol at a given text\n * document position. The request's parameter is of type {@link TextDocumentPositionParams}\n * the response is of type {@link Declaration} or a typed array of {@link DeclarationLink}\n * or a Thenable that resolves to such.\n */\nvar DeclarationRequest;\n(function (DeclarationRequest) {\n DeclarationRequest.method = 'textDocument/declaration';\n DeclarationRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);\n})(DeclarationRequest || (exports.DeclarationRequest = DeclarationRequest = {}));\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SelectionRangeRequest = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * A request to provide selection ranges in a document. The request's\n * parameter is of type {@link SelectionRangeParams}, the\n * response is of type {@link SelectionRange SelectionRange[]} or a Thenable\n * that resolves to such.\n */\nvar SelectionRangeRequest;\n(function (SelectionRangeRequest) {\n SelectionRangeRequest.method = 'textDocument/selectionRange';\n SelectionRangeRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);\n})(SelectionRangeRequest || (exports.SelectionRangeRequest = SelectionRangeRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WorkDoneProgressCancelNotification = exports.WorkDoneProgressCreateRequest = exports.WorkDoneProgress = void 0;\nconst vscode_jsonrpc_1 = require(\"vscode-jsonrpc\");\nconst messages_1 = require(\"./messages\");\nvar WorkDoneProgress;\n(function (WorkDoneProgress) {\n WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();\n function is(value) {\n return value === WorkDoneProgress.type;\n }\n WorkDoneProgress.is = is;\n})(WorkDoneProgress || (exports.WorkDoneProgress = WorkDoneProgress = {}));\n/**\n * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress\n * reporting from the server.\n */\nvar WorkDoneProgressCreateRequest;\n(function (WorkDoneProgressCreateRequest) {\n WorkDoneProgressCreateRequest.method = 'window/workDoneProgress/create';\n WorkDoneProgressCreateRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType(WorkDoneProgressCreateRequest.method);\n})(WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = WorkDoneProgressCreateRequest = {}));\n/**\n * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress\n * initiated on the server side.\n */\nvar WorkDoneProgressCancelNotification;\n(function (WorkDoneProgressCancelNotification) {\n WorkDoneProgressCancelNotification.method = 'window/workDoneProgress/cancel';\n WorkDoneProgressCancelNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType(WorkDoneProgressCancelNotification.method);\n})(WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = WorkDoneProgressCancelNotification = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) TypeFox, Microsoft and others. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CallHierarchyOutgoingCallsRequest = exports.CallHierarchyIncomingCallsRequest = exports.CallHierarchyPrepareRequest = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * A request to result a `CallHierarchyItem` in a document at a given position.\n * Can be used as an input to an incoming or outgoing call hierarchy.\n *\n * @since 3.16.0\n */\nvar CallHierarchyPrepareRequest;\n(function (CallHierarchyPrepareRequest) {\n CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';\n CallHierarchyPrepareRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);\n})(CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = CallHierarchyPrepareRequest = {}));\n/**\n * A request to resolve the incoming calls for a given `CallHierarchyItem`.\n *\n * @since 3.16.0\n */\nvar CallHierarchyIncomingCallsRequest;\n(function (CallHierarchyIncomingCallsRequest) {\n CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';\n CallHierarchyIncomingCallsRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);\n})(CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = CallHierarchyIncomingCallsRequest = {}));\n/**\n * A request to resolve the outgoing calls for a given `CallHierarchyItem`.\n *\n * @since 3.16.0\n */\nvar CallHierarchyOutgoingCallsRequest;\n(function (CallHierarchyOutgoingCallsRequest) {\n CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';\n CallHierarchyOutgoingCallsRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);\n})(CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = CallHierarchyOutgoingCallsRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SemanticTokensRefreshRequest = exports.SemanticTokensRangeRequest = exports.SemanticTokensDeltaRequest = exports.SemanticTokensRequest = exports.SemanticTokensRegistrationType = exports.TokenFormat = void 0;\nconst messages_1 = require(\"./messages\");\n//------- 'textDocument/semanticTokens' -----\nvar TokenFormat;\n(function (TokenFormat) {\n TokenFormat.Relative = 'relative';\n})(TokenFormat || (exports.TokenFormat = TokenFormat = {}));\nvar SemanticTokensRegistrationType;\n(function (SemanticTokensRegistrationType) {\n SemanticTokensRegistrationType.method = 'textDocument/semanticTokens';\n SemanticTokensRegistrationType.type = new messages_1.RegistrationType(SemanticTokensRegistrationType.method);\n})(SemanticTokensRegistrationType || (exports.SemanticTokensRegistrationType = SemanticTokensRegistrationType = {}));\n/**\n * @since 3.16.0\n */\nvar SemanticTokensRequest;\n(function (SemanticTokensRequest) {\n SemanticTokensRequest.method = 'textDocument/semanticTokens/full';\n SemanticTokensRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);\n SemanticTokensRequest.registrationMethod = SemanticTokensRegistrationType.method;\n})(SemanticTokensRequest || (exports.SemanticTokensRequest = SemanticTokensRequest = {}));\n/**\n * @since 3.16.0\n */\nvar SemanticTokensDeltaRequest;\n(function (SemanticTokensDeltaRequest) {\n SemanticTokensDeltaRequest.method = 'textDocument/semanticTokens/full/delta';\n SemanticTokensDeltaRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n SemanticTokensDeltaRequest.type = new messages_1.ProtocolRequestType(SemanticTokensDeltaRequest.method);\n SemanticTokensDeltaRequest.registrationMethod = SemanticTokensRegistrationType.method;\n})(SemanticTokensDeltaRequest || (exports.SemanticTokensDeltaRequest = SemanticTokensDeltaRequest = {}));\n/**\n * @since 3.16.0\n */\nvar SemanticTokensRangeRequest;\n(function (SemanticTokensRangeRequest) {\n SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';\n SemanticTokensRangeRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);\n SemanticTokensRangeRequest.registrationMethod = SemanticTokensRegistrationType.method;\n})(SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = SemanticTokensRangeRequest = {}));\n/**\n * @since 3.16.0\n */\nvar SemanticTokensRefreshRequest;\n(function (SemanticTokensRefreshRequest) {\n SemanticTokensRefreshRequest.method = `workspace/semanticTokens/refresh`;\n SemanticTokensRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n SemanticTokensRefreshRequest.type = new messages_1.ProtocolRequestType0(SemanticTokensRefreshRequest.method);\n})(SemanticTokensRefreshRequest || (exports.SemanticTokensRefreshRequest = SemanticTokensRefreshRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ShowDocumentRequest = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * A request to show a document. This request might open an\n * external program depending on the value of the URI to open.\n * For example a request to open `https://code.visualstudio.com/`\n * will very likely open the URI in a WEB browser.\n *\n * @since 3.16.0\n*/\nvar ShowDocumentRequest;\n(function (ShowDocumentRequest) {\n ShowDocumentRequest.method = 'window/showDocument';\n ShowDocumentRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n ShowDocumentRequest.type = new messages_1.ProtocolRequestType(ShowDocumentRequest.method);\n})(ShowDocumentRequest || (exports.ShowDocumentRequest = ShowDocumentRequest = {}));\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LinkedEditingRangeRequest = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * A request to provide ranges that can be edited together.\n *\n * @since 3.16.0\n */\nvar LinkedEditingRangeRequest;\n(function (LinkedEditingRangeRequest) {\n LinkedEditingRangeRequest.method = 'textDocument/linkedEditingRange';\n LinkedEditingRangeRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n LinkedEditingRangeRequest.type = new messages_1.ProtocolRequestType(LinkedEditingRangeRequest.method);\n})(LinkedEditingRangeRequest || (exports.LinkedEditingRangeRequest = LinkedEditingRangeRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WillDeleteFilesRequest = exports.DidDeleteFilesNotification = exports.DidRenameFilesNotification = exports.WillRenameFilesRequest = exports.DidCreateFilesNotification = exports.WillCreateFilesRequest = exports.FileOperationPatternKind = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * A pattern kind describing if a glob pattern matches a file a folder or\n * both.\n *\n * @since 3.16.0\n */\nvar FileOperationPatternKind;\n(function (FileOperationPatternKind) {\n /**\n * The pattern matches a file only.\n */\n FileOperationPatternKind.file = 'file';\n /**\n * The pattern matches a folder only.\n */\n FileOperationPatternKind.folder = 'folder';\n})(FileOperationPatternKind || (exports.FileOperationPatternKind = FileOperationPatternKind = {}));\n/**\n * The will create files request is sent from the client to the server before files are actually\n * created as long as the creation is triggered from within the client.\n *\n * The request can return a `WorkspaceEdit` which will be applied to workspace before the\n * files are created. Hence the `WorkspaceEdit` can not manipulate the content of the file\n * to be created.\n *\n * @since 3.16.0\n */\nvar WillCreateFilesRequest;\n(function (WillCreateFilesRequest) {\n WillCreateFilesRequest.method = 'workspace/willCreateFiles';\n WillCreateFilesRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n WillCreateFilesRequest.type = new messages_1.ProtocolRequestType(WillCreateFilesRequest.method);\n})(WillCreateFilesRequest || (exports.WillCreateFilesRequest = WillCreateFilesRequest = {}));\n/**\n * The did create files notification is sent from the client to the server when\n * files were created from within the client.\n *\n * @since 3.16.0\n */\nvar DidCreateFilesNotification;\n(function (DidCreateFilesNotification) {\n DidCreateFilesNotification.method = 'workspace/didCreateFiles';\n DidCreateFilesNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidCreateFilesNotification.type = new messages_1.ProtocolNotificationType(DidCreateFilesNotification.method);\n})(DidCreateFilesNotification || (exports.DidCreateFilesNotification = DidCreateFilesNotification = {}));\n/**\n * The will rename files request is sent from the client to the server before files are actually\n * renamed as long as the rename is triggered from within the client.\n *\n * @since 3.16.0\n */\nvar WillRenameFilesRequest;\n(function (WillRenameFilesRequest) {\n WillRenameFilesRequest.method = 'workspace/willRenameFiles';\n WillRenameFilesRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n WillRenameFilesRequest.type = new messages_1.ProtocolRequestType(WillRenameFilesRequest.method);\n})(WillRenameFilesRequest || (exports.WillRenameFilesRequest = WillRenameFilesRequest = {}));\n/**\n * The did rename files notification is sent from the client to the server when\n * files were renamed from within the client.\n *\n * @since 3.16.0\n */\nvar DidRenameFilesNotification;\n(function (DidRenameFilesNotification) {\n DidRenameFilesNotification.method = 'workspace/didRenameFiles';\n DidRenameFilesNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidRenameFilesNotification.type = new messages_1.ProtocolNotificationType(DidRenameFilesNotification.method);\n})(DidRenameFilesNotification || (exports.DidRenameFilesNotification = DidRenameFilesNotification = {}));\n/**\n * The will delete files request is sent from the client to the server before files are actually\n * deleted as long as the deletion is triggered from within the client.\n *\n * @since 3.16.0\n */\nvar DidDeleteFilesNotification;\n(function (DidDeleteFilesNotification) {\n DidDeleteFilesNotification.method = 'workspace/didDeleteFiles';\n DidDeleteFilesNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidDeleteFilesNotification.type = new messages_1.ProtocolNotificationType(DidDeleteFilesNotification.method);\n})(DidDeleteFilesNotification || (exports.DidDeleteFilesNotification = DidDeleteFilesNotification = {}));\n/**\n * The did delete files notification is sent from the client to the server when\n * files were deleted from within the client.\n *\n * @since 3.16.0\n */\nvar WillDeleteFilesRequest;\n(function (WillDeleteFilesRequest) {\n WillDeleteFilesRequest.method = 'workspace/willDeleteFiles';\n WillDeleteFilesRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n WillDeleteFilesRequest.type = new messages_1.ProtocolRequestType(WillDeleteFilesRequest.method);\n})(WillDeleteFilesRequest || (exports.WillDeleteFilesRequest = WillDeleteFilesRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MonikerRequest = exports.MonikerKind = exports.UniquenessLevel = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * Moniker uniqueness level to define scope of the moniker.\n *\n * @since 3.16.0\n */\nvar UniquenessLevel;\n(function (UniquenessLevel) {\n /**\n * The moniker is only unique inside a document\n */\n UniquenessLevel.document = 'document';\n /**\n * The moniker is unique inside a project for which a dump got created\n */\n UniquenessLevel.project = 'project';\n /**\n * The moniker is unique inside the group to which a project belongs\n */\n UniquenessLevel.group = 'group';\n /**\n * The moniker is unique inside the moniker scheme.\n */\n UniquenessLevel.scheme = 'scheme';\n /**\n * The moniker is globally unique\n */\n UniquenessLevel.global = 'global';\n})(UniquenessLevel || (exports.UniquenessLevel = UniquenessLevel = {}));\n/**\n * The moniker kind.\n *\n * @since 3.16.0\n */\nvar MonikerKind;\n(function (MonikerKind) {\n /**\n * The moniker represent a symbol that is imported into a project\n */\n MonikerKind.$import = 'import';\n /**\n * The moniker represents a symbol that is exported from a project\n */\n MonikerKind.$export = 'export';\n /**\n * The moniker represents a symbol that is local to a project (e.g. a local\n * variable of a function, a class not visible outside the project, ...)\n */\n MonikerKind.local = 'local';\n})(MonikerKind || (exports.MonikerKind = MonikerKind = {}));\n/**\n * A request to get the moniker of a symbol at a given text document position.\n * The request parameter is of type {@link TextDocumentPositionParams}.\n * The response is of type {@link Moniker Moniker[]} or `null`.\n */\nvar MonikerRequest;\n(function (MonikerRequest) {\n MonikerRequest.method = 'textDocument/moniker';\n MonikerRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n MonikerRequest.type = new messages_1.ProtocolRequestType(MonikerRequest.method);\n})(MonikerRequest || (exports.MonikerRequest = MonikerRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) TypeFox, Microsoft and others. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TypeHierarchySubtypesRequest = exports.TypeHierarchySupertypesRequest = exports.TypeHierarchyPrepareRequest = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * A request to result a `TypeHierarchyItem` in a document at a given position.\n * Can be used as an input to a subtypes or supertypes type hierarchy.\n *\n * @since 3.17.0\n */\nvar TypeHierarchyPrepareRequest;\n(function (TypeHierarchyPrepareRequest) {\n TypeHierarchyPrepareRequest.method = 'textDocument/prepareTypeHierarchy';\n TypeHierarchyPrepareRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n TypeHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(TypeHierarchyPrepareRequest.method);\n})(TypeHierarchyPrepareRequest || (exports.TypeHierarchyPrepareRequest = TypeHierarchyPrepareRequest = {}));\n/**\n * A request to resolve the supertypes for a given `TypeHierarchyItem`.\n *\n * @since 3.17.0\n */\nvar TypeHierarchySupertypesRequest;\n(function (TypeHierarchySupertypesRequest) {\n TypeHierarchySupertypesRequest.method = 'typeHierarchy/supertypes';\n TypeHierarchySupertypesRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n TypeHierarchySupertypesRequest.type = new messages_1.ProtocolRequestType(TypeHierarchySupertypesRequest.method);\n})(TypeHierarchySupertypesRequest || (exports.TypeHierarchySupertypesRequest = TypeHierarchySupertypesRequest = {}));\n/**\n * A request to resolve the subtypes for a given `TypeHierarchyItem`.\n *\n * @since 3.17.0\n */\nvar TypeHierarchySubtypesRequest;\n(function (TypeHierarchySubtypesRequest) {\n TypeHierarchySubtypesRequest.method = 'typeHierarchy/subtypes';\n TypeHierarchySubtypesRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n TypeHierarchySubtypesRequest.type = new messages_1.ProtocolRequestType(TypeHierarchySubtypesRequest.method);\n})(TypeHierarchySubtypesRequest || (exports.TypeHierarchySubtypesRequest = TypeHierarchySubtypesRequest = {}));\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InlineValueRefreshRequest = exports.InlineValueRequest = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * A request to provide inline values in a document. The request's parameter is of\n * type {@link InlineValueParams}, the response is of type\n * {@link InlineValue InlineValue[]} or a Thenable that resolves to such.\n *\n * @since 3.17.0\n */\nvar InlineValueRequest;\n(function (InlineValueRequest) {\n InlineValueRequest.method = 'textDocument/inlineValue';\n InlineValueRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n InlineValueRequest.type = new messages_1.ProtocolRequestType(InlineValueRequest.method);\n})(InlineValueRequest || (exports.InlineValueRequest = InlineValueRequest = {}));\n/**\n * @since 3.17.0\n */\nvar InlineValueRefreshRequest;\n(function (InlineValueRefreshRequest) {\n InlineValueRefreshRequest.method = `workspace/inlineValue/refresh`;\n InlineValueRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n InlineValueRefreshRequest.type = new messages_1.ProtocolRequestType0(InlineValueRefreshRequest.method);\n})(InlineValueRefreshRequest || (exports.InlineValueRefreshRequest = InlineValueRefreshRequest = {}));\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InlayHintRefreshRequest = exports.InlayHintResolveRequest = exports.InlayHintRequest = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * A request to provide inlay hints in a document. The request's parameter is of\n * type {@link InlayHintsParams}, the response is of type\n * {@link InlayHint InlayHint[]} or a Thenable that resolves to such.\n *\n * @since 3.17.0\n */\nvar InlayHintRequest;\n(function (InlayHintRequest) {\n InlayHintRequest.method = 'textDocument/inlayHint';\n InlayHintRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n InlayHintRequest.type = new messages_1.ProtocolRequestType(InlayHintRequest.method);\n})(InlayHintRequest || (exports.InlayHintRequest = InlayHintRequest = {}));\n/**\n * A request to resolve additional properties for an inlay hint.\n * The request's parameter is of type {@link InlayHint}, the response is\n * of type {@link InlayHint} or a Thenable that resolves to such.\n *\n * @since 3.17.0\n */\nvar InlayHintResolveRequest;\n(function (InlayHintResolveRequest) {\n InlayHintResolveRequest.method = 'inlayHint/resolve';\n InlayHintResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n InlayHintResolveRequest.type = new messages_1.ProtocolRequestType(InlayHintResolveRequest.method);\n})(InlayHintResolveRequest || (exports.InlayHintResolveRequest = InlayHintResolveRequest = {}));\n/**\n * @since 3.17.0\n */\nvar InlayHintRefreshRequest;\n(function (InlayHintRefreshRequest) {\n InlayHintRefreshRequest.method = `workspace/inlayHint/refresh`;\n InlayHintRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n InlayHintRefreshRequest.type = new messages_1.ProtocolRequestType0(InlayHintRefreshRequest.method);\n})(InlayHintRefreshRequest || (exports.InlayHintRefreshRequest = InlayHintRefreshRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DiagnosticRefreshRequest = exports.WorkspaceDiagnosticRequest = exports.DocumentDiagnosticRequest = exports.DocumentDiagnosticReportKind = exports.DiagnosticServerCancellationData = void 0;\nconst vscode_jsonrpc_1 = require(\"vscode-jsonrpc\");\nconst Is = require(\"./utils/is\");\nconst messages_1 = require(\"./messages\");\n/**\n * @since 3.17.0\n */\nvar DiagnosticServerCancellationData;\n(function (DiagnosticServerCancellationData) {\n function is(value) {\n const candidate = value;\n return candidate && Is.boolean(candidate.retriggerRequest);\n }\n DiagnosticServerCancellationData.is = is;\n})(DiagnosticServerCancellationData || (exports.DiagnosticServerCancellationData = DiagnosticServerCancellationData = {}));\n/**\n * The document diagnostic report kinds.\n *\n * @since 3.17.0\n */\nvar DocumentDiagnosticReportKind;\n(function (DocumentDiagnosticReportKind) {\n /**\n * A diagnostic report with a full\n * set of problems.\n */\n DocumentDiagnosticReportKind.Full = 'full';\n /**\n * A report indicating that the last\n * returned report is still accurate.\n */\n DocumentDiagnosticReportKind.Unchanged = 'unchanged';\n})(DocumentDiagnosticReportKind || (exports.DocumentDiagnosticReportKind = DocumentDiagnosticReportKind = {}));\n/**\n * The document diagnostic request definition.\n *\n * @since 3.17.0\n */\nvar DocumentDiagnosticRequest;\n(function (DocumentDiagnosticRequest) {\n DocumentDiagnosticRequest.method = 'textDocument/diagnostic';\n DocumentDiagnosticRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DocumentDiagnosticRequest.type = new messages_1.ProtocolRequestType(DocumentDiagnosticRequest.method);\n DocumentDiagnosticRequest.partialResult = new vscode_jsonrpc_1.ProgressType();\n})(DocumentDiagnosticRequest || (exports.DocumentDiagnosticRequest = DocumentDiagnosticRequest = {}));\n/**\n * The workspace diagnostic request definition.\n *\n * @since 3.17.0\n */\nvar WorkspaceDiagnosticRequest;\n(function (WorkspaceDiagnosticRequest) {\n WorkspaceDiagnosticRequest.method = 'workspace/diagnostic';\n WorkspaceDiagnosticRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n WorkspaceDiagnosticRequest.type = new messages_1.ProtocolRequestType(WorkspaceDiagnosticRequest.method);\n WorkspaceDiagnosticRequest.partialResult = new vscode_jsonrpc_1.ProgressType();\n})(WorkspaceDiagnosticRequest || (exports.WorkspaceDiagnosticRequest = WorkspaceDiagnosticRequest = {}));\n/**\n * The diagnostic refresh request definition.\n *\n * @since 3.17.0\n */\nvar DiagnosticRefreshRequest;\n(function (DiagnosticRefreshRequest) {\n DiagnosticRefreshRequest.method = `workspace/diagnostic/refresh`;\n DiagnosticRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n DiagnosticRefreshRequest.type = new messages_1.ProtocolRequestType0(DiagnosticRefreshRequest.method);\n})(DiagnosticRefreshRequest || (exports.DiagnosticRefreshRequest = DiagnosticRefreshRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DidCloseNotebookDocumentNotification = exports.DidSaveNotebookDocumentNotification = exports.DidChangeNotebookDocumentNotification = exports.NotebookCellArrayChange = exports.DidOpenNotebookDocumentNotification = exports.NotebookDocumentSyncRegistrationType = exports.NotebookDocument = exports.NotebookCell = exports.ExecutionSummary = exports.NotebookCellKind = void 0;\nconst vscode_languageserver_types_1 = require(\"vscode-languageserver-types\");\nconst Is = require(\"./utils/is\");\nconst messages_1 = require(\"./messages\");\n/**\n * A notebook cell kind.\n *\n * @since 3.17.0\n */\nvar NotebookCellKind;\n(function (NotebookCellKind) {\n /**\n * A markup-cell is formatted source that is used for display.\n */\n NotebookCellKind.Markup = 1;\n /**\n * A code-cell is source code.\n */\n NotebookCellKind.Code = 2;\n function is(value) {\n return value === 1 || value === 2;\n }\n NotebookCellKind.is = is;\n})(NotebookCellKind || (exports.NotebookCellKind = NotebookCellKind = {}));\nvar ExecutionSummary;\n(function (ExecutionSummary) {\n function create(executionOrder, success) {\n const result = { executionOrder };\n if (success === true || success === false) {\n result.success = success;\n }\n return result;\n }\n ExecutionSummary.create = create;\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.executionOrder) && (candidate.success === undefined || Is.boolean(candidate.success));\n }\n ExecutionSummary.is = is;\n function equals(one, other) {\n if (one === other) {\n return true;\n }\n if (one === null || one === undefined || other === null || other === undefined) {\n return false;\n }\n return one.executionOrder === other.executionOrder && one.success === other.success;\n }\n ExecutionSummary.equals = equals;\n})(ExecutionSummary || (exports.ExecutionSummary = ExecutionSummary = {}));\nvar NotebookCell;\n(function (NotebookCell) {\n function create(kind, document) {\n return { kind, document };\n }\n NotebookCell.create = create;\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && NotebookCellKind.is(candidate.kind) && vscode_languageserver_types_1.DocumentUri.is(candidate.document) &&\n (candidate.metadata === undefined || Is.objectLiteral(candidate.metadata));\n }\n NotebookCell.is = is;\n function diff(one, two) {\n const result = new Set();\n if (one.document !== two.document) {\n result.add('document');\n }\n if (one.kind !== two.kind) {\n result.add('kind');\n }\n if (one.executionSummary !== two.executionSummary) {\n result.add('executionSummary');\n }\n if ((one.metadata !== undefined || two.metadata !== undefined) && !equalsMetadata(one.metadata, two.metadata)) {\n result.add('metadata');\n }\n if ((one.executionSummary !== undefined || two.executionSummary !== undefined) && !ExecutionSummary.equals(one.executionSummary, two.executionSummary)) {\n result.add('executionSummary');\n }\n return result;\n }\n NotebookCell.diff = diff;\n function equalsMetadata(one, other) {\n if (one === other) {\n return true;\n }\n if (one === null || one === undefined || other === null || other === undefined) {\n return false;\n }\n if (typeof one !== typeof other) {\n return false;\n }\n if (typeof one !== 'object') {\n return false;\n }\n const oneArray = Array.isArray(one);\n const otherArray = Array.isArray(other);\n if (oneArray !== otherArray) {\n return false;\n }\n if (oneArray && otherArray) {\n if (one.length !== other.length) {\n return false;\n }\n for (let i = 0; i < one.length; i++) {\n if (!equalsMetadata(one[i], other[i])) {\n return false;\n }\n }\n }\n if (Is.objectLiteral(one) && Is.objectLiteral(other)) {\n const oneKeys = Object.keys(one);\n const otherKeys = Object.keys(other);\n if (oneKeys.length !== otherKeys.length) {\n return false;\n }\n oneKeys.sort();\n otherKeys.sort();\n if (!equalsMetadata(oneKeys, otherKeys)) {\n return false;\n }\n for (let i = 0; i < oneKeys.length; i++) {\n const prop = oneKeys[i];\n if (!equalsMetadata(one[prop], other[prop])) {\n return false;\n }\n }\n }\n return true;\n }\n})(NotebookCell || (exports.NotebookCell = NotebookCell = {}));\nvar NotebookDocument;\n(function (NotebookDocument) {\n function create(uri, notebookType, version, cells) {\n return { uri, notebookType, version, cells };\n }\n NotebookDocument.create = create;\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && Is.string(candidate.uri) && vscode_languageserver_types_1.integer.is(candidate.version) && Is.typedArray(candidate.cells, NotebookCell.is);\n }\n NotebookDocument.is = is;\n})(NotebookDocument || (exports.NotebookDocument = NotebookDocument = {}));\nvar NotebookDocumentSyncRegistrationType;\n(function (NotebookDocumentSyncRegistrationType) {\n NotebookDocumentSyncRegistrationType.method = 'notebookDocument/sync';\n NotebookDocumentSyncRegistrationType.messageDirection = messages_1.MessageDirection.clientToServer;\n NotebookDocumentSyncRegistrationType.type = new messages_1.RegistrationType(NotebookDocumentSyncRegistrationType.method);\n})(NotebookDocumentSyncRegistrationType || (exports.NotebookDocumentSyncRegistrationType = NotebookDocumentSyncRegistrationType = {}));\n/**\n * A notification sent when a notebook opens.\n *\n * @since 3.17.0\n */\nvar DidOpenNotebookDocumentNotification;\n(function (DidOpenNotebookDocumentNotification) {\n DidOpenNotebookDocumentNotification.method = 'notebookDocument/didOpen';\n DidOpenNotebookDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidOpenNotebookDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenNotebookDocumentNotification.method);\n DidOpenNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;\n})(DidOpenNotebookDocumentNotification || (exports.DidOpenNotebookDocumentNotification = DidOpenNotebookDocumentNotification = {}));\nvar NotebookCellArrayChange;\n(function (NotebookCellArrayChange) {\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.start) && vscode_languageserver_types_1.uinteger.is(candidate.deleteCount) && (candidate.cells === undefined || Is.typedArray(candidate.cells, NotebookCell.is));\n }\n NotebookCellArrayChange.is = is;\n function create(start, deleteCount, cells) {\n const result = { start, deleteCount };\n if (cells !== undefined) {\n result.cells = cells;\n }\n return result;\n }\n NotebookCellArrayChange.create = create;\n})(NotebookCellArrayChange || (exports.NotebookCellArrayChange = NotebookCellArrayChange = {}));\nvar DidChangeNotebookDocumentNotification;\n(function (DidChangeNotebookDocumentNotification) {\n DidChangeNotebookDocumentNotification.method = 'notebookDocument/didChange';\n DidChangeNotebookDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidChangeNotebookDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeNotebookDocumentNotification.method);\n DidChangeNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;\n})(DidChangeNotebookDocumentNotification || (exports.DidChangeNotebookDocumentNotification = DidChangeNotebookDocumentNotification = {}));\n/**\n * A notification sent when a notebook document is saved.\n *\n * @since 3.17.0\n */\nvar DidSaveNotebookDocumentNotification;\n(function (DidSaveNotebookDocumentNotification) {\n DidSaveNotebookDocumentNotification.method = 'notebookDocument/didSave';\n DidSaveNotebookDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidSaveNotebookDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveNotebookDocumentNotification.method);\n DidSaveNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;\n})(DidSaveNotebookDocumentNotification || (exports.DidSaveNotebookDocumentNotification = DidSaveNotebookDocumentNotification = {}));\n/**\n * A notification sent when a notebook closes.\n *\n * @since 3.17.0\n */\nvar DidCloseNotebookDocumentNotification;\n(function (DidCloseNotebookDocumentNotification) {\n DidCloseNotebookDocumentNotification.method = 'notebookDocument/didClose';\n DidCloseNotebookDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidCloseNotebookDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseNotebookDocumentNotification.method);\n DidCloseNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;\n})(DidCloseNotebookDocumentNotification || (exports.DidCloseNotebookDocumentNotification = DidCloseNotebookDocumentNotification = {}));\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InlineCompletionRequest = void 0;\nconst messages_1 = require(\"./messages\");\n/**\n * A request to provide inline completions in a document. The request's parameter is of\n * type {@link InlineCompletionParams}, the response is of type\n * {@link InlineCompletion InlineCompletion[]} or a Thenable that resolves to such.\n *\n * @since 3.18.0\n * @proposed\n */\nvar InlineCompletionRequest;\n(function (InlineCompletionRequest) {\n InlineCompletionRequest.method = 'textDocument/inlineCompletion';\n InlineCompletionRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n InlineCompletionRequest.type = new messages_1.ProtocolRequestType(InlineCompletionRequest.method);\n})(InlineCompletionRequest || (exports.InlineCompletionRequest = InlineCompletionRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WorkspaceSymbolRequest = exports.CodeActionResolveRequest = exports.CodeActionRequest = exports.DocumentSymbolRequest = exports.DocumentHighlightRequest = exports.ReferencesRequest = exports.DefinitionRequest = exports.SignatureHelpRequest = exports.SignatureHelpTriggerKind = exports.HoverRequest = exports.CompletionResolveRequest = exports.CompletionRequest = exports.CompletionTriggerKind = exports.PublishDiagnosticsNotification = exports.WatchKind = exports.RelativePattern = exports.FileChangeType = exports.DidChangeWatchedFilesNotification = exports.WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentNotification = exports.TextDocumentSaveReason = exports.DidSaveTextDocumentNotification = exports.DidCloseTextDocumentNotification = exports.DidChangeTextDocumentNotification = exports.TextDocumentContentChangeEvent = exports.DidOpenTextDocumentNotification = exports.TextDocumentSyncKind = exports.TelemetryEventNotification = exports.LogMessageNotification = exports.ShowMessageRequest = exports.ShowMessageNotification = exports.MessageType = exports.DidChangeConfigurationNotification = exports.ExitNotification = exports.ShutdownRequest = exports.InitializedNotification = exports.InitializeErrorCodes = exports.InitializeRequest = exports.WorkDoneProgressOptions = exports.TextDocumentRegistrationOptions = exports.StaticRegistrationOptions = exports.PositionEncodingKind = exports.FailureHandlingKind = exports.ResourceOperationKind = exports.UnregistrationRequest = exports.RegistrationRequest = exports.DocumentSelector = exports.NotebookCellTextDocumentFilter = exports.NotebookDocumentFilter = exports.TextDocumentFilter = void 0;\nexports.MonikerRequest = exports.MonikerKind = exports.UniquenessLevel = exports.WillDeleteFilesRequest = exports.DidDeleteFilesNotification = exports.WillRenameFilesRequest = exports.DidRenameFilesNotification = exports.WillCreateFilesRequest = exports.DidCreateFilesNotification = exports.FileOperationPatternKind = exports.LinkedEditingRangeRequest = exports.ShowDocumentRequest = exports.SemanticTokensRegistrationType = exports.SemanticTokensRefreshRequest = exports.SemanticTokensRangeRequest = exports.SemanticTokensDeltaRequest = exports.SemanticTokensRequest = exports.TokenFormat = exports.CallHierarchyPrepareRequest = exports.CallHierarchyOutgoingCallsRequest = exports.CallHierarchyIncomingCallsRequest = exports.WorkDoneProgressCancelNotification = exports.WorkDoneProgressCreateRequest = exports.WorkDoneProgress = exports.SelectionRangeRequest = exports.DeclarationRequest = exports.FoldingRangeRefreshRequest = exports.FoldingRangeRequest = exports.ColorPresentationRequest = exports.DocumentColorRequest = exports.ConfigurationRequest = exports.DidChangeWorkspaceFoldersNotification = exports.WorkspaceFoldersRequest = exports.TypeDefinitionRequest = exports.ImplementationRequest = exports.ApplyWorkspaceEditRequest = exports.ExecuteCommandRequest = exports.PrepareRenameRequest = exports.RenameRequest = exports.PrepareSupportDefaultBehavior = exports.DocumentOnTypeFormattingRequest = exports.DocumentRangesFormattingRequest = exports.DocumentRangeFormattingRequest = exports.DocumentFormattingRequest = exports.DocumentLinkResolveRequest = exports.DocumentLinkRequest = exports.CodeLensRefreshRequest = exports.CodeLensResolveRequest = exports.CodeLensRequest = exports.WorkspaceSymbolResolveRequest = void 0;\nexports.InlineCompletionRequest = exports.DidCloseNotebookDocumentNotification = exports.DidSaveNotebookDocumentNotification = exports.DidChangeNotebookDocumentNotification = exports.NotebookCellArrayChange = exports.DidOpenNotebookDocumentNotification = exports.NotebookDocumentSyncRegistrationType = exports.NotebookDocument = exports.NotebookCell = exports.ExecutionSummary = exports.NotebookCellKind = exports.DiagnosticRefreshRequest = exports.WorkspaceDiagnosticRequest = exports.DocumentDiagnosticRequest = exports.DocumentDiagnosticReportKind = exports.DiagnosticServerCancellationData = exports.InlayHintRefreshRequest = exports.InlayHintResolveRequest = exports.InlayHintRequest = exports.InlineValueRefreshRequest = exports.InlineValueRequest = exports.TypeHierarchySupertypesRequest = exports.TypeHierarchySubtypesRequest = exports.TypeHierarchyPrepareRequest = void 0;\nconst messages_1 = require(\"./messages\");\nconst vscode_languageserver_types_1 = require(\"vscode-languageserver-types\");\nconst Is = require(\"./utils/is\");\nconst protocol_implementation_1 = require(\"./protocol.implementation\");\nObject.defineProperty(exports, \"ImplementationRequest\", { enumerable: true, get: function () { return protocol_implementation_1.ImplementationRequest; } });\nconst protocol_typeDefinition_1 = require(\"./protocol.typeDefinition\");\nObject.defineProperty(exports, \"TypeDefinitionRequest\", { enumerable: true, get: function () { return protocol_typeDefinition_1.TypeDefinitionRequest; } });\nconst protocol_workspaceFolder_1 = require(\"./protocol.workspaceFolder\");\nObject.defineProperty(exports, \"WorkspaceFoldersRequest\", { enumerable: true, get: function () { return protocol_workspaceFolder_1.WorkspaceFoldersRequest; } });\nObject.defineProperty(exports, \"DidChangeWorkspaceFoldersNotification\", { enumerable: true, get: function () { return protocol_workspaceFolder_1.DidChangeWorkspaceFoldersNotification; } });\nconst protocol_configuration_1 = require(\"./protocol.configuration\");\nObject.defineProperty(exports, \"ConfigurationRequest\", { enumerable: true, get: function () { return protocol_configuration_1.ConfigurationRequest; } });\nconst protocol_colorProvider_1 = require(\"./protocol.colorProvider\");\nObject.defineProperty(exports, \"DocumentColorRequest\", { enumerable: true, get: function () { return protocol_colorProvider_1.DocumentColorRequest; } });\nObject.defineProperty(exports, \"ColorPresentationRequest\", { enumerable: true, get: function () { return protocol_colorProvider_1.ColorPresentationRequest; } });\nconst protocol_foldingRange_1 = require(\"./protocol.foldingRange\");\nObject.defineProperty(exports, \"FoldingRangeRequest\", { enumerable: true, get: function () { return protocol_foldingRange_1.FoldingRangeRequest; } });\nObject.defineProperty(exports, \"FoldingRangeRefreshRequest\", { enumerable: true, get: function () { return protocol_foldingRange_1.FoldingRangeRefreshRequest; } });\nconst protocol_declaration_1 = require(\"./protocol.declaration\");\nObject.defineProperty(exports, \"DeclarationRequest\", { enumerable: true, get: function () { return protocol_declaration_1.DeclarationRequest; } });\nconst protocol_selectionRange_1 = require(\"./protocol.selectionRange\");\nObject.defineProperty(exports, \"SelectionRangeRequest\", { enumerable: true, get: function () { return protocol_selectionRange_1.SelectionRangeRequest; } });\nconst protocol_progress_1 = require(\"./protocol.progress\");\nObject.defineProperty(exports, \"WorkDoneProgress\", { enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgress; } });\nObject.defineProperty(exports, \"WorkDoneProgressCreateRequest\", { enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgressCreateRequest; } });\nObject.defineProperty(exports, \"WorkDoneProgressCancelNotification\", { enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgressCancelNotification; } });\nconst protocol_callHierarchy_1 = require(\"./protocol.callHierarchy\");\nObject.defineProperty(exports, \"CallHierarchyIncomingCallsRequest\", { enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest; } });\nObject.defineProperty(exports, \"CallHierarchyOutgoingCallsRequest\", { enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest; } });\nObject.defineProperty(exports, \"CallHierarchyPrepareRequest\", { enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyPrepareRequest; } });\nconst protocol_semanticTokens_1 = require(\"./protocol.semanticTokens\");\nObject.defineProperty(exports, \"TokenFormat\", { enumerable: true, get: function () { return protocol_semanticTokens_1.TokenFormat; } });\nObject.defineProperty(exports, \"SemanticTokensRequest\", { enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRequest; } });\nObject.defineProperty(exports, \"SemanticTokensDeltaRequest\", { enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensDeltaRequest; } });\nObject.defineProperty(exports, \"SemanticTokensRangeRequest\", { enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRangeRequest; } });\nObject.defineProperty(exports, \"SemanticTokensRefreshRequest\", { enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRefreshRequest; } });\nObject.defineProperty(exports, \"SemanticTokensRegistrationType\", { enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRegistrationType; } });\nconst protocol_showDocument_1 = require(\"./protocol.showDocument\");\nObject.defineProperty(exports, \"ShowDocumentRequest\", { enumerable: true, get: function () { return protocol_showDocument_1.ShowDocumentRequest; } });\nconst protocol_linkedEditingRange_1 = require(\"./protocol.linkedEditingRange\");\nObject.defineProperty(exports, \"LinkedEditingRangeRequest\", { enumerable: true, get: function () { return protocol_linkedEditingRange_1.LinkedEditingRangeRequest; } });\nconst protocol_fileOperations_1 = require(\"./protocol.fileOperations\");\nObject.defineProperty(exports, \"FileOperationPatternKind\", { enumerable: true, get: function () { return protocol_fileOperations_1.FileOperationPatternKind; } });\nObject.defineProperty(exports, \"DidCreateFilesNotification\", { enumerable: true, get: function () { return protocol_fileOperations_1.DidCreateFilesNotification; } });\nObject.defineProperty(exports, \"WillCreateFilesRequest\", { enumerable: true, get: function () { return protocol_fileOperations_1.WillCreateFilesRequest; } });\nObject.defineProperty(exports, \"DidRenameFilesNotification\", { enumerable: true, get: function () { return protocol_fileOperations_1.DidRenameFilesNotification; } });\nObject.defineProperty(exports, \"WillRenameFilesRequest\", { enumerable: true, get: function () { return protocol_fileOperations_1.WillRenameFilesRequest; } });\nObject.defineProperty(exports, \"DidDeleteFilesNotification\", { enumerable: true, get: function () { return protocol_fileOperations_1.DidDeleteFilesNotification; } });\nObject.defineProperty(exports, \"WillDeleteFilesRequest\", { enumerable: true, get: function () { return protocol_fileOperations_1.WillDeleteFilesRequest; } });\nconst protocol_moniker_1 = require(\"./protocol.moniker\");\nObject.defineProperty(exports, \"UniquenessLevel\", { enumerable: true, get: function () { return protocol_moniker_1.UniquenessLevel; } });\nObject.defineProperty(exports, \"MonikerKind\", { enumerable: true, get: function () { return protocol_moniker_1.MonikerKind; } });\nObject.defineProperty(exports, \"MonikerRequest\", { enumerable: true, get: function () { return protocol_moniker_1.MonikerRequest; } });\nconst protocol_typeHierarchy_1 = require(\"./protocol.typeHierarchy\");\nObject.defineProperty(exports, \"TypeHierarchyPrepareRequest\", { enumerable: true, get: function () { return protocol_typeHierarchy_1.TypeHierarchyPrepareRequest; } });\nObject.defineProperty(exports, \"TypeHierarchySubtypesRequest\", { enumerable: true, get: function () { return protocol_typeHierarchy_1.TypeHierarchySubtypesRequest; } });\nObject.defineProperty(exports, \"TypeHierarchySupertypesRequest\", { enumerable: true, get: function () { return protocol_typeHierarchy_1.TypeHierarchySupertypesRequest; } });\nconst protocol_inlineValue_1 = require(\"./protocol.inlineValue\");\nObject.defineProperty(exports, \"InlineValueRequest\", { enumerable: true, get: function () { return protocol_inlineValue_1.InlineValueRequest; } });\nObject.defineProperty(exports, \"InlineValueRefreshRequest\", { enumerable: true, get: function () { return protocol_inlineValue_1.InlineValueRefreshRequest; } });\nconst protocol_inlayHint_1 = require(\"./protocol.inlayHint\");\nObject.defineProperty(exports, \"InlayHintRequest\", { enumerable: true, get: function () { return protocol_inlayHint_1.InlayHintRequest; } });\nObject.defineProperty(exports, \"InlayHintResolveRequest\", { enumerable: true, get: function () { return protocol_inlayHint_1.InlayHintResolveRequest; } });\nObject.defineProperty(exports, \"InlayHintRefreshRequest\", { enumerable: true, get: function () { return protocol_inlayHint_1.InlayHintRefreshRequest; } });\nconst protocol_diagnostic_1 = require(\"./protocol.diagnostic\");\nObject.defineProperty(exports, \"DiagnosticServerCancellationData\", { enumerable: true, get: function () { return protocol_diagnostic_1.DiagnosticServerCancellationData; } });\nObject.defineProperty(exports, \"DocumentDiagnosticReportKind\", { enumerable: true, get: function () { return protocol_diagnostic_1.DocumentDiagnosticReportKind; } });\nObject.defineProperty(exports, \"DocumentDiagnosticRequest\", { enumerable: true, get: function () { return protocol_diagnostic_1.DocumentDiagnosticRequest; } });\nObject.defineProperty(exports, \"WorkspaceDiagnosticRequest\", { enumerable: true, get: function () { return protocol_diagnostic_1.WorkspaceDiagnosticRequest; } });\nObject.defineProperty(exports, \"DiagnosticRefreshRequest\", { enumerable: true, get: function () { return protocol_diagnostic_1.DiagnosticRefreshRequest; } });\nconst protocol_notebook_1 = require(\"./protocol.notebook\");\nObject.defineProperty(exports, \"NotebookCellKind\", { enumerable: true, get: function () { return protocol_notebook_1.NotebookCellKind; } });\nObject.defineProperty(exports, \"ExecutionSummary\", { enumerable: true, get: function () { return protocol_notebook_1.ExecutionSummary; } });\nObject.defineProperty(exports, \"NotebookCell\", { enumerable: true, get: function () { return protocol_notebook_1.NotebookCell; } });\nObject.defineProperty(exports, \"NotebookDocument\", { enumerable: true, get: function () { return protocol_notebook_1.NotebookDocument; } });\nObject.defineProperty(exports, \"NotebookDocumentSyncRegistrationType\", { enumerable: true, get: function () { return protocol_notebook_1.NotebookDocumentSyncRegistrationType; } });\nObject.defineProperty(exports, \"DidOpenNotebookDocumentNotification\", { enumerable: true, get: function () { return protocol_notebook_1.DidOpenNotebookDocumentNotification; } });\nObject.defineProperty(exports, \"NotebookCellArrayChange\", { enumerable: true, get: function () { return protocol_notebook_1.NotebookCellArrayChange; } });\nObject.defineProperty(exports, \"DidChangeNotebookDocumentNotification\", { enumerable: true, get: function () { return protocol_notebook_1.DidChangeNotebookDocumentNotification; } });\nObject.defineProperty(exports, \"DidSaveNotebookDocumentNotification\", { enumerable: true, get: function () { return protocol_notebook_1.DidSaveNotebookDocumentNotification; } });\nObject.defineProperty(exports, \"DidCloseNotebookDocumentNotification\", { enumerable: true, get: function () { return protocol_notebook_1.DidCloseNotebookDocumentNotification; } });\nconst protocol_inlineCompletion_1 = require(\"./protocol.inlineCompletion\");\nObject.defineProperty(exports, \"InlineCompletionRequest\", { enumerable: true, get: function () { return protocol_inlineCompletion_1.InlineCompletionRequest; } });\n// @ts-ignore: to avoid inlining LocationLink as dynamic import\nlet __noDynamicImport;\n/**\n * The TextDocumentFilter namespace provides helper functions to work with\n * {@link TextDocumentFilter} literals.\n *\n * @since 3.17.0\n */\nvar TextDocumentFilter;\n(function (TextDocumentFilter) {\n function is(value) {\n const candidate = value;\n return Is.string(candidate) || (Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern));\n }\n TextDocumentFilter.is = is;\n})(TextDocumentFilter || (exports.TextDocumentFilter = TextDocumentFilter = {}));\n/**\n * The NotebookDocumentFilter namespace provides helper functions to work with\n * {@link NotebookDocumentFilter} literals.\n *\n * @since 3.17.0\n */\nvar NotebookDocumentFilter;\n(function (NotebookDocumentFilter) {\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && (Is.string(candidate.notebookType) || Is.string(candidate.scheme) || Is.string(candidate.pattern));\n }\n NotebookDocumentFilter.is = is;\n})(NotebookDocumentFilter || (exports.NotebookDocumentFilter = NotebookDocumentFilter = {}));\n/**\n * The NotebookCellTextDocumentFilter namespace provides helper functions to work with\n * {@link NotebookCellTextDocumentFilter} literals.\n *\n * @since 3.17.0\n */\nvar NotebookCellTextDocumentFilter;\n(function (NotebookCellTextDocumentFilter) {\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate)\n && (Is.string(candidate.notebook) || NotebookDocumentFilter.is(candidate.notebook))\n && (candidate.language === undefined || Is.string(candidate.language));\n }\n NotebookCellTextDocumentFilter.is = is;\n})(NotebookCellTextDocumentFilter || (exports.NotebookCellTextDocumentFilter = NotebookCellTextDocumentFilter = {}));\n/**\n * The DocumentSelector namespace provides helper functions to work with\n * {@link DocumentSelector}s.\n */\nvar DocumentSelector;\n(function (DocumentSelector) {\n function is(value) {\n if (!Array.isArray(value)) {\n return false;\n }\n for (let elem of value) {\n if (!Is.string(elem) && !TextDocumentFilter.is(elem) && !NotebookCellTextDocumentFilter.is(elem)) {\n return false;\n }\n }\n return true;\n }\n DocumentSelector.is = is;\n})(DocumentSelector || (exports.DocumentSelector = DocumentSelector = {}));\n/**\n * The `client/registerCapability` request is sent from the server to the client to register a new capability\n * handler on the client side.\n */\nvar RegistrationRequest;\n(function (RegistrationRequest) {\n RegistrationRequest.method = 'client/registerCapability';\n RegistrationRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n RegistrationRequest.type = new messages_1.ProtocolRequestType(RegistrationRequest.method);\n})(RegistrationRequest || (exports.RegistrationRequest = RegistrationRequest = {}));\n/**\n * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability\n * handler on the client side.\n */\nvar UnregistrationRequest;\n(function (UnregistrationRequest) {\n UnregistrationRequest.method = 'client/unregisterCapability';\n UnregistrationRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n UnregistrationRequest.type = new messages_1.ProtocolRequestType(UnregistrationRequest.method);\n})(UnregistrationRequest || (exports.UnregistrationRequest = UnregistrationRequest = {}));\nvar ResourceOperationKind;\n(function (ResourceOperationKind) {\n /**\n * Supports creating new files and folders.\n */\n ResourceOperationKind.Create = 'create';\n /**\n * Supports renaming existing files and folders.\n */\n ResourceOperationKind.Rename = 'rename';\n /**\n * Supports deleting existing files and folders.\n */\n ResourceOperationKind.Delete = 'delete';\n})(ResourceOperationKind || (exports.ResourceOperationKind = ResourceOperationKind = {}));\nvar FailureHandlingKind;\n(function (FailureHandlingKind) {\n /**\n * Applying the workspace change is simply aborted if one of the changes provided\n * fails. All operations executed before the failing operation stay executed.\n */\n FailureHandlingKind.Abort = 'abort';\n /**\n * All operations are executed transactional. That means they either all\n * succeed or no changes at all are applied to the workspace.\n */\n FailureHandlingKind.Transactional = 'transactional';\n /**\n * If the workspace edit contains only textual file changes they are executed transactional.\n * If resource changes (create, rename or delete file) are part of the change the failure\n * handling strategy is abort.\n */\n FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';\n /**\n * The client tries to undo the operations already executed. But there is no\n * guarantee that this is succeeding.\n */\n FailureHandlingKind.Undo = 'undo';\n})(FailureHandlingKind || (exports.FailureHandlingKind = FailureHandlingKind = {}));\n/**\n * A set of predefined position encoding kinds.\n *\n * @since 3.17.0\n */\nvar PositionEncodingKind;\n(function (PositionEncodingKind) {\n /**\n * Character offsets count UTF-8 code units (e.g. bytes).\n */\n PositionEncodingKind.UTF8 = 'utf-8';\n /**\n * Character offsets count UTF-16 code units.\n *\n * This is the default and must always be supported\n * by servers\n */\n PositionEncodingKind.UTF16 = 'utf-16';\n /**\n * Character offsets count UTF-32 code units.\n *\n * Implementation note: these are the same as Unicode codepoints,\n * so this `PositionEncodingKind` may also be used for an\n * encoding-agnostic representation of character offsets.\n */\n PositionEncodingKind.UTF32 = 'utf-32';\n})(PositionEncodingKind || (exports.PositionEncodingKind = PositionEncodingKind = {}));\n/**\n * The StaticRegistrationOptions namespace provides helper functions to work with\n * {@link StaticRegistrationOptions} literals.\n */\nvar StaticRegistrationOptions;\n(function (StaticRegistrationOptions) {\n function hasId(value) {\n const candidate = value;\n return candidate && Is.string(candidate.id) && candidate.id.length > 0;\n }\n StaticRegistrationOptions.hasId = hasId;\n})(StaticRegistrationOptions || (exports.StaticRegistrationOptions = StaticRegistrationOptions = {}));\n/**\n * The TextDocumentRegistrationOptions namespace provides helper functions to work with\n * {@link TextDocumentRegistrationOptions} literals.\n */\nvar TextDocumentRegistrationOptions;\n(function (TextDocumentRegistrationOptions) {\n function is(value) {\n const candidate = value;\n return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));\n }\n TextDocumentRegistrationOptions.is = is;\n})(TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = TextDocumentRegistrationOptions = {}));\n/**\n * The WorkDoneProgressOptions namespace provides helper functions to work with\n * {@link WorkDoneProgressOptions} literals.\n */\nvar WorkDoneProgressOptions;\n(function (WorkDoneProgressOptions) {\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));\n }\n WorkDoneProgressOptions.is = is;\n function hasWorkDoneProgress(value) {\n const candidate = value;\n return candidate && Is.boolean(candidate.workDoneProgress);\n }\n WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;\n})(WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = WorkDoneProgressOptions = {}));\n/**\n * The initialize request is sent from the client to the server.\n * It is sent once as the request after starting up the server.\n * The requests parameter is of type {@link InitializeParams}\n * the response if of type {@link InitializeResult} of a Thenable that\n * resolves to such.\n */\nvar InitializeRequest;\n(function (InitializeRequest) {\n InitializeRequest.method = 'initialize';\n InitializeRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n InitializeRequest.type = new messages_1.ProtocolRequestType(InitializeRequest.method);\n})(InitializeRequest || (exports.InitializeRequest = InitializeRequest = {}));\n/**\n * Known error codes for an `InitializeErrorCodes`;\n */\nvar InitializeErrorCodes;\n(function (InitializeErrorCodes) {\n /**\n * If the protocol version provided by the client can't be handled by the server.\n *\n * @deprecated This initialize error got replaced by client capabilities. There is\n * no version handshake in version 3.0x\n */\n InitializeErrorCodes.unknownProtocolVersion = 1;\n})(InitializeErrorCodes || (exports.InitializeErrorCodes = InitializeErrorCodes = {}));\n/**\n * The initialized notification is sent from the client to the\n * server after the client is fully initialized and the server\n * is allowed to send requests from the server to the client.\n */\nvar InitializedNotification;\n(function (InitializedNotification) {\n InitializedNotification.method = 'initialized';\n InitializedNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n InitializedNotification.type = new messages_1.ProtocolNotificationType(InitializedNotification.method);\n})(InitializedNotification || (exports.InitializedNotification = InitializedNotification = {}));\n//---- Shutdown Method ----\n/**\n * A shutdown request is sent from the client to the server.\n * It is sent once when the client decides to shutdown the\n * server. The only notification that is sent after a shutdown request\n * is the exit event.\n */\nvar ShutdownRequest;\n(function (ShutdownRequest) {\n ShutdownRequest.method = 'shutdown';\n ShutdownRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n ShutdownRequest.type = new messages_1.ProtocolRequestType0(ShutdownRequest.method);\n})(ShutdownRequest || (exports.ShutdownRequest = ShutdownRequest = {}));\n//---- Exit Notification ----\n/**\n * The exit event is sent from the client to the server to\n * ask the server to exit its process.\n */\nvar ExitNotification;\n(function (ExitNotification) {\n ExitNotification.method = 'exit';\n ExitNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n ExitNotification.type = new messages_1.ProtocolNotificationType0(ExitNotification.method);\n})(ExitNotification || (exports.ExitNotification = ExitNotification = {}));\n/**\n * The configuration change notification is sent from the client to the server\n * when the client's configuration has changed. The notification contains\n * the changed configuration as defined by the language client.\n */\nvar DidChangeConfigurationNotification;\n(function (DidChangeConfigurationNotification) {\n DidChangeConfigurationNotification.method = 'workspace/didChangeConfiguration';\n DidChangeConfigurationNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType(DidChangeConfigurationNotification.method);\n})(DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = DidChangeConfigurationNotification = {}));\n//---- Message show and log notifications ----\n/**\n * The message type\n */\nvar MessageType;\n(function (MessageType) {\n /**\n * An error message.\n */\n MessageType.Error = 1;\n /**\n * A warning message.\n */\n MessageType.Warning = 2;\n /**\n * An information message.\n */\n MessageType.Info = 3;\n /**\n * A log message.\n */\n MessageType.Log = 4;\n /**\n * A debug message.\n *\n * @since 3.18.0\n */\n MessageType.Debug = 5;\n})(MessageType || (exports.MessageType = MessageType = {}));\n/**\n * The show message notification is sent from a server to a client to ask\n * the client to display a particular message in the user interface.\n */\nvar ShowMessageNotification;\n(function (ShowMessageNotification) {\n ShowMessageNotification.method = 'window/showMessage';\n ShowMessageNotification.messageDirection = messages_1.MessageDirection.serverToClient;\n ShowMessageNotification.type = new messages_1.ProtocolNotificationType(ShowMessageNotification.method);\n})(ShowMessageNotification || (exports.ShowMessageNotification = ShowMessageNotification = {}));\n/**\n * The show message request is sent from the server to the client to show a message\n * and a set of options actions to the user.\n */\nvar ShowMessageRequest;\n(function (ShowMessageRequest) {\n ShowMessageRequest.method = 'window/showMessageRequest';\n ShowMessageRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n ShowMessageRequest.type = new messages_1.ProtocolRequestType(ShowMessageRequest.method);\n})(ShowMessageRequest || (exports.ShowMessageRequest = ShowMessageRequest = {}));\n/**\n * The log message notification is sent from the server to the client to ask\n * the client to log a particular message.\n */\nvar LogMessageNotification;\n(function (LogMessageNotification) {\n LogMessageNotification.method = 'window/logMessage';\n LogMessageNotification.messageDirection = messages_1.MessageDirection.serverToClient;\n LogMessageNotification.type = new messages_1.ProtocolNotificationType(LogMessageNotification.method);\n})(LogMessageNotification || (exports.LogMessageNotification = LogMessageNotification = {}));\n//---- Telemetry notification\n/**\n * The telemetry event notification is sent from the server to the client to ask\n * the client to log telemetry data.\n */\nvar TelemetryEventNotification;\n(function (TelemetryEventNotification) {\n TelemetryEventNotification.method = 'telemetry/event';\n TelemetryEventNotification.messageDirection = messages_1.MessageDirection.serverToClient;\n TelemetryEventNotification.type = new messages_1.ProtocolNotificationType(TelemetryEventNotification.method);\n})(TelemetryEventNotification || (exports.TelemetryEventNotification = TelemetryEventNotification = {}));\n/**\n * Defines how the host (editor) should sync\n * document changes to the language server.\n */\nvar TextDocumentSyncKind;\n(function (TextDocumentSyncKind) {\n /**\n * Documents should not be synced at all.\n */\n TextDocumentSyncKind.None = 0;\n /**\n * Documents are synced by always sending the full content\n * of the document.\n */\n TextDocumentSyncKind.Full = 1;\n /**\n * Documents are synced by sending the full content on open.\n * After that only incremental updates to the document are\n * send.\n */\n TextDocumentSyncKind.Incremental = 2;\n})(TextDocumentSyncKind || (exports.TextDocumentSyncKind = TextDocumentSyncKind = {}));\n/**\n * The document open notification is sent from the client to the server to signal\n * newly opened text documents. The document's truth is now managed by the client\n * and the server must not try to read the document's truth using the document's\n * uri. Open in this sense means it is managed by the client. It doesn't necessarily\n * mean that its content is presented in an editor. An open notification must not\n * be sent more than once without a corresponding close notification send before.\n * This means open and close notification must be balanced and the max open count\n * is one.\n */\nvar DidOpenTextDocumentNotification;\n(function (DidOpenTextDocumentNotification) {\n DidOpenTextDocumentNotification.method = 'textDocument/didOpen';\n DidOpenTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);\n})(DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = DidOpenTextDocumentNotification = {}));\nvar TextDocumentContentChangeEvent;\n(function (TextDocumentContentChangeEvent) {\n /**\n * Checks whether the information describes a delta event.\n */\n function isIncremental(event) {\n let candidate = event;\n return candidate !== undefined && candidate !== null &&\n typeof candidate.text === 'string' && candidate.range !== undefined &&\n (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number');\n }\n TextDocumentContentChangeEvent.isIncremental = isIncremental;\n /**\n * Checks whether the information describes a full replacement event.\n */\n function isFull(event) {\n let candidate = event;\n return candidate !== undefined && candidate !== null &&\n typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined;\n }\n TextDocumentContentChangeEvent.isFull = isFull;\n})(TextDocumentContentChangeEvent || (exports.TextDocumentContentChangeEvent = TextDocumentContentChangeEvent = {}));\n/**\n * The document change notification is sent from the client to the server to signal\n * changes to a text document.\n */\nvar DidChangeTextDocumentNotification;\n(function (DidChangeTextDocumentNotification) {\n DidChangeTextDocumentNotification.method = 'textDocument/didChange';\n DidChangeTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);\n})(DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = DidChangeTextDocumentNotification = {}));\n/**\n * The document close notification is sent from the client to the server when\n * the document got closed in the client. The document's truth now exists where\n * the document's uri points to (e.g. if the document's uri is a file uri the\n * truth now exists on disk). As with the open notification the close notification\n * is about managing the document's content. Receiving a close notification\n * doesn't mean that the document was open in an editor before. A close\n * notification requires a previous open notification to be sent.\n */\nvar DidCloseTextDocumentNotification;\n(function (DidCloseTextDocumentNotification) {\n DidCloseTextDocumentNotification.method = 'textDocument/didClose';\n DidCloseTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);\n})(DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = DidCloseTextDocumentNotification = {}));\n/**\n * The document save notification is sent from the client to the server when\n * the document got saved in the client.\n */\nvar DidSaveTextDocumentNotification;\n(function (DidSaveTextDocumentNotification) {\n DidSaveTextDocumentNotification.method = 'textDocument/didSave';\n DidSaveTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);\n})(DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = DidSaveTextDocumentNotification = {}));\n/**\n * Represents reasons why a text document is saved.\n */\nvar TextDocumentSaveReason;\n(function (TextDocumentSaveReason) {\n /**\n * Manually triggered, e.g. by the user pressing save, by starting debugging,\n * or by an API call.\n */\n TextDocumentSaveReason.Manual = 1;\n /**\n * Automatic after a delay.\n */\n TextDocumentSaveReason.AfterDelay = 2;\n /**\n * When the editor lost focus.\n */\n TextDocumentSaveReason.FocusOut = 3;\n})(TextDocumentSaveReason || (exports.TextDocumentSaveReason = TextDocumentSaveReason = {}));\n/**\n * A document will save notification is sent from the client to the server before\n * the document is actually saved.\n */\nvar WillSaveTextDocumentNotification;\n(function (WillSaveTextDocumentNotification) {\n WillSaveTextDocumentNotification.method = 'textDocument/willSave';\n WillSaveTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);\n})(WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = WillSaveTextDocumentNotification = {}));\n/**\n * A document will save request is sent from the client to the server before\n * the document is actually saved. The request can return an array of TextEdits\n * which will be applied to the text document before it is saved. Please note that\n * clients might drop results if computing the text edits took too long or if a\n * server constantly fails on this request. This is done to keep the save fast and\n * reliable.\n */\nvar WillSaveTextDocumentWaitUntilRequest;\n(function (WillSaveTextDocumentWaitUntilRequest) {\n WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';\n WillSaveTextDocumentWaitUntilRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);\n})(WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = WillSaveTextDocumentWaitUntilRequest = {}));\n/**\n * The watched files notification is sent from the client to the server when\n * the client detects changes to file watched by the language client.\n */\nvar DidChangeWatchedFilesNotification;\n(function (DidChangeWatchedFilesNotification) {\n DidChangeWatchedFilesNotification.method = 'workspace/didChangeWatchedFiles';\n DidChangeWatchedFilesNotification.messageDirection = messages_1.MessageDirection.clientToServer;\n DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType(DidChangeWatchedFilesNotification.method);\n})(DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = DidChangeWatchedFilesNotification = {}));\n/**\n * The file event type\n */\nvar FileChangeType;\n(function (FileChangeType) {\n /**\n * The file got created.\n */\n FileChangeType.Created = 1;\n /**\n * The file got changed.\n */\n FileChangeType.Changed = 2;\n /**\n * The file got deleted.\n */\n FileChangeType.Deleted = 3;\n})(FileChangeType || (exports.FileChangeType = FileChangeType = {}));\nvar RelativePattern;\n(function (RelativePattern) {\n function is(value) {\n const candidate = value;\n return Is.objectLiteral(candidate) && (vscode_languageserver_types_1.URI.is(candidate.baseUri) || vscode_languageserver_types_1.WorkspaceFolder.is(candidate.baseUri)) && Is.string(candidate.pattern);\n }\n RelativePattern.is = is;\n})(RelativePattern || (exports.RelativePattern = RelativePattern = {}));\nvar WatchKind;\n(function (WatchKind) {\n /**\n * Interested in create events.\n */\n WatchKind.Create = 1;\n /**\n * Interested in change events\n */\n WatchKind.Change = 2;\n /**\n * Interested in delete events\n */\n WatchKind.Delete = 4;\n})(WatchKind || (exports.WatchKind = WatchKind = {}));\n/**\n * Diagnostics notification are sent from the server to the client to signal\n * results of validation runs.\n */\nvar PublishDiagnosticsNotification;\n(function (PublishDiagnosticsNotification) {\n PublishDiagnosticsNotification.method = 'textDocument/publishDiagnostics';\n PublishDiagnosticsNotification.messageDirection = messages_1.MessageDirection.serverToClient;\n PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType(PublishDiagnosticsNotification.method);\n})(PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = PublishDiagnosticsNotification = {}));\n/**\n * How a completion was triggered\n */\nvar CompletionTriggerKind;\n(function (CompletionTriggerKind) {\n /**\n * Completion was triggered by typing an identifier (24x7 code\n * complete), manual invocation (e.g Ctrl+Space) or via API.\n */\n CompletionTriggerKind.Invoked = 1;\n /**\n * Completion was triggered by a trigger character specified by\n * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.\n */\n CompletionTriggerKind.TriggerCharacter = 2;\n /**\n * Completion was re-triggered as current completion list is incomplete\n */\n CompletionTriggerKind.TriggerForIncompleteCompletions = 3;\n})(CompletionTriggerKind || (exports.CompletionTriggerKind = CompletionTriggerKind = {}));\n/**\n * Request to request completion at a given text document position. The request's\n * parameter is of type {@link TextDocumentPosition} the response\n * is of type {@link CompletionItem CompletionItem[]} or {@link CompletionList}\n * or a Thenable that resolves to such.\n *\n * The request can delay the computation of the {@link CompletionItem.detail `detail`}\n * and {@link CompletionItem.documentation `documentation`} properties to the `completionItem/resolve`\n * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,\n * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.\n */\nvar CompletionRequest;\n(function (CompletionRequest) {\n CompletionRequest.method = 'textDocument/completion';\n CompletionRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);\n})(CompletionRequest || (exports.CompletionRequest = CompletionRequest = {}));\n/**\n * Request to resolve additional information for a given completion item.The request's\n * parameter is of type {@link CompletionItem} the response\n * is of type {@link CompletionItem} or a Thenable that resolves to such.\n */\nvar CompletionResolveRequest;\n(function (CompletionResolveRequest) {\n CompletionResolveRequest.method = 'completionItem/resolve';\n CompletionResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);\n})(CompletionResolveRequest || (exports.CompletionResolveRequest = CompletionResolveRequest = {}));\n/**\n * Request to request hover information at a given text document position. The request's\n * parameter is of type {@link TextDocumentPosition} the response is of\n * type {@link Hover} or a Thenable that resolves to such.\n */\nvar HoverRequest;\n(function (HoverRequest) {\n HoverRequest.method = 'textDocument/hover';\n HoverRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);\n})(HoverRequest || (exports.HoverRequest = HoverRequest = {}));\n/**\n * How a signature help was triggered.\n *\n * @since 3.15.0\n */\nvar SignatureHelpTriggerKind;\n(function (SignatureHelpTriggerKind) {\n /**\n * Signature help was invoked manually by the user or by a command.\n */\n SignatureHelpTriggerKind.Invoked = 1;\n /**\n * Signature help was triggered by a trigger character.\n */\n SignatureHelpTriggerKind.TriggerCharacter = 2;\n /**\n * Signature help was triggered by the cursor moving or by the document content changing.\n */\n SignatureHelpTriggerKind.ContentChange = 3;\n})(SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = SignatureHelpTriggerKind = {}));\nvar SignatureHelpRequest;\n(function (SignatureHelpRequest) {\n SignatureHelpRequest.method = 'textDocument/signatureHelp';\n SignatureHelpRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);\n})(SignatureHelpRequest || (exports.SignatureHelpRequest = SignatureHelpRequest = {}));\n/**\n * A request to resolve the definition location of a symbol at a given text\n * document position. The request's parameter is of type {@link TextDocumentPosition}\n * the response is of either type {@link Definition} or a typed array of\n * {@link DefinitionLink} or a Thenable that resolves to such.\n */\nvar DefinitionRequest;\n(function (DefinitionRequest) {\n DefinitionRequest.method = 'textDocument/definition';\n DefinitionRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);\n})(DefinitionRequest || (exports.DefinitionRequest = DefinitionRequest = {}));\n/**\n * A request to resolve project-wide references for the symbol denoted\n * by the given text document position. The request's parameter is of\n * type {@link ReferenceParams} the response is of type\n * {@link Location Location[]} or a Thenable that resolves to such.\n */\nvar ReferencesRequest;\n(function (ReferencesRequest) {\n ReferencesRequest.method = 'textDocument/references';\n ReferencesRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);\n})(ReferencesRequest || (exports.ReferencesRequest = ReferencesRequest = {}));\n/**\n * Request to resolve a {@link DocumentHighlight} for a given\n * text document position. The request's parameter is of type {@link TextDocumentPosition}\n * the request response is an array of type {@link DocumentHighlight}\n * or a Thenable that resolves to such.\n */\nvar DocumentHighlightRequest;\n(function (DocumentHighlightRequest) {\n DocumentHighlightRequest.method = 'textDocument/documentHighlight';\n DocumentHighlightRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);\n})(DocumentHighlightRequest || (exports.DocumentHighlightRequest = DocumentHighlightRequest = {}));\n/**\n * A request to list all symbols found in a given text document. The request's\n * parameter is of type {@link TextDocumentIdentifier} the\n * response is of type {@link SymbolInformation SymbolInformation[]} or a Thenable\n * that resolves to such.\n */\nvar DocumentSymbolRequest;\n(function (DocumentSymbolRequest) {\n DocumentSymbolRequest.method = 'textDocument/documentSymbol';\n DocumentSymbolRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);\n})(DocumentSymbolRequest || (exports.DocumentSymbolRequest = DocumentSymbolRequest = {}));\n/**\n * A request to provide commands for the given text document and range.\n */\nvar CodeActionRequest;\n(function (CodeActionRequest) {\n CodeActionRequest.method = 'textDocument/codeAction';\n CodeActionRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);\n})(CodeActionRequest || (exports.CodeActionRequest = CodeActionRequest = {}));\n/**\n * Request to resolve additional information for a given code action.The request's\n * parameter is of type {@link CodeAction} the response\n * is of type {@link CodeAction} or a Thenable that resolves to such.\n */\nvar CodeActionResolveRequest;\n(function (CodeActionResolveRequest) {\n CodeActionResolveRequest.method = 'codeAction/resolve';\n CodeActionResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n CodeActionResolveRequest.type = new messages_1.ProtocolRequestType(CodeActionResolveRequest.method);\n})(CodeActionResolveRequest || (exports.CodeActionResolveRequest = CodeActionResolveRequest = {}));\n/**\n * A request to list project-wide symbols matching the query string given\n * by the {@link WorkspaceSymbolParams}. The response is\n * of type {@link SymbolInformation SymbolInformation[]} or a Thenable that\n * resolves to such.\n *\n * @since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients\n * need to advertise support for WorkspaceSymbols via the client capability\n * `workspace.symbol.resolveSupport`.\n *\n */\nvar WorkspaceSymbolRequest;\n(function (WorkspaceSymbolRequest) {\n WorkspaceSymbolRequest.method = 'workspace/symbol';\n WorkspaceSymbolRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);\n})(WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = WorkspaceSymbolRequest = {}));\n/**\n * A request to resolve the range inside the workspace\n * symbol's location.\n *\n * @since 3.17.0\n */\nvar WorkspaceSymbolResolveRequest;\n(function (WorkspaceSymbolResolveRequest) {\n WorkspaceSymbolResolveRequest.method = 'workspaceSymbol/resolve';\n WorkspaceSymbolResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n WorkspaceSymbolResolveRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolResolveRequest.method);\n})(WorkspaceSymbolResolveRequest || (exports.WorkspaceSymbolResolveRequest = WorkspaceSymbolResolveRequest = {}));\n/**\n * A request to provide code lens for the given text document.\n */\nvar CodeLensRequest;\n(function (CodeLensRequest) {\n CodeLensRequest.method = 'textDocument/codeLens';\n CodeLensRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n CodeLensRequest.type = new messages_1.ProtocolRequestType(CodeLensRequest.method);\n})(CodeLensRequest || (exports.CodeLensRequest = CodeLensRequest = {}));\n/**\n * A request to resolve a command for a given code lens.\n */\nvar CodeLensResolveRequest;\n(function (CodeLensResolveRequest) {\n CodeLensResolveRequest.method = 'codeLens/resolve';\n CodeLensResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n CodeLensResolveRequest.type = new messages_1.ProtocolRequestType(CodeLensResolveRequest.method);\n})(CodeLensResolveRequest || (exports.CodeLensResolveRequest = CodeLensResolveRequest = {}));\n/**\n * A request to refresh all code actions\n *\n * @since 3.16.0\n */\nvar CodeLensRefreshRequest;\n(function (CodeLensRefreshRequest) {\n CodeLensRefreshRequest.method = `workspace/codeLens/refresh`;\n CodeLensRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n CodeLensRefreshRequest.type = new messages_1.ProtocolRequestType0(CodeLensRefreshRequest.method);\n})(CodeLensRefreshRequest || (exports.CodeLensRefreshRequest = CodeLensRefreshRequest = {}));\n/**\n * A request to provide document links\n */\nvar DocumentLinkRequest;\n(function (DocumentLinkRequest) {\n DocumentLinkRequest.method = 'textDocument/documentLink';\n DocumentLinkRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);\n})(DocumentLinkRequest || (exports.DocumentLinkRequest = DocumentLinkRequest = {}));\n/**\n * Request to resolve additional information for a given document link. The request's\n * parameter is of type {@link DocumentLink} the response\n * is of type {@link DocumentLink} or a Thenable that resolves to such.\n */\nvar DocumentLinkResolveRequest;\n(function (DocumentLinkResolveRequest) {\n DocumentLinkResolveRequest.method = 'documentLink/resolve';\n DocumentLinkResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType(DocumentLinkResolveRequest.method);\n})(DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = DocumentLinkResolveRequest = {}));\n/**\n * A request to format a whole document.\n */\nvar DocumentFormattingRequest;\n(function (DocumentFormattingRequest) {\n DocumentFormattingRequest.method = 'textDocument/formatting';\n DocumentFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);\n})(DocumentFormattingRequest || (exports.DocumentFormattingRequest = DocumentFormattingRequest = {}));\n/**\n * A request to format a range in a document.\n */\nvar DocumentRangeFormattingRequest;\n(function (DocumentRangeFormattingRequest) {\n DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';\n DocumentRangeFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);\n})(DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = DocumentRangeFormattingRequest = {}));\n/**\n * A request to format ranges in a document.\n *\n * @since 3.18.0\n * @proposed\n */\nvar DocumentRangesFormattingRequest;\n(function (DocumentRangesFormattingRequest) {\n DocumentRangesFormattingRequest.method = 'textDocument/rangesFormatting';\n DocumentRangesFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DocumentRangesFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangesFormattingRequest.method);\n})(DocumentRangesFormattingRequest || (exports.DocumentRangesFormattingRequest = DocumentRangesFormattingRequest = {}));\n/**\n * A request to format a document on type.\n */\nvar DocumentOnTypeFormattingRequest;\n(function (DocumentOnTypeFormattingRequest) {\n DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';\n DocumentOnTypeFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);\n})(DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = DocumentOnTypeFormattingRequest = {}));\n//---- Rename ----------------------------------------------\nvar PrepareSupportDefaultBehavior;\n(function (PrepareSupportDefaultBehavior) {\n /**\n * The client's default behavior is to select the identifier\n * according the to language's syntax rule.\n */\n PrepareSupportDefaultBehavior.Identifier = 1;\n})(PrepareSupportDefaultBehavior || (exports.PrepareSupportDefaultBehavior = PrepareSupportDefaultBehavior = {}));\n/**\n * A request to rename a symbol.\n */\nvar RenameRequest;\n(function (RenameRequest) {\n RenameRequest.method = 'textDocument/rename';\n RenameRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);\n})(RenameRequest || (exports.RenameRequest = RenameRequest = {}));\n/**\n * A request to test and perform the setup necessary for a rename.\n *\n * @since 3.16 - support for default behavior\n */\nvar PrepareRenameRequest;\n(function (PrepareRenameRequest) {\n PrepareRenameRequest.method = 'textDocument/prepareRename';\n PrepareRenameRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);\n})(PrepareRenameRequest || (exports.PrepareRenameRequest = PrepareRenameRequest = {}));\n/**\n * A request send from the client to the server to execute a command. The request might return\n * a workspace edit which the client will apply to the workspace.\n */\nvar ExecuteCommandRequest;\n(function (ExecuteCommandRequest) {\n ExecuteCommandRequest.method = 'workspace/executeCommand';\n ExecuteCommandRequest.messageDirection = messages_1.MessageDirection.clientToServer;\n ExecuteCommandRequest.type = new messages_1.ProtocolRequestType(ExecuteCommandRequest.method);\n})(ExecuteCommandRequest || (exports.ExecuteCommandRequest = ExecuteCommandRequest = {}));\n/**\n * A request sent from the server to the client to modified certain resources.\n */\nvar ApplyWorkspaceEditRequest;\n(function (ApplyWorkspaceEditRequest) {\n ApplyWorkspaceEditRequest.method = 'workspace/applyEdit';\n ApplyWorkspaceEditRequest.messageDirection = messages_1.MessageDirection.serverToClient;\n ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');\n})(ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = ApplyWorkspaceEditRequest = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createProtocolConnection = void 0;\nconst vscode_jsonrpc_1 = require(\"vscode-jsonrpc\");\nfunction createProtocolConnection(input, output, logger, options) {\n if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) {\n options = { connectionStrategy: options };\n }\n return (0, vscode_jsonrpc_1.createMessageConnection)(input, output, logger, options);\n}\nexports.createProtocolConnection = createProtocolConnection;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LSPErrorCodes = exports.createProtocolConnection = void 0;\n__exportStar(require(\"vscode-jsonrpc\"), exports);\n__exportStar(require(\"vscode-languageserver-types\"), exports);\n__exportStar(require(\"./messages\"), exports);\n__exportStar(require(\"./protocol\"), exports);\nvar connection_1 = require(\"./connection\");\nObject.defineProperty(exports, \"createProtocolConnection\", { enumerable: true, get: function () { return connection_1.createProtocolConnection; } });\nvar LSPErrorCodes;\n(function (LSPErrorCodes) {\n /**\n * This is the start range of LSP reserved error codes.\n * It doesn't denote a real error code.\n *\n * @since 3.16.0\n */\n LSPErrorCodes.lspReservedErrorRangeStart = -32899;\n /**\n * A request failed but it was syntactically correct, e.g the\n * method name was known and the parameters were valid. The error\n * message should contain human readable information about why\n * the request failed.\n *\n * @since 3.17.0\n */\n LSPErrorCodes.RequestFailed = -32803;\n /**\n * The server cancelled the request. This error code should\n * only be used for requests that explicitly support being\n * server cancellable.\n *\n * @since 3.17.0\n */\n LSPErrorCodes.ServerCancelled = -32802;\n /**\n * The server detected that the content of a document got\n * modified outside normal conditions. A server should\n * NOT send this error code if it detects a content change\n * in it unprocessed messages. The result even computed\n * on an older state might still be useful for the client.\n *\n * If a client decides that a result is not of any use anymore\n * the client should cancel the request.\n */\n LSPErrorCodes.ContentModified = -32801;\n /**\n * The client has canceled a request and a server as detected\n * the cancel.\n */\n LSPErrorCodes.RequestCancelled = -32800;\n /**\n * This is the end range of LSP reserved error codes.\n * It doesn't denote a real error code.\n *\n * @since 3.16.0\n */\n LSPErrorCodes.lspReservedErrorRangeEnd = -32800;\n})(LSPErrorCodes || (exports.LSPErrorCodes = LSPErrorCodes = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createProtocolConnection = void 0;\nconst node_1 = require(\"vscode-jsonrpc/node\");\n__exportStar(require(\"vscode-jsonrpc/node\"), exports);\n__exportStar(require(\"../common/api\"), exports);\nfunction createProtocolConnection(input, output, logger, options) {\n return (0, node_1.createMessageConnection)(input, output, logger, options);\n}\nexports.createProtocolConnection = createProtocolConnection;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.forEach = exports.mapAsync = exports.map = exports.clearTestMode = exports.setTestMode = exports.Semaphore = exports.Delayer = void 0;\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nclass Delayer {\n constructor(defaultDelay) {\n this.defaultDelay = defaultDelay;\n this.timeout = undefined;\n this.completionPromise = undefined;\n this.onSuccess = undefined;\n this.task = undefined;\n }\n trigger(task, delay = this.defaultDelay) {\n this.task = task;\n if (delay >= 0) {\n this.cancelTimeout();\n }\n if (!this.completionPromise) {\n this.completionPromise = new Promise((resolve) => {\n this.onSuccess = resolve;\n }).then(() => {\n this.completionPromise = undefined;\n this.onSuccess = undefined;\n var result = this.task();\n this.task = undefined;\n return result;\n });\n }\n if (delay >= 0 || this.timeout === void 0) {\n this.timeout = (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(() => {\n this.timeout = undefined;\n this.onSuccess(undefined);\n }, delay >= 0 ? delay : this.defaultDelay);\n }\n return this.completionPromise;\n }\n forceDelivery() {\n if (!this.completionPromise) {\n return undefined;\n }\n this.cancelTimeout();\n let result = this.task();\n this.completionPromise = undefined;\n this.onSuccess = undefined;\n this.task = undefined;\n return result;\n }\n isTriggered() {\n return this.timeout !== undefined;\n }\n cancel() {\n this.cancelTimeout();\n this.completionPromise = undefined;\n }\n cancelTimeout() {\n if (this.timeout !== undefined) {\n this.timeout.dispose();\n this.timeout = undefined;\n }\n }\n}\nexports.Delayer = Delayer;\nclass Semaphore {\n constructor(capacity = 1) {\n if (capacity <= 0) {\n throw new Error('Capacity must be greater than 0');\n }\n this._capacity = capacity;\n this._active = 0;\n this._waiting = [];\n }\n lock(thunk) {\n return new Promise((resolve, reject) => {\n this._waiting.push({ thunk, resolve, reject });\n this.runNext();\n });\n }\n get active() {\n return this._active;\n }\n runNext() {\n if (this._waiting.length === 0 || this._active === this._capacity) {\n return;\n }\n (0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => this.doRunNext());\n }\n doRunNext() {\n if (this._waiting.length === 0 || this._active === this._capacity) {\n return;\n }\n const next = this._waiting.shift();\n this._active++;\n if (this._active > this._capacity) {\n throw new Error(`To many thunks active`);\n }\n try {\n const result = next.thunk();\n if (result instanceof Promise) {\n result.then((value) => {\n this._active--;\n next.resolve(value);\n this.runNext();\n }, (err) => {\n this._active--;\n next.reject(err);\n this.runNext();\n });\n }\n else {\n this._active--;\n next.resolve(result);\n this.runNext();\n }\n }\n catch (err) {\n this._active--;\n next.reject(err);\n this.runNext();\n }\n }\n}\nexports.Semaphore = Semaphore;\nlet $test = false;\nfunction setTestMode() {\n $test = true;\n}\nexports.setTestMode = setTestMode;\nfunction clearTestMode() {\n $test = false;\n}\nexports.clearTestMode = clearTestMode;\nconst defaultYieldTimeout = 15 /*ms*/;\nclass Timer {\n constructor(yieldAfter = defaultYieldTimeout) {\n this.yieldAfter = $test === true ? Math.max(yieldAfter, 2) : Math.max(yieldAfter, defaultYieldTimeout);\n this.startTime = Date.now();\n this.counter = 0;\n this.total = 0;\n // start with a counter interval of 1.\n this.counterInterval = 1;\n }\n start() {\n this.counter = 0;\n this.total = 0;\n this.counterInterval = 1;\n this.startTime = Date.now();\n }\n shouldYield() {\n if (++this.counter >= this.counterInterval) {\n const timeTaken = Date.now() - this.startTime;\n const timeLeft = Math.max(0, this.yieldAfter - timeTaken);\n this.total += this.counter;\n this.counter = 0;\n if (timeTaken >= this.yieldAfter || timeLeft <= 1) {\n // Yield also if time left <= 1 since we compute the counter\n // for max < 2 ms.\n // Start with interval 1 again. We could do some calculation\n // with using 80% of the last counter however other things (GC)\n // affect the timing heavily since we have small timings (1 - 15ms).\n this.counterInterval = 1;\n this.total = 0;\n return true;\n }\n else {\n // Only increase the counter until we have spent <= 2 ms. Increasing\n // the counter further is very fragile since timing is influenced\n // by other things and can increase the counter too much. This will result\n // that we yield in average after [14 - 16]ms.\n switch (timeTaken) {\n case 0:\n case 1:\n this.counterInterval = this.total * 2;\n break;\n }\n }\n }\n return false;\n }\n}\nasync function map(items, func, token, options) {\n if (items.length === 0) {\n return [];\n }\n const result = new Array(items.length);\n const timer = new Timer(options?.yieldAfter);\n function convertBatch(start) {\n timer.start();\n for (let i = start; i < items.length; i++) {\n result[i] = func(items[i]);\n if (timer.shouldYield()) {\n options?.yieldCallback && options.yieldCallback();\n return i + 1;\n }\n }\n return -1;\n }\n // Convert the first batch sync on the same frame.\n let index = convertBatch(0);\n while (index !== -1) {\n if (token !== undefined && token.isCancellationRequested) {\n break;\n }\n index = await new Promise((resolve) => {\n (0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => {\n resolve(convertBatch(index));\n });\n });\n }\n return result;\n}\nexports.map = map;\nasync function mapAsync(items, func, token, options) {\n if (items.length === 0) {\n return [];\n }\n const result = new Array(items.length);\n const timer = new Timer(options?.yieldAfter);\n async function convertBatch(start) {\n timer.start();\n for (let i = start; i < items.length; i++) {\n result[i] = await func(items[i], token);\n if (timer.shouldYield()) {\n options?.yieldCallback && options.yieldCallback();\n return i + 1;\n }\n }\n return -1;\n }\n let index = await convertBatch(0);\n while (index !== -1) {\n if (token !== undefined && token.isCancellationRequested) {\n break;\n }\n index = await new Promise((resolve) => {\n (0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => {\n resolve(convertBatch(index));\n });\n });\n }\n return result;\n}\nexports.mapAsync = mapAsync;\nasync function forEach(items, func, token, options) {\n if (items.length === 0) {\n return;\n }\n const timer = new Timer(options?.yieldAfter);\n function runBatch(start) {\n timer.start();\n for (let i = start; i < items.length; i++) {\n func(items[i]);\n if (timer.shouldYield()) {\n options?.yieldCallback && options.yieldCallback();\n return i + 1;\n }\n }\n return -1;\n }\n // Convert the first batch sync on the same frame.\n let index = runBatch(0);\n while (index !== -1) {\n if (token !== undefined && token.isCancellationRequested) {\n break;\n }\n index = await new Promise((resolve) => {\n (0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => {\n resolve(runBatch(index));\n });\n });\n }\n}\nexports.forEach = forEach;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code = require(\"vscode\");\nclass ProtocolCompletionItem extends code.CompletionItem {\n constructor(label) {\n super(label);\n }\n}\nexports.default = ProtocolCompletionItem;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code = require(\"vscode\");\nclass ProtocolCodeLens extends code.CodeLens {\n constructor(range) {\n super(range);\n }\n}\nexports.default = ProtocolCodeLens;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code = require(\"vscode\");\nclass ProtocolDocumentLink extends code.DocumentLink {\n constructor(range, target) {\n super(range, target);\n }\n}\nexports.default = ProtocolDocumentLink;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst vscode = require(\"vscode\");\nclass ProtocolCodeAction extends vscode.CodeAction {\n constructor(title, data) {\n super(title);\n this.data = data;\n }\n}\nexports.default = ProtocolCodeAction;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ProtocolDiagnostic = exports.DiagnosticCode = void 0;\nconst vscode = require(\"vscode\");\nconst Is = require(\"./utils/is\");\nvar DiagnosticCode;\n(function (DiagnosticCode) {\n function is(value) {\n const candidate = value;\n return candidate !== undefined && candidate !== null && (Is.number(candidate.value) || Is.string(candidate.value)) && Is.string(candidate.target);\n }\n DiagnosticCode.is = is;\n})(DiagnosticCode || (exports.DiagnosticCode = DiagnosticCode = {}));\nclass ProtocolDiagnostic extends vscode.Diagnostic {\n constructor(range, message, severity, data) {\n super(range, message, severity);\n this.data = data;\n this.hasDiagnosticCode = false;\n }\n}\nexports.ProtocolDiagnostic = ProtocolDiagnostic;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code = require(\"vscode\");\nclass ProtocolCallHierarchyItem extends code.CallHierarchyItem {\n constructor(kind, name, detail, uri, range, selectionRange, data) {\n super(kind, name, detail, uri, range, selectionRange);\n if (data !== undefined) {\n this.data = data;\n }\n }\n}\nexports.default = ProtocolCallHierarchyItem;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code = require(\"vscode\");\nclass ProtocolTypeHierarchyItem extends code.TypeHierarchyItem {\n constructor(kind, name, detail, uri, range, selectionRange, data) {\n super(kind, name, detail, uri, range, selectionRange);\n if (data !== undefined) {\n this.data = data;\n }\n }\n}\nexports.default = ProtocolTypeHierarchyItem;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code = require(\"vscode\");\nclass WorkspaceSymbol extends code.SymbolInformation {\n constructor(name, kind, containerName, locationOrUri, data) {\n const hasRange = !(locationOrUri instanceof code.Uri);\n super(name, kind, containerName, hasRange ? locationOrUri : new code.Location(locationOrUri, new code.Range(0, 0, 0, 0)));\n this.hasRange = hasRange;\n if (data !== undefined) {\n this.data = data;\n }\n }\n}\nexports.default = WorkspaceSymbol;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code = require(\"vscode\");\nclass ProtocolInlayHint extends code.InlayHint {\n constructor(position, label, kind) {\n super(position, label, kind);\n }\n}\nexports.default = ProtocolInlayHint;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createConverter = void 0;\nconst code = require(\"vscode\");\nconst proto = require(\"vscode-languageserver-protocol\");\nconst Is = require(\"./utils/is\");\nconst async = require(\"./utils/async\");\nconst protocolCompletionItem_1 = require(\"./protocolCompletionItem\");\nconst protocolCodeLens_1 = require(\"./protocolCodeLens\");\nconst protocolDocumentLink_1 = require(\"./protocolDocumentLink\");\nconst protocolCodeAction_1 = require(\"./protocolCodeAction\");\nconst protocolDiagnostic_1 = require(\"./protocolDiagnostic\");\nconst protocolCallHierarchyItem_1 = require(\"./protocolCallHierarchyItem\");\nconst protocolTypeHierarchyItem_1 = require(\"./protocolTypeHierarchyItem\");\nconst protocolWorkspaceSymbol_1 = require(\"./protocolWorkspaceSymbol\");\nconst protocolInlayHint_1 = require(\"./protocolInlayHint\");\nvar InsertReplaceRange;\n(function (InsertReplaceRange) {\n function is(value) {\n const candidate = value;\n return candidate && !!candidate.inserting && !!candidate.replacing;\n }\n InsertReplaceRange.is = is;\n})(InsertReplaceRange || (InsertReplaceRange = {}));\nfunction createConverter(uriConverter) {\n const nullConverter = (value) => value.toString();\n const _uriConverter = uriConverter || nullConverter;\n function asUri(value) {\n return _uriConverter(value);\n }\n function asTextDocumentIdentifier(textDocument) {\n return {\n uri: _uriConverter(textDocument.uri)\n };\n }\n function asTextDocumentItem(textDocument) {\n return {\n uri: _uriConverter(textDocument.uri),\n languageId: textDocument.languageId,\n version: textDocument.version,\n text: textDocument.getText()\n };\n }\n function asVersionedTextDocumentIdentifier(textDocument) {\n return {\n uri: _uriConverter(textDocument.uri),\n version: textDocument.version\n };\n }\n function asOpenTextDocumentParams(textDocument) {\n return {\n textDocument: asTextDocumentItem(textDocument)\n };\n }\n function isTextDocumentChangeEvent(value) {\n const candidate = value;\n return !!candidate.document && !!candidate.contentChanges;\n }\n function isTextDocument(value) {\n const candidate = value;\n return !!candidate.uri && !!candidate.version;\n }\n function asChangeTextDocumentParams(arg0, arg1, arg2) {\n if (isTextDocument(arg0)) {\n const result = {\n textDocument: {\n uri: _uriConverter(arg0.uri),\n version: arg0.version\n },\n contentChanges: [{ text: arg0.getText() }]\n };\n return result;\n }\n else if (isTextDocumentChangeEvent(arg0)) {\n const uri = arg1;\n const version = arg2;\n const result = {\n textDocument: {\n uri: _uriConverter(uri),\n version: version\n },\n contentChanges: arg0.contentChanges.map((change) => {\n const range = change.range;\n return {\n range: {\n start: { line: range.start.line, character: range.start.character },\n end: { line: range.end.line, character: range.end.character }\n },\n rangeLength: change.rangeLength,\n text: change.text\n };\n })\n };\n return result;\n }\n else {\n throw Error('Unsupported text document change parameter');\n }\n }\n function asCloseTextDocumentParams(textDocument) {\n return {\n textDocument: asTextDocumentIdentifier(textDocument)\n };\n }\n function asSaveTextDocumentParams(textDocument, includeContent = false) {\n let result = {\n textDocument: asTextDocumentIdentifier(textDocument)\n };\n if (includeContent) {\n result.text = textDocument.getText();\n }\n return result;\n }\n function asTextDocumentSaveReason(reason) {\n switch (reason) {\n case code.TextDocumentSaveReason.Manual:\n return proto.TextDocumentSaveReason.Manual;\n case code.TextDocumentSaveReason.AfterDelay:\n return proto.TextDocumentSaveReason.AfterDelay;\n case code.TextDocumentSaveReason.FocusOut:\n return proto.TextDocumentSaveReason.FocusOut;\n }\n return proto.TextDocumentSaveReason.Manual;\n }\n function asWillSaveTextDocumentParams(event) {\n return {\n textDocument: asTextDocumentIdentifier(event.document),\n reason: asTextDocumentSaveReason(event.reason)\n };\n }\n function asDidCreateFilesParams(event) {\n return {\n files: event.files.map((fileUri) => ({\n uri: _uriConverter(fileUri),\n })),\n };\n }\n function asDidRenameFilesParams(event) {\n return {\n files: event.files.map((file) => ({\n oldUri: _uriConverter(file.oldUri),\n newUri: _uriConverter(file.newUri),\n })),\n };\n }\n function asDidDeleteFilesParams(event) {\n return {\n files: event.files.map((fileUri) => ({\n uri: _uriConverter(fileUri),\n })),\n };\n }\n function asWillCreateFilesParams(event) {\n return {\n files: event.files.map((fileUri) => ({\n uri: _uriConverter(fileUri),\n })),\n };\n }\n function asWillRenameFilesParams(event) {\n return {\n files: event.files.map((file) => ({\n oldUri: _uriConverter(file.oldUri),\n newUri: _uriConverter(file.newUri),\n })),\n };\n }\n function asWillDeleteFilesParams(event) {\n return {\n files: event.files.map((fileUri) => ({\n uri: _uriConverter(fileUri),\n })),\n };\n }\n function asTextDocumentPositionParams(textDocument, position) {\n return {\n textDocument: asTextDocumentIdentifier(textDocument),\n position: asWorkerPosition(position)\n };\n }\n function asCompletionTriggerKind(triggerKind) {\n switch (triggerKind) {\n case code.CompletionTriggerKind.TriggerCharacter:\n return proto.CompletionTriggerKind.TriggerCharacter;\n case code.CompletionTriggerKind.TriggerForIncompleteCompletions:\n return proto.CompletionTriggerKind.TriggerForIncompleteCompletions;\n default:\n return proto.CompletionTriggerKind.Invoked;\n }\n }\n function asCompletionParams(textDocument, position, context) {\n return {\n textDocument: asTextDocumentIdentifier(textDocument),\n position: asWorkerPosition(position),\n context: {\n triggerKind: asCompletionTriggerKind(context.triggerKind),\n triggerCharacter: context.triggerCharacter\n }\n };\n }\n function asSignatureHelpTriggerKind(triggerKind) {\n switch (triggerKind) {\n case code.SignatureHelpTriggerKind.Invoke:\n return proto.SignatureHelpTriggerKind.Invoked;\n case code.SignatureHelpTriggerKind.TriggerCharacter:\n return proto.SignatureHelpTriggerKind.TriggerCharacter;\n case code.SignatureHelpTriggerKind.ContentChange:\n return proto.SignatureHelpTriggerKind.ContentChange;\n }\n }\n function asParameterInformation(value) {\n // We leave the documentation out on purpose since it usually adds no\n // value for the server.\n return {\n label: value.label\n };\n }\n function asParameterInformations(values) {\n return values.map(asParameterInformation);\n }\n function asSignatureInformation(value) {\n // We leave the documentation out on purpose since it usually adds no\n // value for the server.\n return {\n label: value.label,\n parameters: asParameterInformations(value.parameters)\n };\n }\n function asSignatureInformations(values) {\n return values.map(asSignatureInformation);\n }\n function asSignatureHelp(value) {\n if (value === undefined) {\n return value;\n }\n return {\n signatures: asSignatureInformations(value.signatures),\n activeSignature: value.activeSignature,\n activeParameter: value.activeParameter\n };\n }\n function asSignatureHelpParams(textDocument, position, context) {\n return {\n textDocument: asTextDocumentIdentifier(textDocument),\n position: asWorkerPosition(position),\n context: {\n isRetrigger: context.isRetrigger,\n triggerCharacter: context.triggerCharacter,\n triggerKind: asSignatureHelpTriggerKind(context.triggerKind),\n activeSignatureHelp: asSignatureHelp(context.activeSignatureHelp)\n }\n };\n }\n function asWorkerPosition(position) {\n return { line: position.line, character: position.character };\n }\n function asPosition(value) {\n if (value === undefined || value === null) {\n return value;\n }\n return { line: value.line > proto.uinteger.MAX_VALUE ? proto.uinteger.MAX_VALUE : value.line, character: value.character > proto.uinteger.MAX_VALUE ? proto.uinteger.MAX_VALUE : value.character };\n }\n function asPositions(values, token) {\n return async.map(values, asPosition, token);\n }\n function asPositionsSync(values) {\n return values.map(asPosition);\n }\n function asRange(value) {\n if (value === undefined || value === null) {\n return value;\n }\n return { start: asPosition(value.start), end: asPosition(value.end) };\n }\n function asRanges(values) {\n return values.map(asRange);\n }\n function asLocation(value) {\n if (value === undefined || value === null) {\n return value;\n }\n return proto.Location.create(asUri(value.uri), asRange(value.range));\n }\n function asDiagnosticSeverity(value) {\n switch (value) {\n case code.DiagnosticSeverity.Error:\n return proto.DiagnosticSeverity.Error;\n case code.DiagnosticSeverity.Warning:\n return proto.DiagnosticSeverity.Warning;\n case code.DiagnosticSeverity.Information:\n return proto.DiagnosticSeverity.Information;\n case code.DiagnosticSeverity.Hint:\n return proto.DiagnosticSeverity.Hint;\n }\n }\n function asDiagnosticTags(tags) {\n if (!tags) {\n return undefined;\n }\n let result = [];\n for (let tag of tags) {\n let converted = asDiagnosticTag(tag);\n if (converted !== undefined) {\n result.push(converted);\n }\n }\n return result.length > 0 ? result : undefined;\n }\n function asDiagnosticTag(tag) {\n switch (tag) {\n case code.DiagnosticTag.Unnecessary:\n return proto.DiagnosticTag.Unnecessary;\n case code.DiagnosticTag.Deprecated:\n return proto.DiagnosticTag.Deprecated;\n default:\n return undefined;\n }\n }\n function asRelatedInformation(item) {\n return {\n message: item.message,\n location: asLocation(item.location)\n };\n }\n function asRelatedInformations(items) {\n return items.map(asRelatedInformation);\n }\n function asDiagnosticCode(value) {\n if (value === undefined || value === null) {\n return undefined;\n }\n if (Is.number(value) || Is.string(value)) {\n return value;\n }\n return { value: value.value, target: asUri(value.target) };\n }\n function asDiagnostic(item) {\n const result = proto.Diagnostic.create(asRange(item.range), item.message);\n const protocolDiagnostic = item instanceof protocolDiagnostic_1.ProtocolDiagnostic ? item : undefined;\n if (protocolDiagnostic !== undefined && protocolDiagnostic.data !== undefined) {\n result.data = protocolDiagnostic.data;\n }\n const code = asDiagnosticCode(item.code);\n if (protocolDiagnostic_1.DiagnosticCode.is(code)) {\n if (protocolDiagnostic !== undefined && protocolDiagnostic.hasDiagnosticCode) {\n result.code = code;\n }\n else {\n result.code = code.value;\n result.codeDescription = { href: code.target };\n }\n }\n else {\n result.code = code;\n }\n if (Is.number(item.severity)) {\n result.severity = asDiagnosticSeverity(item.severity);\n }\n if (Array.isArray(item.tags)) {\n result.tags = asDiagnosticTags(item.tags);\n }\n if (item.relatedInformation) {\n result.relatedInformation = asRelatedInformations(item.relatedInformation);\n }\n if (item.source) {\n result.source = item.source;\n }\n return result;\n }\n function asDiagnostics(items, token) {\n if (items === undefined || items === null) {\n return items;\n }\n return async.map(items, asDiagnostic, token);\n }\n function asDiagnosticsSync(items) {\n if (items === undefined || items === null) {\n return items;\n }\n return items.map(asDiagnostic);\n }\n function asDocumentation(format, documentation) {\n switch (format) {\n case '$string':\n return documentation;\n case proto.MarkupKind.PlainText:\n return { kind: format, value: documentation };\n case proto.MarkupKind.Markdown:\n return { kind: format, value: documentation.value };\n default:\n return `Unsupported Markup content received. Kind is: ${format}`;\n }\n }\n function asCompletionItemTag(tag) {\n switch (tag) {\n case code.CompletionItemTag.Deprecated:\n return proto.CompletionItemTag.Deprecated;\n }\n return undefined;\n }\n function asCompletionItemTags(tags) {\n if (tags === undefined) {\n return tags;\n }\n const result = [];\n for (let tag of tags) {\n const converted = asCompletionItemTag(tag);\n if (converted !== undefined) {\n result.push(converted);\n }\n }\n return result;\n }\n function asCompletionItemKind(value, original) {\n if (original !== undefined) {\n return original;\n }\n return value + 1;\n }\n function asCompletionItem(item, labelDetailsSupport = false) {\n let label;\n let labelDetails;\n if (Is.string(item.label)) {\n label = item.label;\n }\n else {\n label = item.label.label;\n if (labelDetailsSupport && (item.label.detail !== undefined || item.label.description !== undefined)) {\n labelDetails = { detail: item.label.detail, description: item.label.description };\n }\n }\n let result = { label: label };\n if (labelDetails !== undefined) {\n result.labelDetails = labelDetails;\n }\n let protocolItem = item instanceof protocolCompletionItem_1.default ? item : undefined;\n if (item.detail) {\n result.detail = item.detail;\n }\n // We only send items back we created. So this can't be something else than\n // a string right now.\n if (item.documentation) {\n if (!protocolItem || protocolItem.documentationFormat === '$string') {\n result.documentation = item.documentation;\n }\n else {\n result.documentation = asDocumentation(protocolItem.documentationFormat, item.documentation);\n }\n }\n if (item.filterText) {\n result.filterText = item.filterText;\n }\n fillPrimaryInsertText(result, item);\n if (Is.number(item.kind)) {\n result.kind = asCompletionItemKind(item.kind, protocolItem && protocolItem.originalItemKind);\n }\n if (item.sortText) {\n result.sortText = item.sortText;\n }\n if (item.additionalTextEdits) {\n result.additionalTextEdits = asTextEdits(item.additionalTextEdits);\n }\n if (item.commitCharacters) {\n result.commitCharacters = item.commitCharacters.slice();\n }\n if (item.command) {\n result.command = asCommand(item.command);\n }\n if (item.preselect === true || item.preselect === false) {\n result.preselect = item.preselect;\n }\n const tags = asCompletionItemTags(item.tags);\n if (protocolItem) {\n if (protocolItem.data !== undefined) {\n result.data = protocolItem.data;\n }\n if (protocolItem.deprecated === true || protocolItem.deprecated === false) {\n if (protocolItem.deprecated === true && tags !== undefined && tags.length > 0) {\n const index = tags.indexOf(code.CompletionItemTag.Deprecated);\n if (index !== -1) {\n tags.splice(index, 1);\n }\n }\n result.deprecated = protocolItem.deprecated;\n }\n if (protocolItem.insertTextMode !== undefined) {\n result.insertTextMode = protocolItem.insertTextMode;\n }\n }\n if (tags !== undefined && tags.length > 0) {\n result.tags = tags;\n }\n if (result.insertTextMode === undefined && item.keepWhitespace === true) {\n result.insertTextMode = proto.InsertTextMode.adjustIndentation;\n }\n return result;\n }\n function fillPrimaryInsertText(target, source) {\n let format = proto.InsertTextFormat.PlainText;\n let text = undefined;\n let range = undefined;\n if (source.textEdit) {\n text = source.textEdit.newText;\n range = source.textEdit.range;\n }\n else if (source.insertText instanceof code.SnippetString) {\n format = proto.InsertTextFormat.Snippet;\n text = source.insertText.value;\n }\n else {\n text = source.insertText;\n }\n if (source.range) {\n range = source.range;\n }\n target.insertTextFormat = format;\n if (source.fromEdit && text !== undefined && range !== undefined) {\n target.textEdit = asCompletionTextEdit(text, range);\n }\n else {\n target.insertText = text;\n }\n }\n function asCompletionTextEdit(newText, range) {\n if (InsertReplaceRange.is(range)) {\n return proto.InsertReplaceEdit.create(newText, asRange(range.inserting), asRange(range.replacing));\n }\n else {\n return { newText, range: asRange(range) };\n }\n }\n function asTextEdit(edit) {\n return { range: asRange(edit.range), newText: edit.newText };\n }\n function asTextEdits(edits) {\n if (edits === undefined || edits === null) {\n return edits;\n }\n return edits.map(asTextEdit);\n }\n function asSymbolKind(item) {\n if (item <= code.SymbolKind.TypeParameter) {\n // Symbol kind is one based in the protocol and zero based in code.\n return (item + 1);\n }\n return proto.SymbolKind.Property;\n }\n function asSymbolTag(item) {\n return item;\n }\n function asSymbolTags(items) {\n return items.map(asSymbolTag);\n }\n function asReferenceParams(textDocument, position, options) {\n return {\n textDocument: asTextDocumentIdentifier(textDocument),\n position: asWorkerPosition(position),\n context: { includeDeclaration: options.includeDeclaration }\n };\n }\n async function asCodeAction(item, token) {\n let result = proto.CodeAction.create(item.title);\n if (item instanceof protocolCodeAction_1.default && item.data !== undefined) {\n result.data = item.data;\n }\n if (item.kind !== undefined) {\n result.kind = asCodeActionKind(item.kind);\n }\n if (item.diagnostics !== undefined) {\n result.diagnostics = await asDiagnostics(item.diagnostics, token);\n }\n if (item.edit !== undefined) {\n throw new Error(`VS Code code actions can only be converted to a protocol code action without an edit.`);\n }\n if (item.command !== undefined) {\n result.command = asCommand(item.command);\n }\n if (item.isPreferred !== undefined) {\n result.isPreferred = item.isPreferred;\n }\n if (item.disabled !== undefined) {\n result.disabled = { reason: item.disabled.reason };\n }\n return result;\n }\n function asCodeActionSync(item) {\n let result = proto.CodeAction.create(item.title);\n if (item instanceof protocolCodeAction_1.default && item.data !== undefined) {\n result.data = item.data;\n }\n if (item.kind !== undefined) {\n result.kind = asCodeActionKind(item.kind);\n }\n if (item.diagnostics !== undefined) {\n result.diagnostics = asDiagnosticsSync(item.diagnostics);\n }\n if (item.edit !== undefined) {\n throw new Error(`VS Code code actions can only be converted to a protocol code action without an edit.`);\n }\n if (item.command !== undefined) {\n result.command = asCommand(item.command);\n }\n if (item.isPreferred !== undefined) {\n result.isPreferred = item.isPreferred;\n }\n if (item.disabled !== undefined) {\n result.disabled = { reason: item.disabled.reason };\n }\n return result;\n }\n async function asCodeActionContext(context, token) {\n if (context === undefined || context === null) {\n return context;\n }\n let only;\n if (context.only && Is.string(context.only.value)) {\n only = [context.only.value];\n }\n return proto.CodeActionContext.create(await asDiagnostics(context.diagnostics, token), only, asCodeActionTriggerKind(context.triggerKind));\n }\n function asCodeActionContextSync(context) {\n if (context === undefined || context === null) {\n return context;\n }\n let only;\n if (context.only && Is.string(context.only.value)) {\n only = [context.only.value];\n }\n return proto.CodeActionContext.create(asDiagnosticsSync(context.diagnostics), only, asCodeActionTriggerKind(context.triggerKind));\n }\n function asCodeActionTriggerKind(kind) {\n switch (kind) {\n case code.CodeActionTriggerKind.Invoke:\n return proto.CodeActionTriggerKind.Invoked;\n case code.CodeActionTriggerKind.Automatic:\n return proto.CodeActionTriggerKind.Automatic;\n default:\n return undefined;\n }\n }\n function asCodeActionKind(item) {\n if (item === undefined || item === null) {\n return undefined;\n }\n return item.value;\n }\n function asInlineValueContext(context) {\n if (context === undefined || context === null) {\n return context;\n }\n return proto.InlineValueContext.create(context.frameId, asRange(context.stoppedLocation));\n }\n function asInlineCompletionParams(document, position, context) {\n return { context: proto.InlineCompletionContext.create(context.triggerKind, context.selectedCompletionInfo),\n textDocument: asTextDocumentIdentifier(document), position: asPosition(position) };\n }\n function asCommand(item) {\n let result = proto.Command.create(item.title, item.command);\n if (item.arguments) {\n result.arguments = item.arguments;\n }\n return result;\n }\n function asCodeLens(item) {\n let result = proto.CodeLens.create(asRange(item.range));\n if (item.command) {\n result.command = asCommand(item.command);\n }\n if (item instanceof protocolCodeLens_1.default) {\n if (item.data) {\n result.data = item.data;\n }\n }\n return result;\n }\n function asFormattingOptions(options, fileOptions) {\n const result = { tabSize: options.tabSize, insertSpaces: options.insertSpaces };\n if (fileOptions.trimTrailingWhitespace) {\n result.trimTrailingWhitespace = true;\n }\n if (fileOptions.trimFinalNewlines) {\n result.trimFinalNewlines = true;\n }\n if (fileOptions.insertFinalNewline) {\n result.insertFinalNewline = true;\n }\n return result;\n }\n function asDocumentSymbolParams(textDocument) {\n return {\n textDocument: asTextDocumentIdentifier(textDocument)\n };\n }\n function asCodeLensParams(textDocument) {\n return {\n textDocument: asTextDocumentIdentifier(textDocument)\n };\n }\n function asDocumentLink(item) {\n let result = proto.DocumentLink.create(asRange(item.range));\n if (item.target) {\n result.target = asUri(item.target);\n }\n if (item.tooltip !== undefined) {\n result.tooltip = item.tooltip;\n }\n let protocolItem = item instanceof protocolDocumentLink_1.default ? item : undefined;\n if (protocolItem && protocolItem.data) {\n result.data = protocolItem.data;\n }\n return result;\n }\n function asDocumentLinkParams(textDocument) {\n return {\n textDocument: asTextDocumentIdentifier(textDocument)\n };\n }\n function asCallHierarchyItem(value) {\n const result = {\n name: value.name,\n kind: asSymbolKind(value.kind),\n uri: asUri(value.uri),\n range: asRange(value.range),\n selectionRange: asRange(value.selectionRange)\n };\n if (value.detail !== undefined && value.detail.length > 0) {\n result.detail = value.detail;\n }\n if (value.tags !== undefined) {\n result.tags = asSymbolTags(value.tags);\n }\n if (value instanceof protocolCallHierarchyItem_1.default && value.data !== undefined) {\n result.data = value.data;\n }\n return result;\n }\n function asTypeHierarchyItem(value) {\n const result = {\n name: value.name,\n kind: asSymbolKind(value.kind),\n uri: asUri(value.uri),\n range: asRange(value.range),\n selectionRange: asRange(value.selectionRange),\n };\n if (value.detail !== undefined && value.detail.length > 0) {\n result.detail = value.detail;\n }\n if (value.tags !== undefined) {\n result.tags = asSymbolTags(value.tags);\n }\n if (value instanceof protocolTypeHierarchyItem_1.default && value.data !== undefined) {\n result.data = value.data;\n }\n return result;\n }\n function asWorkspaceSymbol(item) {\n const result = item instanceof protocolWorkspaceSymbol_1.default\n ? { name: item.name, kind: asSymbolKind(item.kind), location: item.hasRange ? asLocation(item.location) : { uri: _uriConverter(item.location.uri) }, data: item.data }\n : { name: item.name, kind: asSymbolKind(item.kind), location: asLocation(item.location) };\n if (item.tags !== undefined) {\n result.tags = asSymbolTags(item.tags);\n }\n if (item.containerName !== '') {\n result.containerName = item.containerName;\n }\n return result;\n }\n function asInlayHint(item) {\n const label = typeof item.label === 'string'\n ? item.label\n : item.label.map(asInlayHintLabelPart);\n const result = proto.InlayHint.create(asPosition(item.position), label);\n if (item.kind !== undefined) {\n result.kind = item.kind;\n }\n if (item.textEdits !== undefined) {\n result.textEdits = asTextEdits(item.textEdits);\n }\n if (item.tooltip !== undefined) {\n result.tooltip = asTooltip(item.tooltip);\n }\n if (item.paddingLeft !== undefined) {\n result.paddingLeft = item.paddingLeft;\n }\n if (item.paddingRight !== undefined) {\n result.paddingRight = item.paddingRight;\n }\n if (item instanceof protocolInlayHint_1.default && item.data !== undefined) {\n result.data = item.data;\n }\n return result;\n }\n function asInlayHintLabelPart(item) {\n const result = proto.InlayHintLabelPart.create(item.value);\n if (item.location !== undefined) {\n result.location = asLocation(item.location);\n }\n if (item.command !== undefined) {\n result.command = asCommand(item.command);\n }\n if (item.tooltip !== undefined) {\n result.tooltip = asTooltip(item.tooltip);\n }\n return result;\n }\n function asTooltip(value) {\n if (typeof value === 'string') {\n return value;\n }\n const result = {\n kind: proto.MarkupKind.Markdown,\n value: value.value\n };\n return result;\n }\n return {\n asUri,\n asTextDocumentIdentifier,\n asTextDocumentItem,\n asVersionedTextDocumentIdentifier,\n asOpenTextDocumentParams,\n asChangeTextDocumentParams,\n asCloseTextDocumentParams,\n asSaveTextDocumentParams,\n asWillSaveTextDocumentParams,\n asDidCreateFilesParams,\n asDidRenameFilesParams,\n asDidDeleteFilesParams,\n asWillCreateFilesParams,\n asWillRenameFilesParams,\n asWillDeleteFilesParams,\n asTextDocumentPositionParams,\n asCompletionParams,\n asSignatureHelpParams,\n asWorkerPosition,\n asRange,\n asRanges,\n asPosition,\n asPositions,\n asPositionsSync,\n asLocation,\n asDiagnosticSeverity,\n asDiagnosticTag,\n asDiagnostic,\n asDiagnostics,\n asDiagnosticsSync,\n asCompletionItem,\n asTextEdit,\n asSymbolKind,\n asSymbolTag,\n asSymbolTags,\n asReferenceParams,\n asCodeAction,\n asCodeActionSync,\n asCodeActionContext,\n asCodeActionContextSync,\n asInlineValueContext,\n asCommand,\n asCodeLens,\n asFormattingOptions,\n asDocumentSymbolParams,\n asCodeLensParams,\n asDocumentLink,\n asDocumentLinkParams,\n asCallHierarchyItem,\n asTypeHierarchyItem,\n asInlayHint,\n asWorkspaceSymbol,\n asInlineCompletionParams\n };\n}\nexports.createConverter = createConverter;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createConverter = void 0;\nconst code = require(\"vscode\");\nconst ls = require(\"vscode-languageserver-protocol\");\nconst Is = require(\"./utils/is\");\nconst async = require(\"./utils/async\");\nconst protocolCompletionItem_1 = require(\"./protocolCompletionItem\");\nconst protocolCodeLens_1 = require(\"./protocolCodeLens\");\nconst protocolDocumentLink_1 = require(\"./protocolDocumentLink\");\nconst protocolCodeAction_1 = require(\"./protocolCodeAction\");\nconst protocolDiagnostic_1 = require(\"./protocolDiagnostic\");\nconst protocolCallHierarchyItem_1 = require(\"./protocolCallHierarchyItem\");\nconst protocolTypeHierarchyItem_1 = require(\"./protocolTypeHierarchyItem\");\nconst protocolWorkspaceSymbol_1 = require(\"./protocolWorkspaceSymbol\");\nconst protocolInlayHint_1 = require(\"./protocolInlayHint\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nvar CodeBlock;\n(function (CodeBlock) {\n function is(value) {\n let candidate = value;\n return candidate && Is.string(candidate.language) && Is.string(candidate.value);\n }\n CodeBlock.is = is;\n})(CodeBlock || (CodeBlock = {}));\nfunction createConverter(uriConverter, trustMarkdown, supportHtml) {\n const nullConverter = (value) => code.Uri.parse(value);\n const _uriConverter = uriConverter || nullConverter;\n function asUri(value) {\n return _uriConverter(value);\n }\n function asDocumentSelector(selector) {\n const result = [];\n for (const filter of selector) {\n if (typeof filter === 'string') {\n result.push(filter);\n }\n else if (vscode_languageserver_protocol_1.NotebookCellTextDocumentFilter.is(filter)) {\n // We first need to check for the notebook cell filter since a TextDocumentFilter would\n // match both (e.g. the notebook is optional).\n if (typeof filter.notebook === 'string') {\n result.push({ notebookType: filter.notebook, language: filter.language });\n }\n else {\n const notebookType = filter.notebook.notebookType ?? '*';\n result.push({ notebookType: notebookType, scheme: filter.notebook.scheme, pattern: filter.notebook.pattern, language: filter.language });\n }\n }\n else if (vscode_languageserver_protocol_1.TextDocumentFilter.is(filter)) {\n result.push({ language: filter.language, scheme: filter.scheme, pattern: filter.pattern });\n }\n }\n return result;\n }\n async function asDiagnostics(diagnostics, token) {\n return async.map(diagnostics, asDiagnostic, token);\n }\n function asDiagnosticsSync(diagnostics) {\n const result = new Array(diagnostics.length);\n for (let i = 0; i < diagnostics.length; i++) {\n result[i] = asDiagnostic(diagnostics[i]);\n }\n return result;\n }\n function asDiagnostic(diagnostic) {\n let result = new protocolDiagnostic_1.ProtocolDiagnostic(asRange(diagnostic.range), diagnostic.message, asDiagnosticSeverity(diagnostic.severity), diagnostic.data);\n if (diagnostic.code !== undefined) {\n if (typeof diagnostic.code === 'string' || typeof diagnostic.code === 'number') {\n if (ls.CodeDescription.is(diagnostic.codeDescription)) {\n result.code = {\n value: diagnostic.code,\n target: asUri(diagnostic.codeDescription.href)\n };\n }\n else {\n result.code = diagnostic.code;\n }\n }\n else if (protocolDiagnostic_1.DiagnosticCode.is(diagnostic.code)) {\n // This is for backwards compatibility of a proposed API.\n // We should remove this at some point.\n result.hasDiagnosticCode = true;\n const diagnosticCode = diagnostic.code;\n result.code = {\n value: diagnosticCode.value,\n target: asUri(diagnosticCode.target)\n };\n }\n }\n if (diagnostic.source) {\n result.source = diagnostic.source;\n }\n if (diagnostic.relatedInformation) {\n result.relatedInformation = asRelatedInformation(diagnostic.relatedInformation);\n }\n if (Array.isArray(diagnostic.tags)) {\n result.tags = asDiagnosticTags(diagnostic.tags);\n }\n return result;\n }\n function asRelatedInformation(relatedInformation) {\n const result = new Array(relatedInformation.length);\n for (let i = 0; i < relatedInformation.length; i++) {\n const info = relatedInformation[i];\n result[i] = new code.DiagnosticRelatedInformation(asLocation(info.location), info.message);\n }\n return result;\n }\n function asDiagnosticTags(tags) {\n if (!tags) {\n return undefined;\n }\n let result = [];\n for (let tag of tags) {\n let converted = asDiagnosticTag(tag);\n if (converted !== undefined) {\n result.push(converted);\n }\n }\n return result.length > 0 ? result : undefined;\n }\n function asDiagnosticTag(tag) {\n switch (tag) {\n case ls.DiagnosticTag.Unnecessary:\n return code.DiagnosticTag.Unnecessary;\n case ls.DiagnosticTag.Deprecated:\n return code.DiagnosticTag.Deprecated;\n default:\n return undefined;\n }\n }\n function asPosition(value) {\n return value ? new code.Position(value.line, value.character) : undefined;\n }\n function asRange(value) {\n return value ? new code.Range(value.start.line, value.start.character, value.end.line, value.end.character) : undefined;\n }\n async function asRanges(items, token) {\n return async.map(items, (range) => {\n return new code.Range(range.start.line, range.start.character, range.end.line, range.end.character);\n }, token);\n }\n function asDiagnosticSeverity(value) {\n if (value === undefined || value === null) {\n return code.DiagnosticSeverity.Error;\n }\n switch (value) {\n case ls.DiagnosticSeverity.Error:\n return code.DiagnosticSeverity.Error;\n case ls.DiagnosticSeverity.Warning:\n return code.DiagnosticSeverity.Warning;\n case ls.DiagnosticSeverity.Information:\n return code.DiagnosticSeverity.Information;\n case ls.DiagnosticSeverity.Hint:\n return code.DiagnosticSeverity.Hint;\n }\n return code.DiagnosticSeverity.Error;\n }\n function asHoverContent(value) {\n if (Is.string(value)) {\n return asMarkdownString(value);\n }\n else if (CodeBlock.is(value)) {\n let result = asMarkdownString();\n return result.appendCodeblock(value.value, value.language);\n }\n else if (Array.isArray(value)) {\n let result = [];\n for (let element of value) {\n let item = asMarkdownString();\n if (CodeBlock.is(element)) {\n item.appendCodeblock(element.value, element.language);\n }\n else {\n item.appendMarkdown(element);\n }\n result.push(item);\n }\n return result;\n }\n else {\n return asMarkdownString(value);\n }\n }\n function asDocumentation(value) {\n if (Is.string(value)) {\n return value;\n }\n else {\n switch (value.kind) {\n case ls.MarkupKind.Markdown:\n return asMarkdownString(value.value);\n case ls.MarkupKind.PlainText:\n return value.value;\n default:\n return `Unsupported Markup content received. Kind is: ${value.kind}`;\n }\n }\n }\n function asMarkdownString(value) {\n let result;\n if (value === undefined || typeof value === 'string') {\n result = new code.MarkdownString(value);\n }\n else {\n switch (value.kind) {\n case ls.MarkupKind.Markdown:\n result = new code.MarkdownString(value.value);\n break;\n case ls.MarkupKind.PlainText:\n result = new code.MarkdownString();\n result.appendText(value.value);\n break;\n default:\n result = new code.MarkdownString();\n result.appendText(`Unsupported Markup content received. Kind is: ${value.kind}`);\n break;\n }\n }\n result.isTrusted = trustMarkdown;\n result.supportHtml = supportHtml;\n return result;\n }\n function asHover(hover) {\n if (!hover) {\n return undefined;\n }\n return new code.Hover(asHoverContent(hover.contents), asRange(hover.range));\n }\n async function asCompletionResult(value, allCommitCharacters, token) {\n if (!value) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return async.map(value, (item) => asCompletionItem(item, allCommitCharacters), token);\n }\n const list = value;\n const { defaultRange, commitCharacters } = getCompletionItemDefaults(list, allCommitCharacters);\n const converted = await async.map(list.items, (item) => {\n return asCompletionItem(item, commitCharacters, defaultRange, list.itemDefaults?.insertTextMode, list.itemDefaults?.insertTextFormat, list.itemDefaults?.data);\n }, token);\n return new code.CompletionList(converted, list.isIncomplete);\n }\n function getCompletionItemDefaults(list, allCommitCharacters) {\n const rangeDefaults = list.itemDefaults?.editRange;\n const commitCharacters = list.itemDefaults?.commitCharacters ?? allCommitCharacters;\n return ls.Range.is(rangeDefaults)\n ? { defaultRange: asRange(rangeDefaults), commitCharacters }\n : rangeDefaults !== undefined\n ? { defaultRange: { inserting: asRange(rangeDefaults.insert), replacing: asRange(rangeDefaults.replace) }, commitCharacters }\n : { defaultRange: undefined, commitCharacters };\n }\n function asCompletionItemKind(value) {\n // Protocol item kind is 1 based, codes item kind is zero based.\n if (ls.CompletionItemKind.Text <= value && value <= ls.CompletionItemKind.TypeParameter) {\n return [value - 1, undefined];\n }\n return [code.CompletionItemKind.Text, value];\n }\n function asCompletionItemTag(tag) {\n switch (tag) {\n case ls.CompletionItemTag.Deprecated:\n return code.CompletionItemTag.Deprecated;\n }\n return undefined;\n }\n function asCompletionItemTags(tags) {\n if (tags === undefined || tags === null) {\n return [];\n }\n const result = [];\n for (const tag of tags) {\n const converted = asCompletionItemTag(tag);\n if (converted !== undefined) {\n result.push(converted);\n }\n }\n return result;\n }\n function asCompletionItem(item, defaultCommitCharacters, defaultRange, defaultInsertTextMode, defaultInsertTextFormat, defaultData) {\n const tags = asCompletionItemTags(item.tags);\n const label = asCompletionItemLabel(item);\n const result = new protocolCompletionItem_1.default(label);\n if (item.detail) {\n result.detail = item.detail;\n }\n if (item.documentation) {\n result.documentation = asDocumentation(item.documentation);\n result.documentationFormat = Is.string(item.documentation) ? '$string' : item.documentation.kind;\n }\n if (item.filterText) {\n result.filterText = item.filterText;\n }\n const insertText = asCompletionInsertText(item, defaultRange, defaultInsertTextFormat);\n if (insertText) {\n result.insertText = insertText.text;\n result.range = insertText.range;\n result.fromEdit = insertText.fromEdit;\n }\n if (Is.number(item.kind)) {\n let [itemKind, original] = asCompletionItemKind(item.kind);\n result.kind = itemKind;\n if (original) {\n result.originalItemKind = original;\n }\n }\n if (item.sortText) {\n result.sortText = item.sortText;\n }\n if (item.additionalTextEdits) {\n result.additionalTextEdits = asTextEditsSync(item.additionalTextEdits);\n }\n const commitCharacters = item.commitCharacters !== undefined\n ? Is.stringArray(item.commitCharacters) ? item.commitCharacters : undefined\n : defaultCommitCharacters;\n if (commitCharacters) {\n result.commitCharacters = commitCharacters.slice();\n }\n if (item.command) {\n result.command = asCommand(item.command);\n }\n if (item.deprecated === true || item.deprecated === false) {\n result.deprecated = item.deprecated;\n if (item.deprecated === true) {\n tags.push(code.CompletionItemTag.Deprecated);\n }\n }\n if (item.preselect === true || item.preselect === false) {\n result.preselect = item.preselect;\n }\n const data = item.data ?? defaultData;\n if (data !== undefined) {\n result.data = data;\n }\n if (tags.length > 0) {\n result.tags = tags;\n }\n const insertTextMode = item.insertTextMode ?? defaultInsertTextMode;\n if (insertTextMode !== undefined) {\n result.insertTextMode = insertTextMode;\n if (insertTextMode === ls.InsertTextMode.asIs) {\n result.keepWhitespace = true;\n }\n }\n return result;\n }\n function asCompletionItemLabel(item) {\n if (ls.CompletionItemLabelDetails.is(item.labelDetails)) {\n return {\n label: item.label,\n detail: item.labelDetails.detail,\n description: item.labelDetails.description\n };\n }\n else {\n return item.label;\n }\n }\n function asCompletionInsertText(item, defaultRange, defaultInsertTextFormat) {\n const insertTextFormat = item.insertTextFormat ?? defaultInsertTextFormat;\n if (item.textEdit !== undefined || defaultRange !== undefined) {\n const [range, newText] = item.textEdit !== undefined\n ? getCompletionRangeAndText(item.textEdit)\n : [defaultRange, item.textEditText ?? item.label];\n if (insertTextFormat === ls.InsertTextFormat.Snippet) {\n return { text: new code.SnippetString(newText), range: range, fromEdit: true };\n }\n else {\n return { text: newText, range: range, fromEdit: true };\n }\n }\n else if (item.insertText) {\n if (insertTextFormat === ls.InsertTextFormat.Snippet) {\n return { text: new code.SnippetString(item.insertText), fromEdit: false };\n }\n else {\n return { text: item.insertText, fromEdit: false };\n }\n }\n else {\n return undefined;\n }\n }\n function getCompletionRangeAndText(value) {\n if (ls.InsertReplaceEdit.is(value)) {\n return [{ inserting: asRange(value.insert), replacing: asRange(value.replace) }, value.newText];\n }\n else {\n return [asRange(value.range), value.newText];\n }\n }\n function asTextEdit(edit) {\n if (!edit) {\n return undefined;\n }\n return new code.TextEdit(asRange(edit.range), edit.newText);\n }\n async function asTextEdits(items, token) {\n if (!items) {\n return undefined;\n }\n return async.map(items, asTextEdit, token);\n }\n function asTextEditsSync(items) {\n if (!items) {\n return undefined;\n }\n const result = new Array(items.length);\n for (let i = 0; i < items.length; i++) {\n result[i] = asTextEdit(items[i]);\n }\n return result;\n }\n async function asSignatureHelp(item, token) {\n if (!item) {\n return undefined;\n }\n let result = new code.SignatureHelp();\n if (Is.number(item.activeSignature)) {\n result.activeSignature = item.activeSignature;\n }\n else {\n // activeSignature was optional in the past\n result.activeSignature = 0;\n }\n if (Is.number(item.activeParameter)) {\n result.activeParameter = item.activeParameter;\n }\n else {\n // activeParameter was optional in the past\n result.activeParameter = 0;\n }\n if (item.signatures) {\n result.signatures = await asSignatureInformations(item.signatures, token);\n }\n return result;\n }\n async function asSignatureInformations(items, token) {\n return async.mapAsync(items, asSignatureInformation, token);\n }\n async function asSignatureInformation(item, token) {\n let result = new code.SignatureInformation(item.label);\n if (item.documentation !== undefined) {\n result.documentation = asDocumentation(item.documentation);\n }\n if (item.parameters !== undefined) {\n result.parameters = await asParameterInformations(item.parameters, token);\n }\n if (item.activeParameter !== undefined) {\n result.activeParameter = item.activeParameter;\n }\n {\n return result;\n }\n }\n function asParameterInformations(items, token) {\n return async.map(items, asParameterInformation, token);\n }\n function asParameterInformation(item) {\n let result = new code.ParameterInformation(item.label);\n if (item.documentation) {\n result.documentation = asDocumentation(item.documentation);\n }\n return result;\n }\n function asLocation(item) {\n return item ? new code.Location(_uriConverter(item.uri), asRange(item.range)) : undefined;\n }\n async function asDeclarationResult(item, token) {\n if (!item) {\n return undefined;\n }\n return asLocationResult(item, token);\n }\n async function asDefinitionResult(item, token) {\n if (!item) {\n return undefined;\n }\n return asLocationResult(item, token);\n }\n function asLocationLink(item) {\n if (!item) {\n return undefined;\n }\n let result = {\n targetUri: _uriConverter(item.targetUri),\n targetRange: asRange(item.targetRange),\n originSelectionRange: asRange(item.originSelectionRange),\n targetSelectionRange: asRange(item.targetSelectionRange)\n };\n if (!result.targetSelectionRange) {\n throw new Error(`targetSelectionRange must not be undefined or null`);\n }\n return result;\n }\n async function asLocationResult(item, token) {\n if (!item) {\n return undefined;\n }\n if (Is.array(item)) {\n if (item.length === 0) {\n return [];\n }\n else if (ls.LocationLink.is(item[0])) {\n const links = item;\n return async.map(links, asLocationLink, token);\n }\n else {\n const locations = item;\n return async.map(locations, asLocation, token);\n }\n }\n else if (ls.LocationLink.is(item)) {\n return [asLocationLink(item)];\n }\n else {\n return asLocation(item);\n }\n }\n async function asReferences(values, token) {\n if (!values) {\n return undefined;\n }\n return async.map(values, asLocation, token);\n }\n async function asDocumentHighlights(values, token) {\n if (!values) {\n return undefined;\n }\n return async.map(values, asDocumentHighlight, token);\n }\n function asDocumentHighlight(item) {\n let result = new code.DocumentHighlight(asRange(item.range));\n if (Is.number(item.kind)) {\n result.kind = asDocumentHighlightKind(item.kind);\n }\n return result;\n }\n function asDocumentHighlightKind(item) {\n switch (item) {\n case ls.DocumentHighlightKind.Text:\n return code.DocumentHighlightKind.Text;\n case ls.DocumentHighlightKind.Read:\n return code.DocumentHighlightKind.Read;\n case ls.DocumentHighlightKind.Write:\n return code.DocumentHighlightKind.Write;\n }\n return code.DocumentHighlightKind.Text;\n }\n async function asSymbolInformations(values, token) {\n if (!values) {\n return undefined;\n }\n return async.map(values, asSymbolInformation, token);\n }\n function asSymbolKind(item) {\n if (item <= ls.SymbolKind.TypeParameter) {\n // Symbol kind is one based in the protocol and zero based in code.\n return item - 1;\n }\n return code.SymbolKind.Property;\n }\n function asSymbolTag(value) {\n switch (value) {\n case ls.SymbolTag.Deprecated:\n return code.SymbolTag.Deprecated;\n default:\n return undefined;\n }\n }\n function asSymbolTags(items) {\n if (items === undefined || items === null) {\n return undefined;\n }\n const result = [];\n for (const item of items) {\n const converted = asSymbolTag(item);\n if (converted !== undefined) {\n result.push(converted);\n }\n }\n return result.length === 0 ? undefined : result;\n }\n function asSymbolInformation(item) {\n const data = item.data;\n const location = item.location;\n const result = location.range === undefined || data !== undefined\n ? new protocolWorkspaceSymbol_1.default(item.name, asSymbolKind(item.kind), item.containerName ?? '', location.range === undefined ? _uriConverter(location.uri) : new code.Location(_uriConverter(item.location.uri), asRange(location.range)), data)\n : new code.SymbolInformation(item.name, asSymbolKind(item.kind), item.containerName ?? '', new code.Location(_uriConverter(item.location.uri), asRange(location.range)));\n fillTags(result, item);\n return result;\n }\n async function asDocumentSymbols(values, token) {\n if (values === undefined || values === null) {\n return undefined;\n }\n return async.map(values, asDocumentSymbol, token);\n }\n function asDocumentSymbol(value) {\n let result = new code.DocumentSymbol(value.name, value.detail || '', asSymbolKind(value.kind), asRange(value.range), asRange(value.selectionRange));\n fillTags(result, value);\n if (value.children !== undefined && value.children.length > 0) {\n let children = [];\n for (let child of value.children) {\n children.push(asDocumentSymbol(child));\n }\n result.children = children;\n }\n return result;\n }\n function fillTags(result, value) {\n result.tags = asSymbolTags(value.tags);\n if (value.deprecated) {\n if (!result.tags) {\n result.tags = [code.SymbolTag.Deprecated];\n }\n else {\n if (!result.tags.includes(code.SymbolTag.Deprecated)) {\n result.tags = result.tags.concat(code.SymbolTag.Deprecated);\n }\n }\n }\n }\n function asCommand(item) {\n let result = { title: item.title, command: item.command };\n if (item.arguments) {\n result.arguments = item.arguments;\n }\n return result;\n }\n async function asCommands(items, token) {\n if (!items) {\n return undefined;\n }\n return async.map(items, asCommand, token);\n }\n const kindMapping = new Map();\n kindMapping.set(ls.CodeActionKind.Empty, code.CodeActionKind.Empty);\n kindMapping.set(ls.CodeActionKind.QuickFix, code.CodeActionKind.QuickFix);\n kindMapping.set(ls.CodeActionKind.Refactor, code.CodeActionKind.Refactor);\n kindMapping.set(ls.CodeActionKind.RefactorExtract, code.CodeActionKind.RefactorExtract);\n kindMapping.set(ls.CodeActionKind.RefactorInline, code.CodeActionKind.RefactorInline);\n kindMapping.set(ls.CodeActionKind.RefactorRewrite, code.CodeActionKind.RefactorRewrite);\n kindMapping.set(ls.CodeActionKind.Source, code.CodeActionKind.Source);\n kindMapping.set(ls.CodeActionKind.SourceOrganizeImports, code.CodeActionKind.SourceOrganizeImports);\n function asCodeActionKind(item) {\n if (item === undefined || item === null) {\n return undefined;\n }\n let result = kindMapping.get(item);\n if (result) {\n return result;\n }\n let parts = item.split('.');\n result = code.CodeActionKind.Empty;\n for (let part of parts) {\n result = result.append(part);\n }\n return result;\n }\n function asCodeActionKinds(items) {\n if (items === undefined || items === null) {\n return undefined;\n }\n return items.map(kind => asCodeActionKind(kind));\n }\n async function asCodeAction(item, token) {\n if (item === undefined || item === null) {\n return undefined;\n }\n let result = new protocolCodeAction_1.default(item.title, item.data);\n if (item.kind !== undefined) {\n result.kind = asCodeActionKind(item.kind);\n }\n if (item.diagnostics !== undefined) {\n result.diagnostics = asDiagnosticsSync(item.diagnostics);\n }\n if (item.edit !== undefined) {\n result.edit = await asWorkspaceEdit(item.edit, token);\n }\n if (item.command !== undefined) {\n result.command = asCommand(item.command);\n }\n if (item.isPreferred !== undefined) {\n result.isPreferred = item.isPreferred;\n }\n if (item.disabled !== undefined) {\n result.disabled = { reason: item.disabled.reason };\n }\n return result;\n }\n function asCodeActionResult(items, token) {\n return async.mapAsync(items, async (item) => {\n if (ls.Command.is(item)) {\n return asCommand(item);\n }\n else {\n return asCodeAction(item, token);\n }\n }, token);\n }\n function asCodeLens(item) {\n if (!item) {\n return undefined;\n }\n let result = new protocolCodeLens_1.default(asRange(item.range));\n if (item.command) {\n result.command = asCommand(item.command);\n }\n if (item.data !== undefined && item.data !== null) {\n result.data = item.data;\n }\n return result;\n }\n async function asCodeLenses(items, token) {\n if (!items) {\n return undefined;\n }\n return async.map(items, asCodeLens, token);\n }\n async function asWorkspaceEdit(item, token) {\n if (!item) {\n return undefined;\n }\n const sharedMetadata = new Map();\n if (item.changeAnnotations !== undefined) {\n const changeAnnotations = item.changeAnnotations;\n await async.forEach(Object.keys(changeAnnotations), (key) => {\n const metaData = asWorkspaceEditEntryMetadata(changeAnnotations[key]);\n sharedMetadata.set(key, metaData);\n }, token);\n }\n const asMetadata = (annotation) => {\n if (annotation === undefined) {\n return undefined;\n }\n else {\n return sharedMetadata.get(annotation);\n }\n };\n const result = new code.WorkspaceEdit();\n if (item.documentChanges) {\n const documentChanges = item.documentChanges;\n await async.forEach(documentChanges, (change) => {\n if (ls.CreateFile.is(change)) {\n result.createFile(_uriConverter(change.uri), change.options, asMetadata(change.annotationId));\n }\n else if (ls.RenameFile.is(change)) {\n result.renameFile(_uriConverter(change.oldUri), _uriConverter(change.newUri), change.options, asMetadata(change.annotationId));\n }\n else if (ls.DeleteFile.is(change)) {\n result.deleteFile(_uriConverter(change.uri), change.options, asMetadata(change.annotationId));\n }\n else if (ls.TextDocumentEdit.is(change)) {\n const uri = _uriConverter(change.textDocument.uri);\n for (const edit of change.edits) {\n if (ls.AnnotatedTextEdit.is(edit)) {\n result.replace(uri, asRange(edit.range), edit.newText, asMetadata(edit.annotationId));\n }\n else {\n result.replace(uri, asRange(edit.range), edit.newText);\n }\n }\n }\n else {\n throw new Error(`Unknown workspace edit change received:\\n${JSON.stringify(change, undefined, 4)}`);\n }\n }, token);\n }\n else if (item.changes) {\n const changes = item.changes;\n await async.forEach(Object.keys(changes), (key) => {\n result.set(_uriConverter(key), asTextEditsSync(changes[key]));\n }, token);\n }\n return result;\n }\n function asWorkspaceEditEntryMetadata(annotation) {\n if (annotation === undefined) {\n return undefined;\n }\n return { label: annotation.label, needsConfirmation: !!annotation.needsConfirmation, description: annotation.description };\n }\n function asDocumentLink(item) {\n let range = asRange(item.range);\n let target = item.target ? asUri(item.target) : undefined;\n // target must be optional in DocumentLink\n let link = new protocolDocumentLink_1.default(range, target);\n if (item.tooltip !== undefined) {\n link.tooltip = item.tooltip;\n }\n if (item.data !== undefined && item.data !== null) {\n link.data = item.data;\n }\n return link;\n }\n async function asDocumentLinks(items, token) {\n if (!items) {\n return undefined;\n }\n return async.map(items, asDocumentLink, token);\n }\n function asColor(color) {\n return new code.Color(color.red, color.green, color.blue, color.alpha);\n }\n function asColorInformation(ci) {\n return new code.ColorInformation(asRange(ci.range), asColor(ci.color));\n }\n async function asColorInformations(colorInformation, token) {\n if (!colorInformation) {\n return undefined;\n }\n return async.map(colorInformation, asColorInformation, token);\n }\n function asColorPresentation(cp) {\n let presentation = new code.ColorPresentation(cp.label);\n presentation.additionalTextEdits = asTextEditsSync(cp.additionalTextEdits);\n if (cp.textEdit) {\n presentation.textEdit = asTextEdit(cp.textEdit);\n }\n return presentation;\n }\n async function asColorPresentations(colorPresentations, token) {\n if (!colorPresentations) {\n return undefined;\n }\n return async.map(colorPresentations, asColorPresentation, token);\n }\n function asFoldingRangeKind(kind) {\n if (kind) {\n switch (kind) {\n case ls.FoldingRangeKind.Comment:\n return code.FoldingRangeKind.Comment;\n case ls.FoldingRangeKind.Imports:\n return code.FoldingRangeKind.Imports;\n case ls.FoldingRangeKind.Region:\n return code.FoldingRangeKind.Region;\n }\n }\n return undefined;\n }\n function asFoldingRange(r) {\n return new code.FoldingRange(r.startLine, r.endLine, asFoldingRangeKind(r.kind));\n }\n async function asFoldingRanges(foldingRanges, token) {\n if (!foldingRanges) {\n return undefined;\n }\n return async.map(foldingRanges, asFoldingRange, token);\n }\n function asSelectionRange(selectionRange) {\n return new code.SelectionRange(asRange(selectionRange.range), selectionRange.parent ? asSelectionRange(selectionRange.parent) : undefined);\n }\n async function asSelectionRanges(selectionRanges, token) {\n if (!Array.isArray(selectionRanges)) {\n return [];\n }\n return async.map(selectionRanges, asSelectionRange, token);\n }\n function asInlineValue(inlineValue) {\n if (ls.InlineValueText.is(inlineValue)) {\n return new code.InlineValueText(asRange(inlineValue.range), inlineValue.text);\n }\n else if (ls.InlineValueVariableLookup.is(inlineValue)) {\n return new code.InlineValueVariableLookup(asRange(inlineValue.range), inlineValue.variableName, inlineValue.caseSensitiveLookup);\n }\n else {\n return new code.InlineValueEvaluatableExpression(asRange(inlineValue.range), inlineValue.expression);\n }\n }\n async function asInlineValues(inlineValues, token) {\n if (!Array.isArray(inlineValues)) {\n return [];\n }\n return async.map(inlineValues, asInlineValue, token);\n }\n async function asInlayHint(value, token) {\n const label = typeof value.label === 'string'\n ? value.label\n : await async.map(value.label, asInlayHintLabelPart, token);\n const result = new protocolInlayHint_1.default(asPosition(value.position), label);\n if (value.kind !== undefined) {\n result.kind = value.kind;\n }\n if (value.textEdits !== undefined) {\n result.textEdits = await asTextEdits(value.textEdits, token);\n }\n if (value.tooltip !== undefined) {\n result.tooltip = asTooltip(value.tooltip);\n }\n if (value.paddingLeft !== undefined) {\n result.paddingLeft = value.paddingLeft;\n }\n if (value.paddingRight !== undefined) {\n result.paddingRight = value.paddingRight;\n }\n if (value.data !== undefined) {\n result.data = value.data;\n }\n return result;\n }\n function asInlayHintLabelPart(part) {\n const result = new code.InlayHintLabelPart(part.value);\n if (part.location !== undefined) {\n result.location = asLocation(part.location);\n }\n if (part.tooltip !== undefined) {\n result.tooltip = asTooltip(part.tooltip);\n }\n if (part.command !== undefined) {\n result.command = asCommand(part.command);\n }\n return result;\n }\n function asTooltip(value) {\n if (typeof value === 'string') {\n return value;\n }\n return asMarkdownString(value);\n }\n async function asInlayHints(values, token) {\n if (!Array.isArray(values)) {\n return undefined;\n }\n return async.mapAsync(values, asInlayHint, token);\n }\n function asCallHierarchyItem(item) {\n if (item === null) {\n return undefined;\n }\n const result = new protocolCallHierarchyItem_1.default(asSymbolKind(item.kind), item.name, item.detail || '', asUri(item.uri), asRange(item.range), asRange(item.selectionRange), item.data);\n if (item.tags !== undefined) {\n result.tags = asSymbolTags(item.tags);\n }\n return result;\n }\n async function asCallHierarchyItems(items, token) {\n if (items === null) {\n return undefined;\n }\n return async.map(items, asCallHierarchyItem, token);\n }\n async function asCallHierarchyIncomingCall(item, token) {\n return new code.CallHierarchyIncomingCall(asCallHierarchyItem(item.from), await asRanges(item.fromRanges, token));\n }\n async function asCallHierarchyIncomingCalls(items, token) {\n if (items === null) {\n return undefined;\n }\n return async.mapAsync(items, asCallHierarchyIncomingCall, token);\n }\n async function asCallHierarchyOutgoingCall(item, token) {\n return new code.CallHierarchyOutgoingCall(asCallHierarchyItem(item.to), await asRanges(item.fromRanges, token));\n }\n async function asCallHierarchyOutgoingCalls(items, token) {\n if (items === null) {\n return undefined;\n }\n return async.mapAsync(items, asCallHierarchyOutgoingCall, token);\n }\n async function asSemanticTokens(value, _token) {\n if (value === undefined || value === null) {\n return undefined;\n }\n return new code.SemanticTokens(new Uint32Array(value.data), value.resultId);\n }\n function asSemanticTokensEdit(value) {\n return new code.SemanticTokensEdit(value.start, value.deleteCount, value.data !== undefined ? new Uint32Array(value.data) : undefined);\n }\n async function asSemanticTokensEdits(value, _token) {\n if (value === undefined || value === null) {\n return undefined;\n }\n return new code.SemanticTokensEdits(value.edits.map(asSemanticTokensEdit), value.resultId);\n }\n function asSemanticTokensLegend(value) {\n return value;\n }\n async function asLinkedEditingRanges(value, token) {\n if (value === null || value === undefined) {\n return undefined;\n }\n return new code.LinkedEditingRanges(await asRanges(value.ranges, token), asRegularExpression(value.wordPattern));\n }\n function asRegularExpression(value) {\n if (value === null || value === undefined) {\n return undefined;\n }\n return new RegExp(value);\n }\n function asTypeHierarchyItem(item) {\n if (item === null) {\n return undefined;\n }\n let result = new protocolTypeHierarchyItem_1.default(asSymbolKind(item.kind), item.name, item.detail || '', asUri(item.uri), asRange(item.range), asRange(item.selectionRange), item.data);\n if (item.tags !== undefined) {\n result.tags = asSymbolTags(item.tags);\n }\n return result;\n }\n async function asTypeHierarchyItems(items, token) {\n if (items === null) {\n return undefined;\n }\n return async.map(items, asTypeHierarchyItem, token);\n }\n function asGlobPattern(pattern) {\n if (Is.string(pattern)) {\n return pattern;\n }\n if (ls.RelativePattern.is(pattern)) {\n if (ls.URI.is(pattern.baseUri)) {\n return new code.RelativePattern(asUri(pattern.baseUri), pattern.pattern);\n }\n else if (ls.WorkspaceFolder.is(pattern.baseUri)) {\n const workspaceFolder = code.workspace.getWorkspaceFolder(asUri(pattern.baseUri.uri));\n return workspaceFolder !== undefined ? new code.RelativePattern(workspaceFolder, pattern.pattern) : undefined;\n }\n }\n return undefined;\n }\n async function asInlineCompletionResult(value, token) {\n if (!value) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return async.map(value, (item) => asInlineCompletionItem(item), token);\n }\n const list = value;\n const converted = await async.map(list.items, (item) => {\n return asInlineCompletionItem(item);\n }, token);\n return new code.InlineCompletionList(converted);\n }\n function asInlineCompletionItem(item) {\n let insertText;\n if (typeof item.insertText === 'string') {\n insertText = item.insertText;\n }\n else {\n insertText = new code.SnippetString(item.insertText.value);\n }\n let command = undefined;\n if (item.command) {\n command = asCommand(item.command);\n }\n const inlineCompletionItem = new code.InlineCompletionItem(insertText, asRange(item.range), command);\n if (item.filterText) {\n inlineCompletionItem.filterText = item.filterText;\n }\n return inlineCompletionItem;\n }\n return {\n asUri,\n asDocumentSelector,\n asDiagnostics,\n asDiagnostic,\n asRange,\n asRanges,\n asPosition,\n asDiagnosticSeverity,\n asDiagnosticTag,\n asHover,\n asCompletionResult,\n asCompletionItem,\n asTextEdit,\n asTextEdits,\n asSignatureHelp,\n asSignatureInformations,\n asSignatureInformation,\n asParameterInformations,\n asParameterInformation,\n asDeclarationResult,\n asDefinitionResult,\n asLocation,\n asReferences,\n asDocumentHighlights,\n asDocumentHighlight,\n asDocumentHighlightKind,\n asSymbolKind,\n asSymbolTag,\n asSymbolTags,\n asSymbolInformations,\n asSymbolInformation,\n asDocumentSymbols,\n asDocumentSymbol,\n asCommand,\n asCommands,\n asCodeAction,\n asCodeActionKind,\n asCodeActionKinds,\n asCodeActionResult,\n asCodeLens,\n asCodeLenses,\n asWorkspaceEdit,\n asDocumentLink,\n asDocumentLinks,\n asFoldingRangeKind,\n asFoldingRange,\n asFoldingRanges,\n asColor,\n asColorInformation,\n asColorInformations,\n asColorPresentation,\n asColorPresentations,\n asSelectionRange,\n asSelectionRanges,\n asInlineValue,\n asInlineValues,\n asInlayHint,\n asInlayHints,\n asSemanticTokensLegend,\n asSemanticTokens,\n asSemanticTokensEdit,\n asSemanticTokensEdits,\n asCallHierarchyItem,\n asCallHierarchyItems,\n asCallHierarchyIncomingCall,\n asCallHierarchyIncomingCalls,\n asCallHierarchyOutgoingCall,\n asCallHierarchyOutgoingCalls,\n asLinkedEditingRanges: asLinkedEditingRanges,\n asTypeHierarchyItem,\n asTypeHierarchyItems,\n asGlobPattern,\n asInlineCompletionResult,\n asInlineCompletionItem\n };\n}\nexports.createConverter = createConverter;\n", "\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateUuid = exports.parse = exports.isUUID = exports.v4 = exports.empty = void 0;\nclass ValueUUID {\n constructor(_value) {\n this._value = _value;\n // empty\n }\n asHex() {\n return this._value;\n }\n equals(other) {\n return this.asHex() === other.asHex();\n }\n}\nclass V4UUID extends ValueUUID {\n static _oneOf(array) {\n return array[Math.floor(array.length * Math.random())];\n }\n static _randomHex() {\n return V4UUID._oneOf(V4UUID._chars);\n }\n constructor() {\n super([\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n '-',\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n '-',\n '4',\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n '-',\n V4UUID._oneOf(V4UUID._timeHighBits),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n '-',\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n V4UUID._randomHex(),\n ].join(''));\n }\n}\nV4UUID._chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\nV4UUID._timeHighBits = ['8', '9', 'a', 'b'];\n/**\n * An empty UUID that contains only zeros.\n */\nexports.empty = new ValueUUID('00000000-0000-0000-0000-000000000000');\nfunction v4() {\n return new V4UUID();\n}\nexports.v4 = v4;\nconst _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nfunction isUUID(value) {\n return _UUIDPattern.test(value);\n}\nexports.isUUID = isUUID;\n/**\n * Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.\n * @param value A uuid string.\n */\nfunction parse(value) {\n if (!isUUID(value)) {\n throw new Error('invalid uuid');\n }\n return new ValueUUID(value);\n}\nexports.parse = parse;\nfunction generateUuid() {\n return v4().asHex();\n}\nexports.generateUuid = generateUuid;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ProgressPart = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst Is = require(\"./utils/is\");\nclass ProgressPart {\n constructor(_client, _token, done) {\n this._client = _client;\n this._token = _token;\n this._reported = 0;\n this._infinite = false;\n this._lspProgressDisposable = this._client.onProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, (value) => {\n switch (value.kind) {\n case 'begin':\n this.begin(value);\n break;\n case 'report':\n this.report(value);\n break;\n case 'end':\n this.done();\n done && done(this);\n break;\n }\n });\n }\n begin(params) {\n this._infinite = params.percentage === undefined;\n // the progress as already been marked as done / canceled. Ignore begin call\n if (this._lspProgressDisposable === undefined) {\n return;\n }\n // Since we don't use commands this will be a silent window progress with a hidden notification.\n void vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Window, cancellable: params.cancellable, title: params.title }, async (progress, cancellationToken) => {\n // the progress as already been marked as done / canceled. Ignore begin call\n if (this._lspProgressDisposable === undefined) {\n return;\n }\n this._progress = progress;\n this._cancellationToken = cancellationToken;\n this._tokenDisposable = this._cancellationToken.onCancellationRequested(() => {\n this._client.sendNotification(vscode_languageserver_protocol_1.WorkDoneProgressCancelNotification.type, { token: this._token });\n });\n this.report(params);\n return new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n });\n }\n report(params) {\n if (this._infinite && Is.string(params.message)) {\n this._progress !== undefined && this._progress.report({ message: params.message });\n }\n else if (Is.number(params.percentage)) {\n const percentage = Math.max(0, Math.min(params.percentage, 100));\n const delta = Math.max(0, percentage - this._reported);\n this._reported += delta;\n this._progress !== undefined && this._progress.report({ message: params.message, increment: delta });\n }\n }\n cancel() {\n this.cleanup();\n if (this._reject !== undefined) {\n this._reject();\n this._resolve = undefined;\n this._reject = undefined;\n }\n }\n done() {\n this.cleanup();\n if (this._resolve !== undefined) {\n this._resolve();\n this._resolve = undefined;\n this._reject = undefined;\n }\n }\n cleanup() {\n if (this._lspProgressDisposable !== undefined) {\n this._lspProgressDisposable.dispose();\n this._lspProgressDisposable = undefined;\n }\n if (this._tokenDisposable !== undefined) {\n this._tokenDisposable.dispose();\n this._tokenDisposable = undefined;\n }\n this._progress = undefined;\n this._cancellationToken = undefined;\n }\n}\nexports.ProgressPart = ProgressPart;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WorkspaceFeature = exports.TextDocumentLanguageFeature = exports.TextDocumentEventFeature = exports.DynamicDocumentFeature = exports.DynamicFeature = exports.StaticFeature = exports.ensure = exports.LSPCancellationError = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst Is = require(\"./utils/is\");\nconst UUID = require(\"./utils/uuid\");\nclass LSPCancellationError extends vscode_1.CancellationError {\n constructor(data) {\n super();\n this.data = data;\n }\n}\nexports.LSPCancellationError = LSPCancellationError;\nfunction ensure(target, key) {\n if (target[key] === undefined) {\n target[key] = {};\n }\n return target[key];\n}\nexports.ensure = ensure;\nvar StaticFeature;\n(function (StaticFeature) {\n function is(value) {\n const candidate = value;\n return candidate !== undefined && candidate !== null &&\n Is.func(candidate.fillClientCapabilities) && Is.func(candidate.initialize) && Is.func(candidate.getState) && Is.func(candidate.clear) &&\n (candidate.fillInitializeParams === undefined || Is.func(candidate.fillInitializeParams));\n }\n StaticFeature.is = is;\n})(StaticFeature || (exports.StaticFeature = StaticFeature = {}));\nvar DynamicFeature;\n(function (DynamicFeature) {\n function is(value) {\n const candidate = value;\n return candidate !== undefined && candidate !== null &&\n Is.func(candidate.fillClientCapabilities) && Is.func(candidate.initialize) && Is.func(candidate.getState) && Is.func(candidate.clear) &&\n (candidate.fillInitializeParams === undefined || Is.func(candidate.fillInitializeParams)) && Is.func(candidate.register) &&\n Is.func(candidate.unregister) && candidate.registrationType !== undefined;\n }\n DynamicFeature.is = is;\n})(DynamicFeature || (exports.DynamicFeature = DynamicFeature = {}));\n/**\n * An abstract dynamic feature implementation that operates on documents (e.g. text\n * documents or notebooks).\n */\nclass DynamicDocumentFeature {\n constructor(client) {\n this._client = client;\n }\n /**\n * Returns the state the feature is in.\n */\n getState() {\n const selectors = this.getDocumentSelectors();\n let count = 0;\n for (const selector of selectors) {\n count++;\n for (const document of vscode_1.workspace.textDocuments) {\n if (vscode_1.languages.match(selector, document) > 0) {\n return { kind: 'document', id: this.registrationType.method, registrations: true, matches: true };\n }\n }\n }\n const registrations = count > 0;\n return { kind: 'document', id: this.registrationType.method, registrations, matches: false };\n }\n}\nexports.DynamicDocumentFeature = DynamicDocumentFeature;\n/**\n * An abstract base class to implement features that react to events\n * emitted from text documents.\n */\nclass TextDocumentEventFeature extends DynamicDocumentFeature {\n static textDocumentFilter(selectors, textDocument) {\n for (const selector of selectors) {\n if (vscode_1.languages.match(selector, textDocument) > 0) {\n return true;\n }\n }\n return false;\n }\n constructor(client, event, type, middleware, createParams, textDocument, selectorFilter) {\n super(client);\n this._event = event;\n this._type = type;\n this._middleware = middleware;\n this._createParams = createParams;\n this._textDocument = textDocument;\n this._selectorFilter = selectorFilter;\n this._selectors = new Map();\n this._onNotificationSent = new vscode_1.EventEmitter();\n }\n getStateInfo() {\n return [this._selectors.values(), false];\n }\n getDocumentSelectors() {\n return this._selectors.values();\n }\n register(data) {\n if (!data.registerOptions.documentSelector) {\n return;\n }\n if (!this._listener) {\n this._listener = this._event((data) => {\n this.callback(data).catch((error) => {\n this._client.error(`Sending document notification ${this._type.method} failed.`, error);\n });\n });\n }\n this._selectors.set(data.id, this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector));\n }\n async callback(data) {\n const doSend = async (data) => {\n const params = this._createParams(data);\n await this._client.sendNotification(this._type, params);\n this.notificationSent(this.getTextDocument(data), this._type, params);\n };\n if (this.matches(data)) {\n const middleware = this._middleware();\n return middleware ? middleware(data, (data) => doSend(data)) : doSend(data);\n }\n }\n matches(data) {\n if (this._client.hasDedicatedTextSynchronizationFeature(this._textDocument(data))) {\n return false;\n }\n return !this._selectorFilter || this._selectorFilter(this._selectors.values(), data);\n }\n get onNotificationSent() {\n return this._onNotificationSent.event;\n }\n notificationSent(textDocument, type, params) {\n this._onNotificationSent.fire({ textDocument, type, params });\n }\n unregister(id) {\n this._selectors.delete(id);\n if (this._selectors.size === 0 && this._listener) {\n this._listener.dispose();\n this._listener = undefined;\n }\n }\n clear() {\n this._selectors.clear();\n this._onNotificationSent.dispose();\n if (this._listener) {\n this._listener.dispose();\n this._listener = undefined;\n }\n }\n getProvider(document) {\n for (const selector of this._selectors.values()) {\n if (vscode_1.languages.match(selector, document) > 0) {\n return {\n send: (data) => {\n return this.callback(data);\n }\n };\n }\n }\n return undefined;\n }\n}\nexports.TextDocumentEventFeature = TextDocumentEventFeature;\n/**\n * A abstract feature implementation that registers language providers\n * for text documents using a given document selector.\n */\nclass TextDocumentLanguageFeature extends DynamicDocumentFeature {\n constructor(client, registrationType) {\n super(client);\n this._registrationType = registrationType;\n this._registrations = new Map();\n }\n *getDocumentSelectors() {\n for (const registration of this._registrations.values()) {\n const selector = registration.data.registerOptions.documentSelector;\n if (selector === null) {\n continue;\n }\n yield this._client.protocol2CodeConverter.asDocumentSelector(selector);\n }\n }\n get registrationType() {\n return this._registrationType;\n }\n register(data) {\n if (!data.registerOptions.documentSelector) {\n return;\n }\n let registration = this.registerLanguageProvider(data.registerOptions, data.id);\n this._registrations.set(data.id, { disposable: registration[0], data, provider: registration[1] });\n }\n unregister(id) {\n let registration = this._registrations.get(id);\n if (registration !== undefined) {\n registration.disposable.dispose();\n }\n }\n clear() {\n this._registrations.forEach((value) => {\n value.disposable.dispose();\n });\n this._registrations.clear();\n }\n getRegistration(documentSelector, capability) {\n if (!capability) {\n return [undefined, undefined];\n }\n else if (vscode_languageserver_protocol_1.TextDocumentRegistrationOptions.is(capability)) {\n const id = vscode_languageserver_protocol_1.StaticRegistrationOptions.hasId(capability) ? capability.id : UUID.generateUuid();\n const selector = capability.documentSelector ?? documentSelector;\n if (selector) {\n return [id, Object.assign({}, capability, { documentSelector: selector })];\n }\n }\n else if (Is.boolean(capability) && capability === true || vscode_languageserver_protocol_1.WorkDoneProgressOptions.is(capability)) {\n if (!documentSelector) {\n return [undefined, undefined];\n }\n const options = (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector }));\n return [UUID.generateUuid(), options];\n }\n return [undefined, undefined];\n }\n getRegistrationOptions(documentSelector, capability) {\n if (!documentSelector || !capability) {\n return undefined;\n }\n return (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector }));\n }\n getProvider(textDocument) {\n for (const registration of this._registrations.values()) {\n let selector = registration.data.registerOptions.documentSelector;\n if (selector !== null && vscode_1.languages.match(this._client.protocol2CodeConverter.asDocumentSelector(selector), textDocument) > 0) {\n return registration.provider;\n }\n }\n return undefined;\n }\n getAllProviders() {\n const result = [];\n for (const item of this._registrations.values()) {\n result.push(item.provider);\n }\n return result;\n }\n}\nexports.TextDocumentLanguageFeature = TextDocumentLanguageFeature;\nclass WorkspaceFeature {\n constructor(client, registrationType) {\n this._client = client;\n this._registrationType = registrationType;\n this._registrations = new Map();\n }\n getState() {\n const registrations = this._registrations.size > 0;\n return { kind: 'workspace', id: this._registrationType.method, registrations };\n }\n get registrationType() {\n return this._registrationType;\n }\n register(data) {\n const registration = this.registerLanguageProvider(data.registerOptions);\n this._registrations.set(data.id, { disposable: registration[0], provider: registration[1] });\n }\n unregister(id) {\n let registration = this._registrations.get(id);\n if (registration !== undefined) {\n registration.disposable.dispose();\n }\n }\n clear() {\n this._registrations.forEach((registration) => {\n registration.disposable.dispose();\n });\n this._registrations.clear();\n }\n getProviders() {\n const result = [];\n for (const registration of this._registrations.values()) {\n result.push(registration.provider);\n }\n return result;\n }\n}\nexports.WorkspaceFeature = WorkspaceFeature;\n", "const isWindows = typeof process === 'object' &&\n process &&\n process.platform === 'win32'\nmodule.exports = isWindows ? { sep: '\\\\' } : { sep: '/' }\n", "'use strict';\nmodule.exports = balanced;\nfunction balanced(a, b, str) {\n if (a instanceof RegExp) a = maybeMatch(a, str);\n if (b instanceof RegExp) b = maybeMatch(b, str);\n\n var r = range(a, b, str);\n\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + a.length, r[1]),\n post: str.slice(r[1] + b.length)\n };\n}\n\nfunction maybeMatch(reg, str) {\n var m = str.match(reg);\n return m ? m[0] : null;\n}\n\nbalanced.range = range;\nfunction range(a, b, str) {\n var begs, beg, left, right, result;\n var ai = str.indexOf(a);\n var bi = str.indexOf(b, ai + 1);\n var i = ai;\n\n if (ai >= 0 && bi > 0) {\n if(a===b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n\n while (i >= 0 && !result) {\n if (i == ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length == 1) {\n result = [ begs.pop(), bi ];\n } else {\n beg = begs.pop();\n if (beg < left) {\n left = beg;\n right = bi;\n }\n\n bi = str.indexOf(b, i + 1);\n }\n\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n\n if (begs.length) {\n result = [ left, right ];\n }\n }\n\n return result;\n}\n", "var balanced = require('balanced-match');\n\nmodule.exports = expandTop;\n\nvar escSlash = '\\0SLASH'+Math.random()+'\\0';\nvar escOpen = '\\0OPEN'+Math.random()+'\\0';\nvar escClose = '\\0CLOSE'+Math.random()+'\\0';\nvar escComma = '\\0COMMA'+Math.random()+'\\0';\nvar escPeriod = '\\0PERIOD'+Math.random()+'\\0';\n\nfunction numeric(str) {\n return parseInt(str, 10) == str\n ? parseInt(str, 10)\n : str.charCodeAt(0);\n}\n\nfunction escapeBraces(str) {\n return str.split('\\\\\\\\').join(escSlash)\n .split('\\\\{').join(escOpen)\n .split('\\\\}').join(escClose)\n .split('\\\\,').join(escComma)\n .split('\\\\.').join(escPeriod);\n}\n\nfunction unescapeBraces(str) {\n return str.split(escSlash).join('\\\\')\n .split(escOpen).join('{')\n .split(escClose).join('}')\n .split(escComma).join(',')\n .split(escPeriod).join('.');\n}\n\n\n// Basically just str.split(\",\"), but handling cases\n// where we have nested braced sections, which should be\n// treated as individual members, like {a,{b,c},d}\nfunction parseCommaParts(str) {\n if (!str)\n return [''];\n\n var parts = [];\n var m = balanced('{', '}', str);\n\n if (!m)\n return str.split(',');\n\n var pre = m.pre;\n var body = m.body;\n var post = m.post;\n var p = pre.split(',');\n\n p[p.length-1] += '{' + body + '}';\n var postParts = parseCommaParts(post);\n if (post.length) {\n p[p.length-1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n\n parts.push.apply(parts, p);\n\n return parts;\n}\n\nfunction expandTop(str, options) {\n if (!str)\n return [];\n\n options = options || {};\n var max = options.max == null ? Infinity : options.max;\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.substr(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.substr(2);\n }\n\n return expand(escapeBraces(str), max, true).map(unescapeBraces);\n}\n\nfunction embrace(str) {\n return '{' + str + '}';\n}\nfunction isPadded(el) {\n return /^-?0\\d/.test(el);\n}\n\nfunction lte(i, y) {\n return i <= y;\n}\nfunction gte(i, y) {\n return i >= y;\n}\n\nfunction expand(str, max, isTop) {\n var expansions = [];\n\n var m = balanced('{', '}', str);\n if (!m) return [str];\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n var pre = m.pre;\n var post = m.post.length\n ? expand(m.post, max, false)\n : [''];\n\n if (/\\$$/.test(m.pre)) { \n for (var k = 0; k < post.length && k < max; k++) {\n var expansion = pre+ '{' + m.body + '}' + post[k];\n expansions.push(expansion);\n }\n } else {\n var isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n var isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n var isSequence = isNumericSequence || isAlphaSequence;\n var isOptions = m.body.indexOf(',') >= 0;\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post;\n return expand(str, max, true);\n }\n return [str];\n }\n\n var n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand(n[0], max, false).map(embrace);\n if (n.length === 1) {\n return post.map(function(p) {\n return m.pre + n[0] + p;\n });\n }\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n var N;\n\n if (isSequence) {\n var x = numeric(n[0]);\n var y = numeric(n[1]);\n var width = Math.max(n[0].length, n[1].length)\n var incr = n.length == 3\n ? Math.max(Math.abs(numeric(n[2])), 1)\n : 1;\n var test = lte;\n var reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n var pad = n.some(isPadded);\n\n N = [];\n\n for (var i = x; test(i, y) && N.length < max; i += incr) {\n var c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === '\\\\')\n c = '';\n } else {\n c = String(i);\n if (pad) {\n var need = width - c.length;\n if (need > 0) {\n var z = new Array(need + 1).join('0');\n if (i < 0)\n c = '-' + z + c.slice(1);\n else\n c = z + c;\n }\n }\n }\n N.push(c);\n }\n } else {\n N = [];\n\n for (var j = 0; j < n.length; j++) {\n N.push.apply(N, expand(n[j], max, false));\n }\n }\n\n for (var j = 0; j < N.length; j++) {\n for (var k = 0; k < post.length && expansions.length < max; k++) {\n var expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion)\n expansions.push(expansion);\n }\n }\n }\n\n return expansions;\n}\n", "const minimatch = module.exports = (p, pattern, options = {}) => {\n assertValidPattern(pattern)\n\n // shortcut: comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n return false\n }\n\n return new Minimatch(pattern, options).match(p)\n}\n\nmodule.exports = minimatch\n\nconst path = require('./lib/path.js')\nminimatch.sep = path.sep\n\nconst GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\nconst expand = require('brace-expansion')\n\nconst plTypes = {\n '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},\n '?': { open: '(?:', close: ')?' },\n '+': { open: '(?:', close: ')+' },\n '*': { open: '(?:', close: ')*' },\n '@': { open: '(?:', close: ')' }\n}\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed. Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\\\/|^)(?:\\\\.{1,2})($|\\\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\\\/|^)\\\\.).)*?'\n\n// \"abc\" -> { a:true, b:true, c:true }\nconst charSet = s => s.split('').reduce((set, c) => {\n set[c] = true\n return set\n}, {})\n\n// characters that need to be escaped in RegExp.\nconst reSpecials = charSet('().*{}+?[]^$\\\\!')\n\n// characters that indicate we have to add the pattern start\nconst addPatternStartSet = charSet('[.(')\n\n// normalizes slashes.\nconst slashSplit = /\\/+/\n\nminimatch.filter = (pattern, options = {}) =>\n (p, i, list) => minimatch(p, pattern, options)\n\nconst ext = (a, b = {}) => {\n const t = {}\n Object.keys(a).forEach(k => t[k] = a[k])\n Object.keys(b).forEach(k => t[k] = b[k])\n return t\n}\n\nminimatch.defaults = def => {\n if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n return minimatch\n }\n\n const orig = minimatch\n\n const m = (p, pattern, options) => orig(p, pattern, ext(def, options))\n m.Minimatch = class Minimatch extends orig.Minimatch {\n constructor (pattern, options) {\n super(pattern, ext(def, options))\n }\n }\n m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch\n m.filter = (pattern, options) => orig.filter(pattern, ext(def, options))\n m.defaults = options => orig.defaults(ext(def, options))\n m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options))\n m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options))\n m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options))\n\n return m\n}\n\n\n\n\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nminimatch.braceExpand = (pattern, options) => braceExpand(pattern, options)\n\nconst braceExpand = (pattern, options = {}) => {\n assertValidPattern(pattern)\n\n // Thanks to Yeting Li for\n // improving this regexp to avoid a ReDOS vulnerability.\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n // shortcut. no need to expand.\n return [pattern]\n }\n\n return expand(pattern)\n}\n\nconst MAX_PATTERN_LENGTH = 1024 * 64\nconst assertValidPattern = pattern => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion. Otherwise, any series\n// of * is equivalent to a single *. Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\nconst SUBPARSE = Symbol('subparse')\n\nminimatch.makeRe = (pattern, options) =>\n new Minimatch(pattern, options || {}).makeRe()\n\nminimatch.match = (list, pattern, options = {}) => {\n const mm = new Minimatch(pattern, options)\n list = list.filter(f => mm.match(f))\n if (mm.options.nonull && !list.length) {\n list.push(pattern)\n }\n return list\n}\n\n// replace stuff like \\* with *\nconst globUnescape = s => s.replace(/\\\\(.)/g, '$1')\nconst charUnescape = s => s.replace(/\\\\([^-\\]])/g, '$1')\nconst regExpEscape = s => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\nconst braExpEscape = s => s.replace(/[[\\]\\\\]/g, '\\\\$&')\n\nclass Minimatch {\n constructor (pattern, options) {\n assertValidPattern(pattern)\n\n if (!options) options = {}\n\n this.options = options\n this.maxGlobstarRecursion = options.maxGlobstarRecursion !== undefined\n ? options.maxGlobstarRecursion : 200\n this.set = []\n this.pattern = pattern\n this.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||\n options.allowWindowsEscape === false\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, '/')\n }\n this.regexp = null\n this.negate = false\n this.comment = false\n this.empty = false\n this.partial = !!options.partial\n\n // make the set of regexps etc.\n this.make()\n }\n\n debug () {}\n\n make () {\n const pattern = this.pattern\n const options = this.options\n\n // empty patterns and comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n this.comment = true\n return\n }\n if (!pattern) {\n this.empty = true\n return\n }\n\n // step 1: figure out negation, etc.\n this.parseNegate()\n\n // step 2: expand braces\n let set = this.globSet = this.braceExpand()\n\n if (options.debug) this.debug = (...args) => console.error(...args)\n\n this.debug(this.pattern, set)\n\n // step 3: now we have a set, so turn each one into a series of path-portion\n // matching patterns.\n // These will be regexps, except in the case of \"**\", which is\n // set to the GLOBSTAR object for globstar behavior,\n // and will not contain any / characters\n set = this.globParts = set.map(s => s.split(slashSplit))\n\n this.debug(this.pattern, set)\n\n // glob --> regexps\n set = set.map((s, si, set) => s.map(this.parse, this))\n\n this.debug(this.pattern, set)\n\n // filter out everything that didn't compile properly.\n set = set.filter(s => s.indexOf(false) === -1)\n\n this.debug(this.pattern, set)\n\n this.set = set\n }\n\n parseNegate () {\n if (this.options.nonegate) return\n\n const pattern = this.pattern\n let negate = false\n let negateOffset = 0\n\n for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n negate = !negate\n negateOffset++\n }\n\n if (negateOffset) this.pattern = pattern.slice(negateOffset)\n this.negate = negate\n }\n\n // set partial to true to test if, for example,\n // \"/a/b\" matches the start of \"/*/b/*/d\"\n // Partial means, if you run out of file before you run\n // out of pattern, then that's fine, as long as all\n // the parts match.\n matchOne (file, pattern, partial) {\n if (pattern.indexOf(GLOBSTAR) !== -1) {\n return this._matchGlobstar(file, pattern, partial, 0, 0)\n }\n return this._matchOne(file, pattern, partial, 0, 0)\n }\n\n _matchGlobstar (file, pattern, partial, fileIndex, patternIndex) {\n // find first globstar from patternIndex\n let firstgs = -1\n for (let i = patternIndex; i < pattern.length; i++) {\n if (pattern[i] === GLOBSTAR) { firstgs = i; break }\n }\n\n // find last globstar\n let lastgs = -1\n for (let i = pattern.length - 1; i >= 0; i--) {\n if (pattern[i] === GLOBSTAR) { lastgs = i; break }\n }\n\n const head = pattern.slice(patternIndex, firstgs)\n const body = partial ? pattern.slice(firstgs + 1) : pattern.slice(firstgs + 1, lastgs)\n const tail = partial ? [] : pattern.slice(lastgs + 1)\n\n // check the head\n if (head.length) {\n const fileHead = file.slice(fileIndex, fileIndex + head.length)\n if (!this._matchOne(fileHead, head, partial, 0, 0)) {\n return false\n }\n fileIndex += head.length\n }\n\n // check the tail\n let fileTailMatch = 0\n if (tail.length) {\n if (tail.length + fileIndex > file.length) return false\n\n const tailStart = file.length - tail.length\n if (this._matchOne(file, tail, partial, tailStart, 0)) {\n fileTailMatch = tail.length\n } else {\n // affordance for stuff like a/**/* matching a/b/\n if (file[file.length - 1] !== '' ||\n fileIndex + tail.length === file.length) {\n return false\n }\n if (!this._matchOne(file, tail, partial, tailStart - 1, 0)) {\n return false\n }\n fileTailMatch = tail.length + 1\n }\n }\n\n // if body is empty (single ** between head and tail)\n if (!body.length) {\n let sawSome = !!fileTailMatch\n for (let i = fileIndex; i < file.length - fileTailMatch; i++) {\n const f = String(file[i])\n sawSome = true\n if (f === '.' || f === '..' ||\n (!this.options.dot && f.charAt(0) === '.')) {\n return false\n }\n }\n return partial || sawSome\n }\n\n // split body into segments at each GLOBSTAR\n const bodySegments = [[[], 0]]\n let currentBody = bodySegments[0]\n let nonGsParts = 0\n const nonGsPartsSums = [0]\n for (const b of body) {\n if (b === GLOBSTAR) {\n nonGsPartsSums.push(nonGsParts)\n currentBody = [[], 0]\n bodySegments.push(currentBody)\n } else {\n currentBody[0].push(b)\n nonGsParts++\n }\n }\n\n let idx = bodySegments.length - 1\n const fileLength = file.length - fileTailMatch\n for (const b of bodySegments) {\n b[1] = fileLength - (nonGsPartsSums[idx--] + b[0].length)\n }\n\n return !!this._matchGlobStarBodySections(\n file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch\n )\n }\n\n // return false for \"nope, not matching\"\n // return null for \"not matching, cannot keep trying\"\n _matchGlobStarBodySections (\n file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail\n ) {\n const bs = bodySegments[bodyIndex]\n if (!bs) {\n // just make sure there are no bad dots\n for (let i = fileIndex; i < file.length; i++) {\n sawTail = true\n const f = file[i]\n if (f === '.' || f === '..' ||\n (!this.options.dot && f.charAt(0) === '.')) {\n return false\n }\n }\n return sawTail\n }\n\n const [body, after] = bs\n while (fileIndex <= after) {\n const m = this._matchOne(\n file.slice(0, fileIndex + body.length),\n body,\n partial,\n fileIndex,\n 0\n )\n // if limit exceeded, no match. intentional false negative,\n // acceptable break in correctness for security.\n if (m && globStarDepth < this.maxGlobstarRecursion) {\n const sub = this._matchGlobStarBodySections(\n file, bodySegments,\n fileIndex + body.length, bodyIndex + 1,\n partial, globStarDepth + 1, sawTail\n )\n if (sub !== false) {\n return sub\n }\n }\n const f = file[fileIndex]\n if (f === '.' || f === '..' ||\n (!this.options.dot && f.charAt(0) === '.')) {\n return false\n }\n fileIndex++\n }\n return partial || null\n }\n\n _matchOne (file, pattern, partial, fileIndex, patternIndex) {\n let fi, pi, fl, pl\n for (\n fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length\n ; (fi < fl) && (pi < pl)\n ; fi++, pi++\n ) {\n this.debug('matchOne loop')\n const p = pattern[pi]\n const f = file[fi]\n\n this.debug(pattern, p, f)\n\n // should be impossible.\n // some invalid regexp stuff in the set.\n /* istanbul ignore if */\n if (p === false || p === GLOBSTAR) return false\n\n // something other than **\n // non-magic patterns just have to match exactly\n // patterns with magic have been turned into regexps.\n let hit\n if (typeof p === 'string') {\n hit = f === p\n this.debug('string match', p, f, hit)\n } else {\n hit = f.match(p)\n this.debug('pattern match', p, f, hit)\n }\n\n if (!hit) return false\n }\n\n // now either we fell off the end of the pattern, or we're done.\n if (fi === fl && pi === pl) {\n // ran out of pattern and filename at the same time.\n // an exact hit!\n return true\n } else if (fi === fl) {\n // ran out of file, but still had pattern left.\n // this is ok if we're doing the match as part of\n // a glob fs traversal.\n return partial\n } else /* istanbul ignore else */ if (pi === pl) {\n // ran out of pattern, still have file left.\n // this is only acceptable if we're on the very last\n // empty segment of a file with a trailing slash.\n // a/* should match a/b/\n return (fi === fl - 1) && (file[fi] === '')\n }\n\n // should be unreachable.\n /* istanbul ignore next */\n throw new Error('wtf?')\n }\n\n braceExpand () {\n return braceExpand(this.pattern, this.options)\n }\n\n parse (pattern, isSub) {\n assertValidPattern(pattern)\n\n const options = this.options\n\n // shortcuts\n if (pattern === '**') {\n if (!options.noglobstar)\n return GLOBSTAR\n else\n pattern = '*'\n }\n if (pattern === '') return ''\n\n let re = ''\n let hasMagic = false\n let escaping = false\n // ? => one single character\n const patternListStack = []\n const negativeLists = []\n let stateChar\n let inClass = false\n let reClassStart = -1\n let classStart = -1\n let cs\n let pl\n let sp\n // . and .. never match anything that doesn't start with .,\n // even when options.dot is set. However, if the pattern\n // starts with ., then traversal patterns can match.\n let dotTravAllowed = pattern.charAt(0) === '.'\n let dotFileAllowed = options.dot || dotTravAllowed\n const patternStart = () =>\n dotTravAllowed\n ? ''\n : dotFileAllowed\n ? '(?!(?:^|\\\\/)\\\\.{1,2}(?:$|\\\\/))'\n : '(?!\\\\.)'\n const subPatternStart = (p) =>\n p.charAt(0) === '.'\n ? ''\n : options.dot\n ? '(?!(?:^|\\\\/)\\\\.{1,2}(?:$|\\\\/))'\n : '(?!\\\\.)'\n\n\n const clearStateChar = () => {\n if (stateChar) {\n // we had some state-tracking character\n // that wasn't consumed by this pass.\n switch (stateChar) {\n case '*':\n re += star\n hasMagic = true\n break\n case '?':\n re += qmark\n hasMagic = true\n break\n default:\n re += '\\\\' + stateChar\n break\n }\n this.debug('clearStateChar %j %j', stateChar, re)\n stateChar = false\n }\n }\n\n for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) {\n this.debug('%s\\t%s %s %j', pattern, i, re, c)\n\n // skip over any that are escaped.\n if (escaping) {\n /* istanbul ignore next - completely not allowed, even escaped. */\n if (c === '/') {\n return false\n }\n\n if (reSpecials[c]) {\n re += '\\\\'\n }\n re += c\n escaping = false\n continue\n }\n\n switch (c) {\n /* istanbul ignore next */\n case '/': {\n // Should already be path-split by now.\n return false\n }\n\n case '\\\\':\n if (inClass && pattern.charAt(i + 1) === '-') {\n re += c\n continue\n }\n\n clearStateChar()\n escaping = true\n continue\n\n // the various stateChar values\n // for the \"extglob\" stuff.\n case '?':\n case '*':\n case '+':\n case '@':\n case '!':\n this.debug('%s\\t%s %s %j <-- stateChar', pattern, i, re, c)\n\n // all of those are literals inside a class, except that\n // the glob [!a] means [^a] in regexp\n if (inClass) {\n this.debug(' in class')\n if (c === '!' && i === classStart + 1) c = '^'\n re += c\n continue\n }\n\n // coalesce consecutive non-globstar * characters\n if (c === '*' && stateChar === '*') continue\n\n // if we already have a stateChar, then it means\n // that there was something like ** or +? in there.\n // Handle the stateChar, then proceed with this one.\n this.debug('call clearStateChar %j', stateChar)\n clearStateChar()\n stateChar = c\n // if extglob is disabled, then +(asdf|foo) isn't a thing.\n // just clear the statechar *now*, rather than even diving into\n // the patternList stuff.\n if (options.noext) clearStateChar()\n continue\n\n case '(': {\n if (inClass) {\n re += '('\n continue\n }\n\n if (!stateChar) {\n re += '\\\\('\n continue\n }\n\n const plEntry = {\n type: stateChar,\n start: i - 1,\n reStart: re.length,\n open: plTypes[stateChar].open,\n close: plTypes[stateChar].close,\n }\n this.debug(this.pattern, '\\t', plEntry)\n patternListStack.push(plEntry)\n // negation is (?:(?!(?:js)(?:))[^/]*)\n re += plEntry.open\n // next entry starts with a dot maybe?\n if (plEntry.start === 0 && plEntry.type !== '!') {\n dotTravAllowed = true\n re += subPatternStart(pattern.slice(i + 1))\n }\n this.debug('plType %j %j', stateChar, re)\n stateChar = false\n continue\n }\n\n case ')': {\n const plEntry = patternListStack[patternListStack.length - 1]\n if (inClass || !plEntry) {\n re += '\\\\)'\n continue\n }\n patternListStack.pop()\n\n // closing an extglob\n clearStateChar()\n hasMagic = true\n pl = plEntry\n // negation is (?:(?!js)[^/]*)\n // The others are (?:)\n re += pl.close\n if (pl.type === '!') {\n negativeLists.push(Object.assign(pl, { reEnd: re.length }))\n }\n continue\n }\n\n case '|': {\n const plEntry = patternListStack[patternListStack.length - 1]\n if (inClass || !plEntry) {\n re += '\\\\|'\n continue\n }\n\n clearStateChar()\n re += '|'\n // next subpattern can start with a dot?\n if (plEntry.start === 0 && plEntry.type !== '!') {\n dotTravAllowed = true\n re += subPatternStart(pattern.slice(i + 1))\n }\n continue\n }\n\n // these are mostly the same in regexp and glob\n case '[':\n // swallow any state-tracking char before the [\n clearStateChar()\n\n if (inClass) {\n re += '\\\\' + c\n continue\n }\n\n inClass = true\n classStart = i\n reClassStart = re.length\n re += c\n continue\n\n case ']':\n // a right bracket shall lose its special\n // meaning and represent itself in\n // a bracket expression if it occurs\n // first in the list. -- POSIX.2 2.8.3.2\n if (i === classStart + 1 || !inClass) {\n re += '\\\\' + c\n continue\n }\n\n // split where the last [ was, make sure we don't have\n // an invalid re. if so, re-walk the contents of the\n // would-be class to re-translate any characters that\n // were passed through as-is\n // TODO: It would probably be faster to determine this\n // without a try/catch and a new RegExp, but it's tricky\n // to do safely. For now, this is safe and works.\n cs = pattern.substring(classStart + 1, i)\n try {\n RegExp('[' + braExpEscape(charUnescape(cs)) + ']')\n // looks good, finish up the class.\n re += c\n } catch (er) {\n // out of order ranges in JS are errors, but in glob syntax,\n // they're just a range that matches nothing.\n re = re.substring(0, reClassStart) + '(?:$.)' // match nothing ever\n }\n hasMagic = true\n inClass = false\n continue\n\n default:\n // swallow any state char that wasn't consumed\n clearStateChar()\n\n if (reSpecials[c] && !(c === '^' && inClass)) {\n re += '\\\\'\n }\n\n re += c\n break\n\n } // switch\n } // for\n\n // handle the case where we left a class open.\n // \"[abc\" is valid, equivalent to \"\\[abc\"\n if (inClass) {\n // split where the last [ was, and escape it\n // this is a huge pita. We now have to re-walk\n // the contents of the would-be class to re-translate\n // any characters that were passed through as-is\n cs = pattern.slice(classStart + 1)\n sp = this.parse(cs, SUBPARSE)\n re = re.substring(0, reClassStart) + '\\\\[' + sp[0]\n hasMagic = hasMagic || sp[1]\n }\n\n // handle the case where we had a +( thing at the *end*\n // of the pattern.\n // each pattern list stack adds 3 chars, and we need to go through\n // and escape any | chars that were passed through as-is for the regexp.\n // Go through and escape them, taking care not to double-escape any\n // | chars that were already escaped.\n for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {\n let tail\n tail = re.slice(pl.reStart + pl.open.length)\n this.debug('setting tail', re, pl)\n // maybe some even number of \\, then maybe 1 \\, followed by a |\n tail = tail.replace(/((?:\\\\{2}){0,64})(\\\\?)\\|/g, (_, $1, $2) => {\n /* istanbul ignore else - should already be done */\n if (!$2) {\n // the | isn't already escaped, so escape it.\n $2 = '\\\\'\n }\n\n // need to escape all those slashes *again*, without escaping the\n // one that we need for escaping the | character. As it works out,\n // escaping an even number of slashes can be done by simply repeating\n // it exactly after itself. That's why this trick works.\n //\n // I am sorry that you have to see this.\n return $1 + $1 + $2 + '|'\n })\n\n this.debug('tail=%j\\n %s', tail, tail, pl, re)\n const t = pl.type === '*' ? star\n : pl.type === '?' ? qmark\n : '\\\\' + pl.type\n\n hasMagic = true\n re = re.slice(0, pl.reStart) + t + '\\\\(' + tail\n }\n\n // handle trailing things that only matter at the very end.\n clearStateChar()\n if (escaping) {\n // trailing \\\\\n re += '\\\\\\\\'\n }\n\n // only need to apply the nodot start if the re starts with\n // something that could conceivably capture a dot\n const addPatternStart = addPatternStartSet[re.charAt(0)]\n\n // Hack to work around lack of negative lookbehind in JS\n // A pattern like: *.!(x).!(y|z) needs to ensure that a name\n // like 'a.xyz.yz' doesn't match. So, the first negative\n // lookahead, has to look ALL the way ahead, to the end of\n // the pattern.\n for (let n = negativeLists.length - 1; n > -1; n--) {\n const nl = negativeLists[n]\n\n const nlBefore = re.slice(0, nl.reStart)\n const nlFirst = re.slice(nl.reStart, nl.reEnd - 8)\n let nlAfter = re.slice(nl.reEnd)\n const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter\n\n // Handle nested stuff like *(*.js|!(*.json)), where open parens\n // mean that we should *not* include the ) in the bit that is considered\n // \"after\" the negated section.\n const closeParensBefore = nlBefore.split(')').length\n const openParensBefore = nlBefore.split('(').length - closeParensBefore\n let cleanAfter = nlAfter\n for (let i = 0; i < openParensBefore; i++) {\n cleanAfter = cleanAfter.replace(/\\)[+*?]?/, '')\n }\n nlAfter = cleanAfter\n\n const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\\\/)' : ''\n\n re = nlBefore + nlFirst + nlAfter + dollar + nlLast\n }\n\n // if the re is not \"\" at this point, then we need to make sure\n // it doesn't match against an empty path part.\n // Otherwise a/* will match a/, which it should not.\n if (re !== '' && hasMagic) {\n re = '(?=.)' + re\n }\n\n if (addPatternStart) {\n re = patternStart() + re\n }\n\n // parsing just a piece of a larger pattern.\n if (isSub === SUBPARSE) {\n return [re, hasMagic]\n }\n\n // if it's nocase, and the lcase/uppercase don't match, it's magic\n if (options.nocase && !hasMagic) {\n hasMagic = pattern.toUpperCase() !== pattern.toLowerCase()\n }\n\n // skip the regexp for non-magical patterns\n // unescape anything in it, though, so that it'll be\n // an exact match against a file etc.\n if (!hasMagic) {\n return globUnescape(pattern)\n }\n\n const flags = options.nocase ? 'i' : ''\n try {\n return Object.assign(new RegExp('^' + re + '$', flags), {\n _glob: pattern,\n _src: re,\n })\n } catch (er) /* istanbul ignore next - should be impossible */ {\n // If it was an invalid regular expression, then it can't match\n // anything. This trick looks for a character after the end of\n // the string, which is of course impossible, except in multi-line\n // mode, but it's not a /m regex.\n return new RegExp('$.')\n }\n }\n\n makeRe () {\n if (this.regexp || this.regexp === false) return this.regexp\n\n // at this point, this.set is a 2d array of partial\n // pattern strings, or \"**\".\n //\n // It's better to use .match(). This function shouldn't\n // be used, really, but it's pretty convenient sometimes,\n // when you just want to work with a regex.\n const set = this.set\n\n if (!set.length) {\n this.regexp = false\n return this.regexp\n }\n const options = this.options\n\n const twoStar = options.noglobstar ? star\n : options.dot ? twoStarDot\n : twoStarNoDot\n const flags = options.nocase ? 'i' : ''\n\n // coalesce globstars and regexpify non-globstar patterns\n // if it's the only item, then we just do one twoStar\n // if it's the first, and there are more, prepend (\\/|twoStar\\/)? to next\n // if it's the last, append (\\/twoStar|) to previous\n // if it's in the middle, append (\\/|\\/twoStar\\/) to previous\n // then filter out GLOBSTAR symbols\n let re = set.map(pattern => {\n pattern = pattern.map(p =>\n typeof p === 'string' ? regExpEscape(p)\n : p === GLOBSTAR ? GLOBSTAR\n : p._src\n ).reduce((set, p) => {\n if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) {\n set.push(p)\n }\n return set\n }, [])\n pattern.forEach((p, i) => {\n if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) {\n return\n }\n if (i === 0) {\n if (pattern.length > 1) {\n pattern[i+1] = '(?:\\\\\\/|' + twoStar + '\\\\\\/)?' + pattern[i+1]\n } else {\n pattern[i] = twoStar\n }\n } else if (i === pattern.length - 1) {\n pattern[i-1] += '(?:\\\\\\/|' + twoStar + ')?'\n } else {\n pattern[i-1] += '(?:\\\\\\/|\\\\\\/' + twoStar + '\\\\\\/)' + pattern[i+1]\n pattern[i+1] = GLOBSTAR\n }\n })\n return pattern.filter(p => p !== GLOBSTAR).join('/')\n }).join('|')\n\n // must match entire pattern\n // ending in a * or ** will make it less strict.\n re = '^(?:' + re + ')$'\n\n // can match anything, as long as it's not this.\n if (this.negate) re = '^(?!' + re + ').*$'\n\n try {\n this.regexp = new RegExp(re, flags)\n } catch (ex) /* istanbul ignore next - should be impossible */ {\n this.regexp = false\n }\n return this.regexp\n }\n\n match (f, partial = this.partial) {\n this.debug('match', f, this.pattern)\n // short-circuit in the case of busted things.\n // comments, etc.\n if (this.comment) return false\n if (this.empty) return f === ''\n\n if (f === '/' && partial) return true\n\n const options = this.options\n\n // windows: need to use /, not \\\n if (path.sep !== '/') {\n f = f.split(path.sep).join('/')\n }\n\n // treat the test path as a set of pathparts.\n f = f.split(slashSplit)\n this.debug(this.pattern, 'split', f)\n\n // just ONE of the pattern sets in this.set needs to match\n // in order for it to be valid. If negating, then just one\n // match means that we have failed.\n // Either way, return on the first hit.\n\n const set = this.set\n this.debug(this.pattern, 'set', set)\n\n // Find the basename of the path by looking for the last non-empty segment\n let filename\n for (let i = f.length - 1; i >= 0; i--) {\n filename = f[i]\n if (filename) break\n }\n\n for (let i = 0; i < set.length; i++) {\n const pattern = set[i]\n let file = f\n if (options.matchBase && pattern.length === 1) {\n file = [filename]\n }\n const hit = this.matchOne(file, pattern, partial)\n if (hit) {\n if (options.flipNegate) return true\n return !this.negate\n }\n }\n\n // didn't get any hits. this is success if it's a negative\n // pattern, failure otherwise.\n if (options.flipNegate) return false\n return this.negate\n }\n\n static defaults (def) {\n return minimatch.defaults(def).Minimatch\n }\n}\n\nminimatch.Minimatch = Minimatch\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DiagnosticFeature = exports.DiagnosticPullMode = exports.vsdiag = void 0;\nconst minimatch = require(\"minimatch\");\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst uuid_1 = require(\"./utils/uuid\");\nconst features_1 = require(\"./features\");\nfunction ensure(target, key) {\n if (target[key] === void 0) {\n target[key] = {};\n }\n return target[key];\n}\nvar vsdiag;\n(function (vsdiag) {\n let DocumentDiagnosticReportKind;\n (function (DocumentDiagnosticReportKind) {\n DocumentDiagnosticReportKind[\"full\"] = \"full\";\n DocumentDiagnosticReportKind[\"unChanged\"] = \"unChanged\";\n })(DocumentDiagnosticReportKind = vsdiag.DocumentDiagnosticReportKind || (vsdiag.DocumentDiagnosticReportKind = {}));\n})(vsdiag || (exports.vsdiag = vsdiag = {}));\nvar DiagnosticPullMode;\n(function (DiagnosticPullMode) {\n DiagnosticPullMode[\"onType\"] = \"onType\";\n DiagnosticPullMode[\"onSave\"] = \"onSave\";\n})(DiagnosticPullMode || (exports.DiagnosticPullMode = DiagnosticPullMode = {}));\nvar RequestStateKind;\n(function (RequestStateKind) {\n RequestStateKind[\"active\"] = \"open\";\n RequestStateKind[\"reschedule\"] = \"reschedule\";\n RequestStateKind[\"outDated\"] = \"drop\";\n})(RequestStateKind || (RequestStateKind = {}));\n/**\n * Manages the open tabs. We don't directly use the tab API since for\n * diagnostics we need to de-dupe tabs that show the same resources since\n * we pull on the model not the UI.\n */\nclass Tabs {\n constructor() {\n this.open = new Set();\n this._onOpen = new vscode_1.EventEmitter();\n this._onClose = new vscode_1.EventEmitter();\n Tabs.fillTabResources(this.open);\n const openTabsHandler = (event) => {\n if (event.closed.length === 0 && event.opened.length === 0) {\n return;\n }\n const oldTabs = this.open;\n const currentTabs = new Set();\n Tabs.fillTabResources(currentTabs);\n const closed = new Set();\n const opened = new Set(currentTabs);\n for (const tab of oldTabs.values()) {\n if (currentTabs.has(tab)) {\n opened.delete(tab);\n }\n else {\n closed.add(tab);\n }\n }\n this.open = currentTabs;\n if (closed.size > 0) {\n const toFire = new Set();\n for (const item of closed) {\n toFire.add(vscode_1.Uri.parse(item));\n }\n this._onClose.fire(toFire);\n }\n if (opened.size > 0) {\n const toFire = new Set();\n for (const item of opened) {\n toFire.add(vscode_1.Uri.parse(item));\n }\n this._onOpen.fire(toFire);\n }\n };\n if (vscode_1.window.tabGroups.onDidChangeTabs !== undefined) {\n this.disposable = vscode_1.window.tabGroups.onDidChangeTabs(openTabsHandler);\n }\n else {\n this.disposable = { dispose: () => { } };\n }\n }\n get onClose() {\n return this._onClose.event;\n }\n get onOpen() {\n return this._onOpen.event;\n }\n dispose() {\n this.disposable.dispose();\n }\n isActive(document) {\n return document instanceof vscode_1.Uri\n ? vscode_1.window.activeTextEditor?.document.uri === document\n : vscode_1.window.activeTextEditor?.document === document;\n }\n isVisible(document) {\n const uri = document instanceof vscode_1.Uri ? document : document.uri;\n return this.open.has(uri.toString());\n }\n getTabResources() {\n const result = new Set();\n Tabs.fillTabResources(new Set(), result);\n return result;\n }\n static fillTabResources(strings, uris) {\n const seen = strings ?? new Set();\n for (const group of vscode_1.window.tabGroups.all) {\n for (const tab of group.tabs) {\n const input = tab.input;\n let uri;\n if (input instanceof vscode_1.TabInputText) {\n uri = input.uri;\n }\n else if (input instanceof vscode_1.TabInputTextDiff) {\n uri = input.modified;\n }\n else if (input instanceof vscode_1.TabInputCustom) {\n uri = input.uri;\n }\n if (uri !== undefined && !seen.has(uri.toString())) {\n seen.add(uri.toString());\n uris !== undefined && uris.add(uri);\n }\n }\n }\n }\n}\nvar PullState;\n(function (PullState) {\n PullState[PullState[\"document\"] = 1] = \"document\";\n PullState[PullState[\"workspace\"] = 2] = \"workspace\";\n})(PullState || (PullState = {}));\nvar DocumentOrUri;\n(function (DocumentOrUri) {\n function asKey(document) {\n return document instanceof vscode_1.Uri ? document.toString() : document.uri.toString();\n }\n DocumentOrUri.asKey = asKey;\n})(DocumentOrUri || (DocumentOrUri = {}));\nclass DocumentPullStateTracker {\n constructor() {\n this.documentPullStates = new Map();\n this.workspacePullStates = new Map();\n }\n track(kind, document, arg1) {\n const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates;\n const [key, uri, version] = document instanceof vscode_1.Uri\n ? [document.toString(), document, arg1]\n : [document.uri.toString(), document.uri, document.version];\n let state = states.get(key);\n if (state === undefined) {\n state = { document: uri, pulledVersion: version, resultId: undefined };\n states.set(key, state);\n }\n return state;\n }\n update(kind, document, arg1, arg2) {\n const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates;\n const [key, uri, version, resultId] = document instanceof vscode_1.Uri\n ? [document.toString(), document, arg1, arg2]\n : [document.uri.toString(), document.uri, document.version, arg1];\n let state = states.get(key);\n if (state === undefined) {\n state = { document: uri, pulledVersion: version, resultId };\n states.set(key, state);\n }\n else {\n state.pulledVersion = version;\n state.resultId = resultId;\n }\n }\n unTrack(kind, document) {\n const key = DocumentOrUri.asKey(document);\n const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates;\n states.delete(key);\n }\n tracks(kind, document) {\n const key = DocumentOrUri.asKey(document);\n const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates;\n return states.has(key);\n }\n getResultId(kind, document) {\n const key = DocumentOrUri.asKey(document);\n const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates;\n return states.get(key)?.resultId;\n }\n getAllResultIds() {\n const result = [];\n for (let [uri, value] of this.workspacePullStates) {\n if (this.documentPullStates.has(uri)) {\n value = this.documentPullStates.get(uri);\n }\n if (value.resultId !== undefined) {\n result.push({ uri, value: value.resultId });\n }\n }\n return result;\n }\n}\nclass DiagnosticRequestor {\n constructor(client, tabs, options) {\n this.client = client;\n this.tabs = tabs;\n this.options = options;\n this.isDisposed = false;\n this.onDidChangeDiagnosticsEmitter = new vscode_1.EventEmitter();\n this.provider = this.createProvider();\n this.diagnostics = vscode_1.languages.createDiagnosticCollection(options.identifier);\n this.openRequests = new Map();\n this.documentStates = new DocumentPullStateTracker();\n this.workspaceErrorCounter = 0;\n }\n knows(kind, document) {\n const uri = document instanceof vscode_1.Uri ? document : document.uri;\n return this.documentStates.tracks(kind, document) || this.openRequests.has(uri.toString());\n }\n forget(kind, document) {\n this.documentStates.unTrack(kind, document);\n }\n pull(document, cb) {\n if (this.isDisposed) {\n return;\n }\n const uri = document instanceof vscode_1.Uri ? document : document.uri;\n this.pullAsync(document).then(() => {\n if (cb) {\n cb();\n }\n }, (error) => {\n this.client.error(`Document pull failed for text document ${uri.toString()}`, error, false);\n });\n }\n async pullAsync(document, version) {\n if (this.isDisposed) {\n return;\n }\n const isUri = document instanceof vscode_1.Uri;\n const uri = isUri ? document : document.uri;\n const key = uri.toString();\n version = isUri ? version : document.version;\n const currentRequestState = this.openRequests.get(key);\n const documentState = isUri\n ? this.documentStates.track(PullState.document, document, version)\n : this.documentStates.track(PullState.document, document);\n if (currentRequestState === undefined) {\n const tokenSource = new vscode_1.CancellationTokenSource();\n this.openRequests.set(key, { state: RequestStateKind.active, document: document, version: version, tokenSource });\n let report;\n let afterState;\n try {\n report = await this.provider.provideDiagnostics(document, documentState.resultId, tokenSource.token) ?? { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] };\n }\n catch (error) {\n if (error instanceof features_1.LSPCancellationError && vscode_languageserver_protocol_1.DiagnosticServerCancellationData.is(error.data) && error.data.retriggerRequest === false) {\n afterState = { state: RequestStateKind.outDated, document };\n }\n if (afterState === undefined && error instanceof vscode_1.CancellationError) {\n afterState = { state: RequestStateKind.reschedule, document };\n }\n else {\n throw error;\n }\n }\n afterState = afterState ?? this.openRequests.get(key);\n if (afterState === undefined) {\n // This shouldn't happen. Log it\n this.client.error(`Lost request state in diagnostic pull model. Clearing diagnostics for ${key}`);\n this.diagnostics.delete(uri);\n return;\n }\n this.openRequests.delete(key);\n if (!this.tabs.isVisible(document)) {\n this.documentStates.unTrack(PullState.document, document);\n return;\n }\n if (afterState.state === RequestStateKind.outDated) {\n return;\n }\n // report is only undefined if the request has thrown.\n if (report !== undefined) {\n if (report.kind === vsdiag.DocumentDiagnosticReportKind.full) {\n this.diagnostics.set(uri, report.items);\n }\n documentState.pulledVersion = version;\n documentState.resultId = report.resultId;\n }\n if (afterState.state === RequestStateKind.reschedule) {\n this.pull(document);\n }\n }\n else {\n if (currentRequestState.state === RequestStateKind.active) {\n // Cancel the current request and reschedule a new one when the old one returned.\n currentRequestState.tokenSource.cancel();\n this.openRequests.set(key, { state: RequestStateKind.reschedule, document: currentRequestState.document });\n }\n else if (currentRequestState.state === RequestStateKind.outDated) {\n this.openRequests.set(key, { state: RequestStateKind.reschedule, document: currentRequestState.document });\n }\n }\n }\n forgetDocument(document) {\n const uri = document instanceof vscode_1.Uri ? document : document.uri;\n const key = uri.toString();\n const request = this.openRequests.get(key);\n if (this.options.workspaceDiagnostics) {\n // If we run workspace diagnostic pull a last time for the diagnostics\n // and the rely on getting them from the workspace result.\n if (request !== undefined) {\n this.openRequests.set(key, { state: RequestStateKind.reschedule, document: document });\n }\n else {\n this.pull(document, () => {\n this.forget(PullState.document, document);\n });\n }\n }\n else {\n // We have normal pull or inter file dependencies. In this case we\n // clear the diagnostics (to have the same start as after startup).\n // We also cancel outstanding requests.\n if (request !== undefined) {\n if (request.state === RequestStateKind.active) {\n request.tokenSource.cancel();\n }\n this.openRequests.set(key, { state: RequestStateKind.outDated, document: document });\n }\n this.diagnostics.delete(uri);\n this.forget(PullState.document, document);\n }\n }\n pullWorkspace() {\n if (this.isDisposed) {\n return;\n }\n this.pullWorkspaceAsync().then(() => {\n this.workspaceTimeout = (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(() => {\n this.pullWorkspace();\n }, 2000);\n }, (error) => {\n if (!(error instanceof features_1.LSPCancellationError) && !vscode_languageserver_protocol_1.DiagnosticServerCancellationData.is(error.data)) {\n this.client.error(`Workspace diagnostic pull failed.`, error, false);\n this.workspaceErrorCounter++;\n }\n if (this.workspaceErrorCounter <= 5) {\n this.workspaceTimeout = (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(() => {\n this.pullWorkspace();\n }, 2000);\n }\n });\n }\n async pullWorkspaceAsync() {\n if (!this.provider.provideWorkspaceDiagnostics || this.isDisposed) {\n return;\n }\n if (this.workspaceCancellation !== undefined) {\n this.workspaceCancellation.cancel();\n this.workspaceCancellation = undefined;\n }\n this.workspaceCancellation = new vscode_1.CancellationTokenSource();\n const previousResultIds = this.documentStates.getAllResultIds().map((item) => {\n return {\n uri: this.client.protocol2CodeConverter.asUri(item.uri),\n value: item.value\n };\n });\n await this.provider.provideWorkspaceDiagnostics(previousResultIds, this.workspaceCancellation.token, (chunk) => {\n if (!chunk || this.isDisposed) {\n return;\n }\n for (const item of chunk.items) {\n if (item.kind === vsdiag.DocumentDiagnosticReportKind.full) {\n // Favour document pull result over workspace results. So skip if it is tracked\n // as a document result.\n if (!this.documentStates.tracks(PullState.document, item.uri)) {\n this.diagnostics.set(item.uri, item.items);\n }\n }\n this.documentStates.update(PullState.workspace, item.uri, item.version ?? undefined, item.resultId);\n }\n });\n }\n createProvider() {\n const result = {\n onDidChangeDiagnostics: this.onDidChangeDiagnosticsEmitter.event,\n provideDiagnostics: (document, previousResultId, token) => {\n const provideDiagnostics = (document, previousResultId, token) => {\n const params = {\n identifier: this.options.identifier,\n textDocument: { uri: this.client.code2ProtocolConverter.asUri(document instanceof vscode_1.Uri ? document : document.uri) },\n previousResultId: previousResultId\n };\n if (this.isDisposed === true || !this.client.isRunning()) {\n return { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] };\n }\n return this.client.sendRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, params, token).then(async (result) => {\n if (result === undefined || result === null || this.isDisposed || token.isCancellationRequested) {\n return { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] };\n }\n if (result.kind === vscode_languageserver_protocol_1.DocumentDiagnosticReportKind.Full) {\n return { kind: vsdiag.DocumentDiagnosticReportKind.full, resultId: result.resultId, items: await this.client.protocol2CodeConverter.asDiagnostics(result.items, token) };\n }\n else {\n return { kind: vsdiag.DocumentDiagnosticReportKind.unChanged, resultId: result.resultId };\n }\n }, (error) => {\n return this.client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, token, error, { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] });\n });\n };\n const middleware = this.client.middleware;\n return middleware.provideDiagnostics\n ? middleware.provideDiagnostics(document, previousResultId, token, provideDiagnostics)\n : provideDiagnostics(document, previousResultId, token);\n }\n };\n if (this.options.workspaceDiagnostics) {\n result.provideWorkspaceDiagnostics = (resultIds, token, resultReporter) => {\n const convertReport = async (report) => {\n if (report.kind === vscode_languageserver_protocol_1.DocumentDiagnosticReportKind.Full) {\n return {\n kind: vsdiag.DocumentDiagnosticReportKind.full,\n uri: this.client.protocol2CodeConverter.asUri(report.uri),\n resultId: report.resultId,\n version: report.version,\n items: await this.client.protocol2CodeConverter.asDiagnostics(report.items, token)\n };\n }\n else {\n return {\n kind: vsdiag.DocumentDiagnosticReportKind.unChanged,\n uri: this.client.protocol2CodeConverter.asUri(report.uri),\n resultId: report.resultId,\n version: report.version\n };\n }\n };\n const convertPreviousResultIds = (resultIds) => {\n const converted = [];\n for (const item of resultIds) {\n converted.push({ uri: this.client.code2ProtocolConverter.asUri(item.uri), value: item.value });\n }\n return converted;\n };\n const provideDiagnostics = (resultIds, token) => {\n const partialResultToken = (0, uuid_1.generateUuid)();\n const disposable = this.client.onProgress(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.partialResult, partialResultToken, async (partialResult) => {\n if (partialResult === undefined || partialResult === null) {\n resultReporter(null);\n return;\n }\n const converted = {\n items: []\n };\n for (const item of partialResult.items) {\n try {\n converted.items.push(await convertReport(item));\n }\n catch (error) {\n this.client.error(`Converting workspace diagnostics failed.`, error);\n }\n }\n resultReporter(converted);\n });\n const params = {\n identifier: this.options.identifier,\n previousResultIds: convertPreviousResultIds(resultIds),\n partialResultToken: partialResultToken\n };\n if (this.isDisposed === true || !this.client.isRunning()) {\n return { items: [] };\n }\n return this.client.sendRequest(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.type, params, token).then(async (result) => {\n if (token.isCancellationRequested) {\n return { items: [] };\n }\n const converted = {\n items: []\n };\n for (const item of result.items) {\n converted.items.push(await convertReport(item));\n }\n disposable.dispose();\n resultReporter(converted);\n return { items: [] };\n }, (error) => {\n disposable.dispose();\n return this.client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, token, error, { items: [] });\n });\n };\n const middleware = this.client.middleware;\n return middleware.provideWorkspaceDiagnostics\n ? middleware.provideWorkspaceDiagnostics(resultIds, token, resultReporter, provideDiagnostics)\n : provideDiagnostics(resultIds, token, resultReporter);\n };\n }\n return result;\n }\n dispose() {\n this.isDisposed = true;\n // Cancel and clear workspace pull if present.\n this.workspaceCancellation?.cancel();\n this.workspaceTimeout?.dispose();\n // Cancel all request and mark open requests as outdated.\n for (const [key, request] of this.openRequests) {\n if (request.state === RequestStateKind.active) {\n request.tokenSource.cancel();\n }\n this.openRequests.set(key, { state: RequestStateKind.outDated, document: request.document });\n }\n // cleanup old diagnostics\n this.diagnostics.dispose();\n }\n}\nclass BackgroundScheduler {\n constructor(diagnosticRequestor) {\n this.diagnosticRequestor = diagnosticRequestor;\n this.documents = new vscode_languageserver_protocol_1.LinkedMap();\n this.isDisposed = false;\n }\n add(document) {\n if (this.isDisposed === true) {\n return;\n }\n const key = DocumentOrUri.asKey(document);\n if (this.documents.has(key)) {\n return;\n }\n this.documents.set(key, document, vscode_languageserver_protocol_1.Touch.Last);\n this.trigger();\n }\n remove(document) {\n const key = DocumentOrUri.asKey(document);\n this.documents.delete(key);\n // No more documents. Stop background activity.\n if (this.documents.size === 0) {\n this.stop();\n }\n else if (key === this.endDocumentKey()) {\n // Make sure we have a correct last document. It could have\n this.endDocument = this.documents.last;\n }\n }\n trigger() {\n if (this.isDisposed === true) {\n return;\n }\n // We have a round running. So simply make sure we run up to the\n // last document\n if (this.intervalHandle !== undefined) {\n this.endDocument = this.documents.last;\n return;\n }\n this.endDocument = this.documents.last;\n this.intervalHandle = (0, vscode_languageserver_protocol_1.RAL)().timer.setInterval(() => {\n const document = this.documents.first;\n if (document !== undefined) {\n const key = DocumentOrUri.asKey(document);\n this.diagnosticRequestor.pull(document);\n this.documents.set(key, document, vscode_languageserver_protocol_1.Touch.Last);\n if (key === this.endDocumentKey()) {\n this.stop();\n }\n }\n }, 200);\n }\n dispose() {\n this.isDisposed = true;\n this.stop();\n this.documents.clear();\n }\n stop() {\n this.intervalHandle?.dispose();\n this.intervalHandle = undefined;\n this.endDocument = undefined;\n }\n endDocumentKey() {\n return this.endDocument !== undefined ? DocumentOrUri.asKey(this.endDocument) : undefined;\n }\n}\nclass DiagnosticFeatureProviderImpl {\n constructor(client, tabs, options) {\n const diagnosticPullOptions = client.clientOptions.diagnosticPullOptions ?? { onChange: true, onSave: false };\n const documentSelector = client.protocol2CodeConverter.asDocumentSelector(options.documentSelector);\n const disposables = [];\n const matchResource = (resource) => {\n const selector = options.documentSelector;\n if (diagnosticPullOptions.match !== undefined) {\n return diagnosticPullOptions.match(selector, resource);\n }\n for (const filter of selector) {\n if (!vscode_languageserver_protocol_1.TextDocumentFilter.is(filter)) {\n continue;\n }\n // The filter is a language id. We can't determine if it matches\n // so we return false.\n if (typeof filter === 'string') {\n return false;\n }\n if (filter.language !== undefined && filter.language !== '*') {\n return false;\n }\n if (filter.scheme !== undefined && filter.scheme !== '*' && filter.scheme !== resource.scheme) {\n return false;\n }\n if (filter.pattern !== undefined) {\n const matcher = new minimatch.Minimatch(filter.pattern, { noext: true });\n if (!matcher.makeRe()) {\n return false;\n }\n if (!matcher.match(resource.fsPath)) {\n return false;\n }\n }\n }\n return true;\n };\n const matches = (document) => {\n return document instanceof vscode_1.Uri\n ? matchResource(document)\n : vscode_1.languages.match(documentSelector, document) > 0 && tabs.isVisible(document);\n };\n const isActiveDocument = (document) => {\n return document instanceof vscode_1.Uri\n ? this.activeTextDocument?.uri.toString() === document.toString()\n : this.activeTextDocument === document;\n };\n this.diagnosticRequestor = new DiagnosticRequestor(client, tabs, options);\n this.backgroundScheduler = new BackgroundScheduler(this.diagnosticRequestor);\n const addToBackgroundIfNeeded = (document) => {\n if (!matches(document) || !options.interFileDependencies || isActiveDocument(document)) {\n return;\n }\n this.backgroundScheduler.add(document);\n };\n this.activeTextDocument = vscode_1.window.activeTextEditor?.document;\n vscode_1.window.onDidChangeActiveTextEditor((editor) => {\n const oldActive = this.activeTextDocument;\n this.activeTextDocument = editor?.document;\n if (oldActive !== undefined) {\n addToBackgroundIfNeeded(oldActive);\n }\n if (this.activeTextDocument !== undefined) {\n this.backgroundScheduler.remove(this.activeTextDocument);\n }\n });\n // For pull model diagnostics we pull for documents visible in the UI.\n // From an eventing point of view we still rely on open document events\n // and filter the documents that are not visible in the UI instead of\n // listening to Tab events. Major reason is event timing since we need\n // to ensure that the pull is send after the document open has reached\n // the server.\n // We always pull on open.\n const openFeature = client.getFeature(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.method);\n disposables.push(openFeature.onNotificationSent((event) => {\n const textDocument = event.textDocument;\n // We already know about this document. This can happen via a tab open.\n if (this.diagnosticRequestor.knows(PullState.document, textDocument)) {\n return;\n }\n if (matches(textDocument)) {\n this.diagnosticRequestor.pull(textDocument, () => { addToBackgroundIfNeeded(textDocument); });\n }\n }));\n disposables.push(tabs.onOpen((opened) => {\n for (const resource of opened) {\n // We already know about this document. This can happen via a document open.\n if (this.diagnosticRequestor.knows(PullState.document, resource)) {\n continue;\n }\n const uriStr = resource.toString();\n let textDocument;\n for (const item of vscode_1.workspace.textDocuments) {\n if (uriStr === item.uri.toString()) {\n textDocument = item;\n break;\n }\n }\n // In VS Code the event timing is as follows:\n // 1. tab events are fired.\n // 2. open document events are fired and internal data structures like\n // workspace.textDocuments and Window.activeTextEditor are updated.\n //\n // This means: for newly created tab/editors we don't find the underlying\n // document yet. So we do nothing an rely on the underlying open document event\n // to be fired.\n if (textDocument !== undefined && matches(textDocument)) {\n this.diagnosticRequestor.pull(textDocument, () => { addToBackgroundIfNeeded(textDocument); });\n }\n }\n }));\n // Pull all diagnostics for documents that are already open\n const pulledTextDocuments = new Set();\n for (const textDocument of vscode_1.workspace.textDocuments) {\n if (matches(textDocument)) {\n this.diagnosticRequestor.pull(textDocument, () => { addToBackgroundIfNeeded(textDocument); });\n pulledTextDocuments.add(textDocument.uri.toString());\n }\n }\n // Pull all tabs if not already pulled as text document\n if (diagnosticPullOptions.onTabs === true) {\n for (const resource of tabs.getTabResources()) {\n if (!pulledTextDocuments.has(resource.toString()) && matches(resource)) {\n this.diagnosticRequestor.pull(resource, () => { addToBackgroundIfNeeded(resource); });\n }\n }\n }\n // We don't need to pull on tab open since we will receive a document open as well later on\n // and that event allows us to use a document for a match check which will have a set\n // language id.\n if (diagnosticPullOptions.onChange === true) {\n const changeFeature = client.getFeature(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.method);\n disposables.push(changeFeature.onNotificationSent(async (event) => {\n const textDocument = event.textDocument;\n if ((diagnosticPullOptions.filter === undefined || !diagnosticPullOptions.filter(textDocument, DiagnosticPullMode.onType)) && this.diagnosticRequestor.knows(PullState.document, textDocument)) {\n this.diagnosticRequestor.pull(textDocument, () => { this.backgroundScheduler.trigger(); });\n }\n }));\n }\n if (diagnosticPullOptions.onSave === true) {\n const saveFeature = client.getFeature(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.method);\n disposables.push(saveFeature.onNotificationSent((event) => {\n const textDocument = event.textDocument;\n if ((diagnosticPullOptions.filter === undefined || !diagnosticPullOptions.filter(textDocument, DiagnosticPullMode.onSave)) && this.diagnosticRequestor.knows(PullState.document, textDocument)) {\n this.diagnosticRequestor.pull(event.textDocument, () => { this.backgroundScheduler.trigger(); });\n }\n }));\n }\n // When the document closes clear things up\n const closeFeature = client.getFeature(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.method);\n disposables.push(closeFeature.onNotificationSent((event) => {\n this.cleanUpDocument(event.textDocument);\n }));\n // Same when a tabs closes.\n tabs.onClose((closed) => {\n for (const document of closed) {\n this.cleanUpDocument(document);\n }\n });\n // We received a did change from the server.\n this.diagnosticRequestor.onDidChangeDiagnosticsEmitter.event(() => {\n for (const textDocument of vscode_1.workspace.textDocuments) {\n if (matches(textDocument)) {\n this.diagnosticRequestor.pull(textDocument);\n }\n }\n });\n // da348dc5-c30a-4515-9d98-31ff3be38d14 is the test UUID to test the middle ware. So don't auto trigger pulls.\n if (options.workspaceDiagnostics === true && options.identifier !== 'da348dc5-c30a-4515-9d98-31ff3be38d14') {\n this.diagnosticRequestor.pullWorkspace();\n }\n this.disposable = vscode_1.Disposable.from(...disposables, this.backgroundScheduler, this.diagnosticRequestor);\n }\n get onDidChangeDiagnosticsEmitter() {\n return this.diagnosticRequestor.onDidChangeDiagnosticsEmitter;\n }\n get diagnostics() {\n return this.diagnosticRequestor.provider;\n }\n cleanUpDocument(document) {\n if (this.diagnosticRequestor.knows(PullState.document, document)) {\n this.diagnosticRequestor.forgetDocument(document);\n this.backgroundScheduler.remove(document);\n }\n }\n}\nclass DiagnosticFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type);\n }\n fillClientCapabilities(capabilities) {\n let capability = ensure(ensure(capabilities, 'textDocument'), 'diagnostic');\n capability.dynamicRegistration = true;\n // We first need to decide how a UI will look with related documents.\n // An easy implementation would be to only show related diagnostics for\n // the active editor.\n capability.relatedDocumentSupport = false;\n ensure(ensure(capabilities, 'workspace'), 'diagnostics').refreshSupport = true;\n }\n initialize(capabilities, documentSelector) {\n const client = this._client;\n client.onRequest(vscode_languageserver_protocol_1.DiagnosticRefreshRequest.type, async () => {\n for (const provider of this.getAllProviders()) {\n provider.onDidChangeDiagnosticsEmitter.fire();\n }\n });\n let [id, options] = this.getRegistration(documentSelector, capabilities.diagnosticProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n clear() {\n if (this.tabs !== undefined) {\n this.tabs.dispose();\n this.tabs = undefined;\n }\n super.clear();\n }\n registerLanguageProvider(options) {\n if (this.tabs === undefined) {\n this.tabs = new Tabs();\n }\n const provider = new DiagnosticFeatureProviderImpl(this._client, this.tabs, options);\n return [provider.disposable, provider];\n }\n}\nexports.DiagnosticFeature = DiagnosticFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NotebookDocumentSyncFeature = void 0;\nconst vscode = require(\"vscode\");\nconst minimatch = require(\"minimatch\");\nconst proto = require(\"vscode-languageserver-protocol\");\nconst UUID = require(\"./utils/uuid\");\nconst Is = require(\"./utils/is\");\nfunction ensure(target, key) {\n if (target[key] === void 0) {\n target[key] = {};\n }\n return target[key];\n}\nvar Converter;\n(function (Converter) {\n let c2p;\n (function (c2p) {\n function asVersionedNotebookDocumentIdentifier(notebookDocument, base) {\n return {\n version: notebookDocument.version,\n uri: base.asUri(notebookDocument.uri)\n };\n }\n c2p.asVersionedNotebookDocumentIdentifier = asVersionedNotebookDocumentIdentifier;\n function asNotebookDocument(notebookDocument, cells, base) {\n const result = proto.NotebookDocument.create(base.asUri(notebookDocument.uri), notebookDocument.notebookType, notebookDocument.version, asNotebookCells(cells, base));\n if (Object.keys(notebookDocument.metadata).length > 0) {\n result.metadata = asMetadata(notebookDocument.metadata);\n }\n return result;\n }\n c2p.asNotebookDocument = asNotebookDocument;\n function asNotebookCells(cells, base) {\n return cells.map(cell => asNotebookCell(cell, base));\n }\n c2p.asNotebookCells = asNotebookCells;\n function asMetadata(metadata) {\n const seen = new Set();\n return deepCopy(seen, metadata);\n }\n c2p.asMetadata = asMetadata;\n function asNotebookCell(cell, base) {\n const result = proto.NotebookCell.create(asNotebookCellKind(cell.kind), base.asUri(cell.document.uri));\n if (Object.keys(cell.metadata).length > 0) {\n result.metadata = asMetadata(cell.metadata);\n }\n if (cell.executionSummary !== undefined && (Is.number(cell.executionSummary.executionOrder) && Is.boolean(cell.executionSummary.success))) {\n result.executionSummary = {\n executionOrder: cell.executionSummary.executionOrder,\n success: cell.executionSummary.success\n };\n }\n return result;\n }\n c2p.asNotebookCell = asNotebookCell;\n function asNotebookCellKind(kind) {\n switch (kind) {\n case vscode.NotebookCellKind.Markup:\n return proto.NotebookCellKind.Markup;\n case vscode.NotebookCellKind.Code:\n return proto.NotebookCellKind.Code;\n }\n }\n function deepCopy(seen, value) {\n if (seen.has(value)) {\n throw new Error(`Can't deep copy cyclic structures.`);\n }\n if (Array.isArray(value)) {\n const result = [];\n for (const elem of value) {\n if (elem !== null && typeof elem === 'object' || Array.isArray(elem)) {\n result.push(deepCopy(seen, elem));\n }\n else {\n if (elem instanceof RegExp) {\n throw new Error(`Can't transfer regular expressions to the server`);\n }\n result.push(elem);\n }\n }\n return result;\n }\n else {\n const props = Object.keys(value);\n const result = Object.create(null);\n for (const prop of props) {\n const elem = value[prop];\n if (elem !== null && typeof elem === 'object' || Array.isArray(elem)) {\n result[prop] = deepCopy(seen, elem);\n }\n else {\n if (elem instanceof RegExp) {\n throw new Error(`Can't transfer regular expressions to the server`);\n }\n result[prop] = elem;\n }\n }\n return result;\n }\n }\n function asTextContentChange(event, base) {\n const params = base.asChangeTextDocumentParams(event, event.document.uri, event.document.version);\n return { document: params.textDocument, changes: params.contentChanges };\n }\n c2p.asTextContentChange = asTextContentChange;\n function asNotebookDocumentChangeEvent(event, base) {\n const result = Object.create(null);\n if (event.metadata) {\n result.metadata = Converter.c2p.asMetadata(event.metadata);\n }\n if (event.cells !== undefined) {\n const cells = Object.create(null);\n const changedCells = event.cells;\n if (changedCells.structure) {\n cells.structure = {\n array: {\n start: changedCells.structure.array.start,\n deleteCount: changedCells.structure.array.deleteCount,\n cells: changedCells.structure.array.cells !== undefined ? changedCells.structure.array.cells.map(cell => Converter.c2p.asNotebookCell(cell, base)) : undefined\n },\n didOpen: changedCells.structure.didOpen !== undefined\n ? changedCells.structure.didOpen.map(cell => base.asOpenTextDocumentParams(cell.document).textDocument)\n : undefined,\n didClose: changedCells.structure.didClose !== undefined\n ? changedCells.structure.didClose.map(cell => base.asCloseTextDocumentParams(cell.document).textDocument)\n : undefined\n };\n }\n if (changedCells.data !== undefined) {\n cells.data = changedCells.data.map(cell => Converter.c2p.asNotebookCell(cell, base));\n }\n if (changedCells.textContent !== undefined) {\n cells.textContent = changedCells.textContent.map(event => Converter.c2p.asTextContentChange(event, base));\n }\n if (Object.keys(cells).length > 0) {\n result.cells = cells;\n }\n }\n return result;\n }\n c2p.asNotebookDocumentChangeEvent = asNotebookDocumentChangeEvent;\n })(c2p = Converter.c2p || (Converter.c2p = {}));\n})(Converter || (Converter = {}));\nvar $NotebookCell;\n(function ($NotebookCell) {\n function computeDiff(originalCells, modifiedCells, compareMetadata) {\n const originalLength = originalCells.length;\n const modifiedLength = modifiedCells.length;\n let startIndex = 0;\n while (startIndex < modifiedLength && startIndex < originalLength && equals(originalCells[startIndex], modifiedCells[startIndex], compareMetadata)) {\n startIndex++;\n }\n if (startIndex < modifiedLength && startIndex < originalLength) {\n let originalEndIndex = originalLength - 1;\n let modifiedEndIndex = modifiedLength - 1;\n while (originalEndIndex >= 0 && modifiedEndIndex >= 0 && equals(originalCells[originalEndIndex], modifiedCells[modifiedEndIndex], compareMetadata)) {\n originalEndIndex--;\n modifiedEndIndex--;\n }\n const deleteCount = (originalEndIndex + 1) - startIndex;\n const newCells = startIndex === modifiedEndIndex + 1 ? undefined : modifiedCells.slice(startIndex, modifiedEndIndex + 1);\n return newCells !== undefined ? { start: startIndex, deleteCount, cells: newCells } : { start: startIndex, deleteCount };\n }\n else if (startIndex < modifiedLength) {\n return { start: startIndex, deleteCount: 0, cells: modifiedCells.slice(startIndex) };\n }\n else if (startIndex < originalLength) {\n return { start: startIndex, deleteCount: originalLength - startIndex };\n }\n else {\n // The two arrays are the same.\n return undefined;\n }\n }\n $NotebookCell.computeDiff = computeDiff;\n /**\n * We only sync kind, document, execution and metadata to the server. So we only need to compare those.\n */\n function equals(one, other, compareMetaData = true) {\n if (one.kind !== other.kind || one.document.uri.toString() !== other.document.uri.toString() || one.document.languageId !== other.document.languageId ||\n !equalsExecution(one.executionSummary, other.executionSummary)) {\n return false;\n }\n return !compareMetaData || (compareMetaData && equalsMetadata(one.metadata, other.metadata));\n }\n function equalsExecution(one, other) {\n if (one === other) {\n return true;\n }\n if (one === undefined || other === undefined) {\n return false;\n }\n return one.executionOrder === other.executionOrder && one.success === other.success && equalsTiming(one.timing, other.timing);\n }\n function equalsTiming(one, other) {\n if (one === other) {\n return true;\n }\n if (one === undefined || other === undefined) {\n return false;\n }\n return one.startTime === other.startTime && one.endTime === other.endTime;\n }\n function equalsMetadata(one, other) {\n if (one === other) {\n return true;\n }\n if (one === null || one === undefined || other === null || other === undefined) {\n return false;\n }\n if (typeof one !== typeof other) {\n return false;\n }\n if (typeof one !== 'object') {\n return false;\n }\n const oneArray = Array.isArray(one);\n const otherArray = Array.isArray(other);\n if (oneArray !== otherArray) {\n return false;\n }\n if (oneArray && otherArray) {\n if (one.length !== other.length) {\n return false;\n }\n for (let i = 0; i < one.length; i++) {\n if (!equalsMetadata(one[i], other[i])) {\n return false;\n }\n }\n }\n if (isObjectLiteral(one) && isObjectLiteral(other)) {\n const oneKeys = Object.keys(one);\n const otherKeys = Object.keys(other);\n if (oneKeys.length !== otherKeys.length) {\n return false;\n }\n oneKeys.sort();\n otherKeys.sort();\n if (!equalsMetadata(oneKeys, otherKeys)) {\n return false;\n }\n for (let i = 0; i < oneKeys.length; i++) {\n const prop = oneKeys[i];\n if (!equalsMetadata(one[prop], other[prop])) {\n return false;\n }\n }\n return true;\n }\n return false;\n }\n function isObjectLiteral(value) {\n return value !== null && typeof value === 'object';\n }\n $NotebookCell.isObjectLiteral = isObjectLiteral;\n})($NotebookCell || ($NotebookCell = {}));\nvar $NotebookDocumentFilter;\n(function ($NotebookDocumentFilter) {\n function matchNotebook(filter, notebookDocument) {\n if (typeof filter === 'string') {\n return filter === '*' || notebookDocument.notebookType === filter;\n }\n if (filter.notebookType !== undefined && filter.notebookType !== '*' && notebookDocument.notebookType !== filter.notebookType) {\n return false;\n }\n const uri = notebookDocument.uri;\n if (filter.scheme !== undefined && filter.scheme !== '*' && uri.scheme !== filter.scheme) {\n return false;\n }\n if (filter.pattern !== undefined) {\n const matcher = new minimatch.Minimatch(filter.pattern, { noext: true });\n if (!matcher.makeRe()) {\n return false;\n }\n if (!matcher.match(uri.fsPath)) {\n return false;\n }\n }\n return true;\n }\n $NotebookDocumentFilter.matchNotebook = matchNotebook;\n})($NotebookDocumentFilter || ($NotebookDocumentFilter = {}));\nvar $NotebookDocumentSyncOptions;\n(function ($NotebookDocumentSyncOptions) {\n function asDocumentSelector(options) {\n const selector = options.notebookSelector;\n const result = [];\n for (const element of selector) {\n const notebookType = (typeof element.notebook === 'string' ? element.notebook : element.notebook?.notebookType) ?? '*';\n const scheme = (typeof element.notebook === 'string') ? undefined : element.notebook?.scheme;\n const pattern = (typeof element.notebook === 'string') ? undefined : element.notebook?.pattern;\n if (element.cells !== undefined) {\n for (const cell of element.cells) {\n result.push(asDocumentFilter(notebookType, scheme, pattern, cell.language));\n }\n }\n else {\n result.push(asDocumentFilter(notebookType, scheme, pattern, undefined));\n }\n }\n return result;\n }\n $NotebookDocumentSyncOptions.asDocumentSelector = asDocumentSelector;\n function asDocumentFilter(notebookType, scheme, pattern, language) {\n return scheme === undefined && pattern === undefined\n ? { notebook: notebookType, language }\n : { notebook: { notebookType, scheme, pattern }, language };\n }\n})($NotebookDocumentSyncOptions || ($NotebookDocumentSyncOptions = {}));\nvar SyncInfo;\n(function (SyncInfo) {\n function create(cells) {\n return {\n cells,\n uris: new Set(cells.map(cell => cell.document.uri.toString()))\n };\n }\n SyncInfo.create = create;\n})(SyncInfo || (SyncInfo = {}));\nclass NotebookDocumentSyncFeatureProvider {\n constructor(client, options) {\n this.client = client;\n this.options = options;\n this.notebookSyncInfo = new Map();\n this.notebookDidOpen = new Set();\n this.disposables = [];\n this.selector = client.protocol2CodeConverter.asDocumentSelector($NotebookDocumentSyncOptions.asDocumentSelector(options));\n // open\n vscode.workspace.onDidOpenNotebookDocument((notebookDocument) => {\n this.notebookDidOpen.add(notebookDocument.uri.toString());\n this.didOpen(notebookDocument);\n }, undefined, this.disposables);\n for (const notebookDocument of vscode.workspace.notebookDocuments) {\n this.notebookDidOpen.add(notebookDocument.uri.toString());\n this.didOpen(notebookDocument);\n }\n // Notebook document changed.\n vscode.workspace.onDidChangeNotebookDocument(event => this.didChangeNotebookDocument(event), undefined, this.disposables);\n //save\n if (this.options.save === true) {\n vscode.workspace.onDidSaveNotebookDocument(notebookDocument => this.didSave(notebookDocument), undefined, this.disposables);\n }\n // close\n vscode.workspace.onDidCloseNotebookDocument((notebookDocument) => {\n this.didClose(notebookDocument);\n this.notebookDidOpen.delete(notebookDocument.uri.toString());\n }, undefined, this.disposables);\n }\n getState() {\n for (const notebook of vscode.workspace.notebookDocuments) {\n const matchingCells = this.getMatchingCells(notebook);\n if (matchingCells !== undefined) {\n return { kind: 'document', id: '$internal', registrations: true, matches: true };\n }\n }\n return { kind: 'document', id: '$internal', registrations: true, matches: false };\n }\n get mode() {\n return 'notebook';\n }\n handles(textDocument) {\n return vscode.languages.match(this.selector, textDocument) > 0;\n }\n didOpenNotebookCellTextDocument(notebookDocument, cell) {\n if (vscode.languages.match(this.selector, cell.document) === 0) {\n return;\n }\n if (!this.notebookDidOpen.has(notebookDocument.uri.toString())) {\n // We have never received an open notification for the notebook document.\n // VS Code guarantees that we first get cell document open and then\n // notebook open. So simply wait for the notebook open.\n return;\n }\n const syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString());\n // In VS Code we receive a notebook open before a cell document open.\n // The document and the cell is synced.\n const cellMatches = this.cellMatches(notebookDocument, cell);\n if (syncInfo !== undefined) {\n const cellIsSynced = syncInfo.uris.has(cell.document.uri.toString());\n if ((cellMatches && cellIsSynced) || (!cellMatches && !cellIsSynced)) {\n // The cell doesn't match and was not synced or it matches and is synced.\n // In both cases nothing to do.\n //\n // Note that if the language mode of a document changes we remove the\n // cell and add it back to update the language mode on the server side.\n return;\n }\n if (cellMatches) {\n // don't use cells from above since there might be more matching cells in the notebook\n // Since we had a matching cell above we will have matching cells now.\n const matchingCells = this.getMatchingCells(notebookDocument);\n if (matchingCells !== undefined) {\n const event = this.asNotebookDocumentChangeEvent(notebookDocument, undefined, syncInfo, matchingCells);\n if (event !== undefined) {\n this.doSendChange(event, matchingCells).catch(() => { });\n }\n }\n }\n }\n else {\n // No sync info. But we have a open event for the notebook document\n // itself. If the cell matches then we need to send an open with\n // exactly that cell.\n if (cellMatches) {\n this.doSendOpen(notebookDocument, [cell]).catch(() => { });\n }\n }\n }\n didChangeNotebookCellTextDocument(notebookDocument, event) {\n // No match with the selector\n if (vscode.languages.match(this.selector, event.document) === 0) {\n return;\n }\n this.doSendChange({\n notebook: notebookDocument,\n cells: { textContent: [event] }\n }, undefined).catch(() => { });\n }\n didCloseNotebookCellTextDocument(notebookDocument, cell) {\n const syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString());\n if (syncInfo === undefined) {\n // The notebook document got never synced. So it doesn't matter if a cell\n // document closes.\n return;\n }\n const cellUri = cell.document.uri;\n const index = syncInfo.cells.findIndex((item) => item.document.uri.toString() === cellUri.toString());\n if (index === -1) {\n // The cell never got synced or it got deleted and we now received the document\n // close event.\n return;\n }\n if (index === 0 && syncInfo.cells.length === 1) {\n // The last cell. Close the notebook document in the server.\n this.doSendClose(notebookDocument, syncInfo.cells).catch(() => { });\n }\n else {\n const newCells = syncInfo.cells.slice();\n const deleted = newCells.splice(index, 1);\n this.doSendChange({\n notebook: notebookDocument,\n cells: {\n structure: {\n array: { start: index, deleteCount: 1 },\n didClose: deleted\n }\n }\n }, newCells).catch(() => { });\n }\n }\n dispose() {\n for (const disposable of this.disposables) {\n disposable.dispose();\n }\n }\n didOpen(notebookDocument, matchingCells = this.getMatchingCells(notebookDocument), syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString())) {\n if (syncInfo !== undefined) {\n if (matchingCells !== undefined) {\n const event = this.asNotebookDocumentChangeEvent(notebookDocument, undefined, syncInfo, matchingCells);\n if (event !== undefined) {\n this.doSendChange(event, matchingCells).catch(() => { });\n }\n }\n else {\n this.doSendClose(notebookDocument, []).catch(() => { });\n }\n }\n else {\n // Check if we need to sync the notebook document.\n if (matchingCells === undefined) {\n return;\n }\n this.doSendOpen(notebookDocument, matchingCells).catch(() => { });\n }\n }\n didChangeNotebookDocument(event) {\n const notebookDocument = event.notebook;\n const syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString());\n if (syncInfo === undefined) {\n // We have no changes to the cells. Since the notebook wasn't synced\n // it will not be synced now.\n if (event.contentChanges.length === 0) {\n return;\n }\n // Check if we have new matching cells.\n const cells = this.getMatchingCells(notebookDocument);\n // No matching cells and the notebook never synced. So still no need\n // to sync it.\n if (cells === undefined) {\n return;\n }\n // Open the notebook document and ignore the rest of the changes\n // this the notebooks will be synced with the correct settings.\n this.didOpen(notebookDocument, cells, syncInfo);\n }\n else {\n // The notebook is synced. First check if we have no matching\n // cells anymore and if so close the notebook\n const cells = this.getMatchingCells(notebookDocument);\n if (cells === undefined) {\n this.didClose(notebookDocument, syncInfo);\n return;\n }\n const newEvent = this.asNotebookDocumentChangeEvent(event.notebook, event, syncInfo, cells);\n if (newEvent !== undefined) {\n this.doSendChange(newEvent, cells).catch(() => { });\n }\n }\n }\n didSave(notebookDocument) {\n const syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString());\n if (syncInfo === undefined) {\n return;\n }\n this.doSendSave(notebookDocument).catch(() => { });\n }\n didClose(notebookDocument, syncInfo = this.notebookSyncInfo.get(notebookDocument.uri.toString())) {\n if (syncInfo === undefined) {\n return;\n }\n const syncedCells = notebookDocument.getCells().filter(cell => syncInfo.uris.has(cell.document.uri.toString()));\n this.doSendClose(notebookDocument, syncedCells).catch(() => { });\n }\n async sendDidOpenNotebookDocument(notebookDocument) {\n const cells = this.getMatchingCells(notebookDocument);\n if (cells === undefined) {\n return;\n }\n return this.doSendOpen(notebookDocument, cells);\n }\n async doSendOpen(notebookDocument, cells) {\n const send = async (notebookDocument, cells) => {\n const nb = Converter.c2p.asNotebookDocument(notebookDocument, cells, this.client.code2ProtocolConverter);\n const cellDocuments = cells.map(cell => this.client.code2ProtocolConverter.asTextDocumentItem(cell.document));\n try {\n await this.client.sendNotification(proto.DidOpenNotebookDocumentNotification.type, {\n notebookDocument: nb,\n cellTextDocuments: cellDocuments\n });\n }\n catch (error) {\n this.client.error('Sending DidOpenNotebookDocumentNotification failed', error);\n throw error;\n }\n };\n const middleware = this.client.middleware?.notebooks;\n this.notebookSyncInfo.set(notebookDocument.uri.toString(), SyncInfo.create(cells));\n return middleware?.didOpen !== undefined ? middleware.didOpen(notebookDocument, cells, send) : send(notebookDocument, cells);\n }\n async sendDidChangeNotebookDocument(event) {\n return this.doSendChange(event, undefined);\n }\n async doSendChange(event, cells = this.getMatchingCells(event.notebook)) {\n const send = async (event) => {\n try {\n await this.client.sendNotification(proto.DidChangeNotebookDocumentNotification.type, {\n notebookDocument: Converter.c2p.asVersionedNotebookDocumentIdentifier(event.notebook, this.client.code2ProtocolConverter),\n change: Converter.c2p.asNotebookDocumentChangeEvent(event, this.client.code2ProtocolConverter)\n });\n }\n catch (error) {\n this.client.error('Sending DidChangeNotebookDocumentNotification failed', error);\n throw error;\n }\n };\n const middleware = this.client.middleware?.notebooks;\n if (event.cells?.structure !== undefined) {\n this.notebookSyncInfo.set(event.notebook.uri.toString(), SyncInfo.create(cells ?? []));\n }\n return middleware?.didChange !== undefined ? middleware?.didChange(event, send) : send(event);\n }\n async sendDidSaveNotebookDocument(notebookDocument) {\n return this.doSendSave(notebookDocument);\n }\n async doSendSave(notebookDocument) {\n const send = async (notebookDocument) => {\n try {\n await this.client.sendNotification(proto.DidSaveNotebookDocumentNotification.type, {\n notebookDocument: { uri: this.client.code2ProtocolConverter.asUri(notebookDocument.uri) }\n });\n }\n catch (error) {\n this.client.error('Sending DidSaveNotebookDocumentNotification failed', error);\n throw error;\n }\n };\n const middleware = this.client.middleware?.notebooks;\n return middleware?.didSave !== undefined ? middleware.didSave(notebookDocument, send) : send(notebookDocument);\n }\n async sendDidCloseNotebookDocument(notebookDocument) {\n return this.doSendClose(notebookDocument, this.getMatchingCells(notebookDocument) ?? []);\n }\n async doSendClose(notebookDocument, cells) {\n const send = async (notebookDocument, cells) => {\n try {\n await this.client.sendNotification(proto.DidCloseNotebookDocumentNotification.type, {\n notebookDocument: { uri: this.client.code2ProtocolConverter.asUri(notebookDocument.uri) },\n cellTextDocuments: cells.map(cell => this.client.code2ProtocolConverter.asTextDocumentIdentifier(cell.document))\n });\n }\n catch (error) {\n this.client.error('Sending DidCloseNotebookDocumentNotification failed', error);\n throw error;\n }\n };\n const middleware = this.client.middleware?.notebooks;\n this.notebookSyncInfo.delete(notebookDocument.uri.toString());\n return middleware?.didClose !== undefined ? middleware.didClose(notebookDocument, cells, send) : send(notebookDocument, cells);\n }\n asNotebookDocumentChangeEvent(notebook, event, syncInfo, matchingCells) {\n if (event !== undefined && event.notebook !== notebook) {\n throw new Error('Notebook must be identical');\n }\n const result = {\n notebook: notebook\n };\n if (event?.metadata !== undefined) {\n result.metadata = Converter.c2p.asMetadata(event.metadata);\n }\n let matchingCellsSet;\n if (event?.cellChanges !== undefined && event.cellChanges.length > 0) {\n const data = [];\n // Only consider the new matching cells.\n matchingCellsSet = new Set(matchingCells.map(cell => cell.document.uri.toString()));\n for (const cellChange of event.cellChanges) {\n if (matchingCellsSet.has(cellChange.cell.document.uri.toString()) && (cellChange.executionSummary !== undefined || cellChange.metadata !== undefined)) {\n data.push(cellChange.cell);\n }\n }\n if (data.length > 0) {\n result.cells = result.cells ?? {};\n result.cells.data = data;\n }\n }\n if (((event?.contentChanges !== undefined && event.contentChanges.length > 0) || event === undefined) && syncInfo !== undefined && matchingCells !== undefined) {\n // We still have matching cells. Check if the cell changes\n // affect the notebook on the server side.\n const oldCells = syncInfo.cells;\n const newCells = matchingCells;\n // meta data changes are reported using on the cell itself. So we can ignore comparing\n // it which has a positive effect on performance.\n const diff = $NotebookCell.computeDiff(oldCells, newCells, false);\n let addedCells;\n let removedCells;\n if (diff !== undefined) {\n addedCells = diff.cells === undefined\n ? new Map()\n : new Map(diff.cells.map(cell => [cell.document.uri.toString(), cell]));\n removedCells = diff.deleteCount === 0\n ? new Map()\n : new Map(oldCells.slice(diff.start, diff.start + diff.deleteCount).map(cell => [cell.document.uri.toString(), cell]));\n // Remove the onces that got deleted and inserted again.\n for (const key of Array.from(removedCells.keys())) {\n if (addedCells.has(key)) {\n removedCells.delete(key);\n addedCells.delete(key);\n }\n }\n result.cells = result.cells ?? {};\n const didOpen = [];\n const didClose = [];\n if (addedCells.size > 0 || removedCells.size > 0) {\n for (const cell of addedCells.values()) {\n didOpen.push(cell);\n }\n for (const cell of removedCells.values()) {\n didClose.push(cell);\n }\n }\n result.cells.structure = {\n array: diff,\n didOpen,\n didClose\n };\n }\n }\n // The notebook is a property as well.\n return Object.keys(result).length > 1 ? result : undefined;\n }\n getMatchingCells(notebookDocument, cells = notebookDocument.getCells()) {\n if (this.options.notebookSelector === undefined) {\n return undefined;\n }\n for (const item of this.options.notebookSelector) {\n if (item.notebook === undefined || $NotebookDocumentFilter.matchNotebook(item.notebook, notebookDocument)) {\n const filtered = this.filterCells(notebookDocument, cells, item.cells);\n return filtered.length === 0 ? undefined : filtered;\n }\n }\n return undefined;\n }\n cellMatches(notebookDocument, cell) {\n const cells = this.getMatchingCells(notebookDocument, [cell]);\n return cells !== undefined && cells[0] === cell;\n }\n filterCells(notebookDocument, cells, cellSelector) {\n const filtered = cellSelector !== undefined ? cells.filter((cell) => {\n const cellLanguage = cell.document.languageId;\n return cellSelector.some((filter => (filter.language === '*' || cellLanguage === filter.language)));\n }) : cells;\n return typeof this.client.clientOptions.notebookDocumentOptions?.filterCells === 'function'\n ? this.client.clientOptions.notebookDocumentOptions.filterCells(notebookDocument, filtered)\n : filtered;\n }\n}\nclass NotebookDocumentSyncFeature {\n constructor(client) {\n this.client = client;\n this.registrations = new Map();\n this.registrationType = proto.NotebookDocumentSyncRegistrationType.type;\n // We don't receive an event for cells where the document changes its language mode\n // Since we allow servers to filter on the language mode we fire such an event ourselves.\n vscode.workspace.onDidOpenTextDocument((textDocument) => {\n if (textDocument.uri.scheme !== NotebookDocumentSyncFeature.CellScheme) {\n return;\n }\n const [notebookDocument, notebookCell] = this.findNotebookDocumentAndCell(textDocument);\n if (notebookDocument === undefined || notebookCell === undefined) {\n return;\n }\n for (const provider of this.registrations.values()) {\n if (provider instanceof NotebookDocumentSyncFeatureProvider) {\n provider.didOpenNotebookCellTextDocument(notebookDocument, notebookCell);\n }\n }\n });\n vscode.workspace.onDidChangeTextDocument((event) => {\n if (event.contentChanges.length === 0) {\n return;\n }\n const textDocument = event.document;\n if (textDocument.uri.scheme !== NotebookDocumentSyncFeature.CellScheme) {\n return;\n }\n const [notebookDocument,] = this.findNotebookDocumentAndCell(textDocument);\n if (notebookDocument === undefined) {\n return;\n }\n for (const provider of this.registrations.values()) {\n if (provider instanceof NotebookDocumentSyncFeatureProvider) {\n provider.didChangeNotebookCellTextDocument(notebookDocument, event);\n }\n }\n });\n vscode.workspace.onDidCloseTextDocument((textDocument) => {\n if (textDocument.uri.scheme !== NotebookDocumentSyncFeature.CellScheme) {\n return;\n }\n // There are two cases when we receive a close for a text document\n // 1: the cell got removed. This is handled in `onDidChangeNotebookCells`\n // 2: the language mode of a cell changed. This keeps the URI stable so\n // we will still find the cell and the notebook document.\n const [notebookDocument, notebookCell] = this.findNotebookDocumentAndCell(textDocument);\n if (notebookDocument === undefined || notebookCell === undefined) {\n return;\n }\n for (const provider of this.registrations.values()) {\n if (provider instanceof NotebookDocumentSyncFeatureProvider) {\n provider.didCloseNotebookCellTextDocument(notebookDocument, notebookCell);\n }\n }\n });\n }\n getState() {\n if (this.registrations.size === 0) {\n return { kind: 'document', id: this.registrationType.method, registrations: false, matches: false };\n }\n for (const provider of this.registrations.values()) {\n const state = provider.getState();\n if (state.kind === 'document' && state.registrations === true && state.matches === true) {\n return { kind: 'document', id: this.registrationType.method, registrations: true, matches: true };\n }\n }\n return { kind: 'document', id: this.registrationType.method, registrations: true, matches: false };\n }\n fillClientCapabilities(capabilities) {\n const synchronization = ensure(ensure(capabilities, 'notebookDocument'), 'synchronization');\n synchronization.dynamicRegistration = true;\n synchronization.executionSummarySupport = true;\n }\n preInitialize(capabilities) {\n const options = capabilities.notebookDocumentSync;\n if (options === undefined) {\n return;\n }\n this.dedicatedChannel = this.client.protocol2CodeConverter.asDocumentSelector($NotebookDocumentSyncOptions.asDocumentSelector(options));\n }\n initialize(capabilities) {\n const options = capabilities.notebookDocumentSync;\n if (options === undefined) {\n return;\n }\n const id = options.id ?? UUID.generateUuid();\n this.register({ id, registerOptions: options });\n }\n register(data) {\n const provider = new NotebookDocumentSyncFeatureProvider(this.client, data.registerOptions);\n this.registrations.set(data.id, provider);\n }\n unregister(id) {\n const provider = this.registrations.get(id);\n provider && provider.dispose();\n }\n clear() {\n for (const provider of this.registrations.values()) {\n provider.dispose();\n }\n this.registrations.clear();\n }\n handles(textDocument) {\n if (textDocument.uri.scheme !== NotebookDocumentSyncFeature.CellScheme) {\n return false;\n }\n if (this.dedicatedChannel !== undefined && vscode.languages.match(this.dedicatedChannel, textDocument) > 0) {\n return true;\n }\n for (const provider of this.registrations.values()) {\n if (provider.handles(textDocument)) {\n return true;\n }\n }\n return false;\n }\n getProvider(notebookCell) {\n for (const provider of this.registrations.values()) {\n if (provider.handles(notebookCell.document)) {\n return provider;\n }\n }\n return undefined;\n }\n findNotebookDocumentAndCell(textDocument) {\n const uri = textDocument.uri.toString();\n for (const notebookDocument of vscode.workspace.notebookDocuments) {\n for (const cell of notebookDocument.getCells()) {\n if (cell.document.uri.toString() === uri) {\n return [notebookDocument, cell];\n }\n }\n }\n return [undefined, undefined];\n }\n}\nexports.NotebookDocumentSyncFeature = NotebookDocumentSyncFeature;\nNotebookDocumentSyncFeature.CellScheme = 'vscode-notebook-cell';\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SyncConfigurationFeature = exports.toJSONObject = exports.ConfigurationFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst Is = require(\"./utils/is\");\nconst UUID = require(\"./utils/uuid\");\nconst features_1 = require(\"./features\");\n/**\n * Configuration pull model. From server to client.\n */\nclass ConfigurationFeature {\n constructor(client) {\n this._client = client;\n }\n getState() {\n return { kind: 'static' };\n }\n fillClientCapabilities(capabilities) {\n capabilities.workspace = capabilities.workspace || {};\n capabilities.workspace.configuration = true;\n }\n initialize() {\n let client = this._client;\n client.onRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, (params, token) => {\n let configuration = (params) => {\n let result = [];\n for (let item of params.items) {\n let resource = item.scopeUri !== void 0 && item.scopeUri !== null ? this._client.protocol2CodeConverter.asUri(item.scopeUri) : undefined;\n result.push(this.getConfiguration(resource, item.section !== null ? item.section : undefined));\n }\n return result;\n };\n let middleware = client.middleware.workspace;\n return middleware && middleware.configuration\n ? middleware.configuration(params, token, configuration)\n : configuration(params, token);\n });\n }\n getConfiguration(resource, section) {\n let result = null;\n if (section) {\n let index = section.lastIndexOf('.');\n if (index === -1) {\n result = toJSONObject(vscode_1.workspace.getConfiguration(undefined, resource).get(section));\n }\n else {\n let config = vscode_1.workspace.getConfiguration(section.substr(0, index), resource);\n if (config) {\n result = toJSONObject(config.get(section.substr(index + 1)));\n }\n }\n }\n else {\n let config = vscode_1.workspace.getConfiguration(undefined, resource);\n result = {};\n for (let key of Object.keys(config)) {\n if (config.has(key)) {\n result[key] = toJSONObject(config.get(key));\n }\n }\n }\n if (result === undefined) {\n result = null;\n }\n return result;\n }\n clear() {\n }\n}\nexports.ConfigurationFeature = ConfigurationFeature;\nfunction toJSONObject(obj) {\n if (obj) {\n if (Array.isArray(obj)) {\n return obj.map(toJSONObject);\n }\n else if (typeof obj === 'object') {\n const res = Object.create(null);\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = toJSONObject(obj[key]);\n }\n }\n return res;\n }\n }\n return obj;\n}\nexports.toJSONObject = toJSONObject;\nclass SyncConfigurationFeature {\n constructor(_client) {\n this._client = _client;\n this.isCleared = false;\n this._listeners = new Map();\n }\n getState() {\n return { kind: 'workspace', id: this.registrationType.method, registrations: this._listeners.size > 0 };\n }\n get registrationType() {\n return vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type;\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'workspace'), 'didChangeConfiguration').dynamicRegistration = true;\n }\n initialize() {\n this.isCleared = false;\n let section = this._client.clientOptions.synchronize?.configurationSection;\n if (section !== undefined) {\n this.register({\n id: UUID.generateUuid(),\n registerOptions: {\n section: section\n }\n });\n }\n }\n register(data) {\n let disposable = vscode_1.workspace.onDidChangeConfiguration((event) => {\n this.onDidChangeConfiguration(data.registerOptions.section, event);\n });\n this._listeners.set(data.id, disposable);\n if (data.registerOptions.section !== undefined) {\n this.onDidChangeConfiguration(data.registerOptions.section, undefined);\n }\n }\n unregister(id) {\n let disposable = this._listeners.get(id);\n if (disposable) {\n this._listeners.delete(id);\n disposable.dispose();\n }\n }\n clear() {\n for (const disposable of this._listeners.values()) {\n disposable.dispose();\n }\n this._listeners.clear();\n this.isCleared = true;\n }\n onDidChangeConfiguration(configurationSection, event) {\n if (this.isCleared) {\n return;\n }\n let sections;\n if (Is.string(configurationSection)) {\n sections = [configurationSection];\n }\n else {\n sections = configurationSection;\n }\n if (sections !== undefined && event !== undefined) {\n let affected = sections.some((section) => event.affectsConfiguration(section));\n if (!affected) {\n return;\n }\n }\n const didChangeConfiguration = async (sections) => {\n if (sections === undefined) {\n return this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: null });\n }\n else {\n return this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: this.extractSettingsInformation(sections) });\n }\n };\n let middleware = this._client.middleware.workspace?.didChangeConfiguration;\n (middleware ? middleware(sections, didChangeConfiguration) : didChangeConfiguration(sections)).catch((error) => {\n this._client.error(`Sending notification ${vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type.method} failed`, error);\n });\n }\n extractSettingsInformation(keys) {\n function ensurePath(config, path) {\n let current = config;\n for (let i = 0; i < path.length - 1; i++) {\n let obj = current[path[i]];\n if (!obj) {\n obj = Object.create(null);\n current[path[i]] = obj;\n }\n current = obj;\n }\n return current;\n }\n let resource = this._client.clientOptions.workspaceFolder\n ? this._client.clientOptions.workspaceFolder.uri\n : undefined;\n let result = Object.create(null);\n for (let i = 0; i < keys.length; i++) {\n let key = keys[i];\n let index = key.indexOf('.');\n let config = null;\n if (index >= 0) {\n config = vscode_1.workspace.getConfiguration(key.substr(0, index), resource).get(key.substr(index + 1));\n }\n else {\n config = vscode_1.workspace.getConfiguration(undefined, resource).get(key);\n }\n if (config) {\n let path = keys[i].split('.');\n ensurePath(result, path)[path[path.length - 1]] = toJSONObject(config);\n }\n }\n return result;\n }\n}\nexports.SyncConfigurationFeature = SyncConfigurationFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DidSaveTextDocumentFeature = exports.WillSaveWaitUntilFeature = exports.WillSaveFeature = exports.DidChangeTextDocumentFeature = exports.DidCloseTextDocumentFeature = exports.DidOpenTextDocumentFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst UUID = require(\"./utils/uuid\");\nclass DidOpenTextDocumentFeature extends features_1.TextDocumentEventFeature {\n constructor(client, syncedDocuments) {\n super(client, vscode_1.workspace.onDidOpenTextDocument, vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, () => client.middleware.didOpen, (textDocument) => client.code2ProtocolConverter.asOpenTextDocumentParams(textDocument), (data) => data, features_1.TextDocumentEventFeature.textDocumentFilter);\n this._syncedDocuments = syncedDocuments;\n }\n get openDocuments() {\n return this._syncedDocuments.values();\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;\n if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) {\n this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } });\n }\n }\n get registrationType() {\n return vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type;\n }\n register(data) {\n super.register(data);\n if (!data.registerOptions.documentSelector) {\n return;\n }\n const documentSelector = this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector);\n vscode_1.workspace.textDocuments.forEach((textDocument) => {\n const uri = textDocument.uri.toString();\n if (this._syncedDocuments.has(uri)) {\n return;\n }\n if (vscode_1.languages.match(documentSelector, textDocument) > 0 && !this._client.hasDedicatedTextSynchronizationFeature(textDocument)) {\n const middleware = this._client.middleware;\n const didOpen = (textDocument) => {\n return this._client.sendNotification(this._type, this._createParams(textDocument));\n };\n (middleware.didOpen ? middleware.didOpen(textDocument, didOpen) : didOpen(textDocument)).catch((error) => {\n this._client.error(`Sending document notification ${this._type.method} failed`, error);\n });\n this._syncedDocuments.set(uri, textDocument);\n }\n });\n }\n getTextDocument(data) {\n return data;\n }\n notificationSent(textDocument, type, params) {\n this._syncedDocuments.set(textDocument.uri.toString(), textDocument);\n super.notificationSent(textDocument, type, params);\n }\n}\nexports.DidOpenTextDocumentFeature = DidOpenTextDocumentFeature;\nclass DidCloseTextDocumentFeature extends features_1.TextDocumentEventFeature {\n constructor(client, syncedDocuments, pendingTextDocumentChanges) {\n super(client, vscode_1.workspace.onDidCloseTextDocument, vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, () => client.middleware.didClose, (textDocument) => client.code2ProtocolConverter.asCloseTextDocumentParams(textDocument), (data) => data, features_1.TextDocumentEventFeature.textDocumentFilter);\n this._syncedDocuments = syncedDocuments;\n this._pendingTextDocumentChanges = pendingTextDocumentChanges;\n }\n get registrationType() {\n return vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type;\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;\n if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) {\n this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } });\n }\n }\n async callback(data) {\n await super.callback(data);\n this._pendingTextDocumentChanges.delete(data.uri.toString());\n }\n getTextDocument(data) {\n return data;\n }\n notificationSent(textDocument, type, params) {\n this._syncedDocuments.delete(textDocument.uri.toString());\n super.notificationSent(textDocument, type, params);\n }\n unregister(id) {\n const selector = this._selectors.get(id);\n // The super call removed the selector from the map\n // of selectors.\n super.unregister(id);\n const selectors = this._selectors.values();\n this._syncedDocuments.forEach((textDocument) => {\n if (vscode_1.languages.match(selector, textDocument) > 0 && !this._selectorFilter(selectors, textDocument) && !this._client.hasDedicatedTextSynchronizationFeature(textDocument)) {\n let middleware = this._client.middleware;\n let didClose = (textDocument) => {\n return this._client.sendNotification(this._type, this._createParams(textDocument));\n };\n this._syncedDocuments.delete(textDocument.uri.toString());\n (middleware.didClose ? middleware.didClose(textDocument, didClose) : didClose(textDocument)).catch((error) => {\n this._client.error(`Sending document notification ${this._type.method} failed`, error);\n });\n }\n });\n }\n}\nexports.DidCloseTextDocumentFeature = DidCloseTextDocumentFeature;\nclass DidChangeTextDocumentFeature extends features_1.DynamicDocumentFeature {\n constructor(client, pendingTextDocumentChanges) {\n super(client);\n this._changeData = new Map();\n this._onNotificationSent = new vscode_1.EventEmitter();\n this._onPendingChangeAdded = new vscode_1.EventEmitter();\n this._pendingTextDocumentChanges = pendingTextDocumentChanges;\n this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None;\n }\n get onNotificationSent() {\n return this._onNotificationSent.event;\n }\n get onPendingChangeAdded() {\n return this._onPendingChangeAdded.event;\n }\n get syncKind() {\n return this._syncKind;\n }\n get registrationType() {\n return vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type;\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;\n if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.change !== undefined && textDocumentSyncOptions.change !== vscode_languageserver_protocol_1.TextDocumentSyncKind.None) {\n this.register({\n id: UUID.generateUuid(),\n registerOptions: Object.assign({}, { documentSelector: documentSelector }, { syncKind: textDocumentSyncOptions.change })\n });\n }\n }\n register(data) {\n if (!data.registerOptions.documentSelector) {\n return;\n }\n if (!this._listener) {\n this._listener = vscode_1.workspace.onDidChangeTextDocument(this.callback, this);\n }\n this._changeData.set(data.id, {\n syncKind: data.registerOptions.syncKind,\n documentSelector: this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector),\n });\n this.updateSyncKind(data.registerOptions.syncKind);\n }\n *getDocumentSelectors() {\n for (const data of this._changeData.values()) {\n yield data.documentSelector;\n }\n }\n async callback(event) {\n // Text document changes are send for dirty changes as well. We don't\n // have dirty / un-dirty events in the LSP so we ignore content changes\n // with length zero.\n if (event.contentChanges.length === 0) {\n return;\n }\n // We need to capture the URI and version here since they might change on the text document\n // until we reach did `didChange` call since the middleware support async execution.\n const uri = event.document.uri;\n const version = event.document.version;\n const promises = [];\n for (const changeData of this._changeData.values()) {\n if (vscode_1.languages.match(changeData.documentSelector, event.document) > 0 && !this._client.hasDedicatedTextSynchronizationFeature(event.document)) {\n const middleware = this._client.middleware;\n if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental) {\n const didChange = async (event) => {\n const params = this._client.code2ProtocolConverter.asChangeTextDocumentParams(event, uri, version);\n await this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params);\n this.notificationSent(event.document, vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params);\n };\n promises.push(middleware.didChange ? middleware.didChange(event, event => didChange(event)) : didChange(event));\n }\n else if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) {\n const didChange = async (event) => {\n const eventUri = event.document.uri.toString();\n this._pendingTextDocumentChanges.set(eventUri, event.document);\n this._onPendingChangeAdded.fire();\n };\n promises.push(middleware.didChange ? middleware.didChange(event, event => didChange(event)) : didChange(event));\n }\n }\n }\n return Promise.all(promises).then(undefined, (error) => {\n this._client.error(`Sending document notification ${vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type.method} failed`, error);\n throw error;\n });\n }\n notificationSent(textDocument, type, params) {\n this._onNotificationSent.fire({ textDocument, type, params });\n }\n unregister(id) {\n this._changeData.delete(id);\n if (this._changeData.size === 0) {\n if (this._listener) {\n this._listener.dispose();\n this._listener = undefined;\n }\n this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None;\n }\n else {\n this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None;\n for (const changeData of this._changeData.values()) {\n this.updateSyncKind(changeData.syncKind);\n if (this._syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) {\n break;\n }\n }\n }\n }\n clear() {\n this._pendingTextDocumentChanges.clear();\n this._changeData.clear();\n this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None;\n if (this._listener) {\n this._listener.dispose();\n this._listener = undefined;\n }\n }\n getPendingDocumentChanges(excludes) {\n if (this._pendingTextDocumentChanges.size === 0) {\n return [];\n }\n let result;\n if (excludes.size === 0) {\n result = Array.from(this._pendingTextDocumentChanges.values());\n this._pendingTextDocumentChanges.clear();\n }\n else {\n result = [];\n for (const entry of this._pendingTextDocumentChanges) {\n if (!excludes.has(entry[0])) {\n result.push(entry[1]);\n this._pendingTextDocumentChanges.delete(entry[0]);\n }\n }\n }\n return result;\n }\n getProvider(document) {\n for (const changeData of this._changeData.values()) {\n if (vscode_1.languages.match(changeData.documentSelector, document) > 0) {\n return {\n send: (event) => {\n return this.callback(event);\n }\n };\n }\n }\n return undefined;\n }\n updateSyncKind(syncKind) {\n if (this._syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) {\n return;\n }\n switch (syncKind) {\n case vscode_languageserver_protocol_1.TextDocumentSyncKind.Full:\n this._syncKind = syncKind;\n break;\n case vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental:\n if (this._syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.None) {\n this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental;\n }\n break;\n }\n }\n}\nexports.DidChangeTextDocumentFeature = DidChangeTextDocumentFeature;\nclass WillSaveFeature extends features_1.TextDocumentEventFeature {\n constructor(client) {\n super(client, vscode_1.workspace.onWillSaveTextDocument, vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, () => client.middleware.willSave, (willSaveEvent) => client.code2ProtocolConverter.asWillSaveTextDocumentParams(willSaveEvent), (event) => event.document, (selectors, willSaveEvent) => features_1.TextDocumentEventFeature.textDocumentFilter(selectors, willSaveEvent.document));\n }\n get registrationType() {\n return vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type;\n }\n fillClientCapabilities(capabilities) {\n let value = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'synchronization');\n value.willSave = true;\n }\n initialize(capabilities, documentSelector) {\n let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;\n if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSave) {\n this.register({\n id: UUID.generateUuid(),\n registerOptions: { documentSelector: documentSelector }\n });\n }\n }\n getTextDocument(data) {\n return data.document;\n }\n}\nexports.WillSaveFeature = WillSaveFeature;\nclass WillSaveWaitUntilFeature extends features_1.DynamicDocumentFeature {\n constructor(client) {\n super(client);\n this._selectors = new Map();\n }\n getDocumentSelectors() {\n return this._selectors.values();\n }\n get registrationType() {\n return vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type;\n }\n fillClientCapabilities(capabilities) {\n let value = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'synchronization');\n value.willSaveWaitUntil = true;\n }\n initialize(capabilities, documentSelector) {\n let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;\n if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSaveWaitUntil) {\n this.register({\n id: UUID.generateUuid(),\n registerOptions: { documentSelector: documentSelector }\n });\n }\n }\n register(data) {\n if (!data.registerOptions.documentSelector) {\n return;\n }\n if (!this._listener) {\n this._listener = vscode_1.workspace.onWillSaveTextDocument(this.callback, this);\n }\n this._selectors.set(data.id, this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector));\n }\n callback(event) {\n if (features_1.TextDocumentEventFeature.textDocumentFilter(this._selectors.values(), event.document) && !this._client.hasDedicatedTextSynchronizationFeature(event.document)) {\n let middleware = this._client.middleware;\n let willSaveWaitUntil = (event) => {\n return this._client.sendRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, this._client.code2ProtocolConverter.asWillSaveTextDocumentParams(event)).then(async (edits) => {\n let vEdits = await this._client.protocol2CodeConverter.asTextEdits(edits);\n return vEdits === undefined ? [] : vEdits;\n });\n };\n event.waitUntil(middleware.willSaveWaitUntil\n ? middleware.willSaveWaitUntil(event, willSaveWaitUntil)\n : willSaveWaitUntil(event));\n }\n }\n unregister(id) {\n this._selectors.delete(id);\n if (this._selectors.size === 0 && this._listener) {\n this._listener.dispose();\n this._listener = undefined;\n }\n }\n clear() {\n this._selectors.clear();\n if (this._listener) {\n this._listener.dispose();\n this._listener = undefined;\n }\n }\n}\nexports.WillSaveWaitUntilFeature = WillSaveWaitUntilFeature;\nclass DidSaveTextDocumentFeature extends features_1.TextDocumentEventFeature {\n constructor(client) {\n super(client, vscode_1.workspace.onDidSaveTextDocument, vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, () => client.middleware.didSave, (textDocument) => client.code2ProtocolConverter.asSaveTextDocumentParams(textDocument, this._includeText), (data) => data, features_1.TextDocumentEventFeature.textDocumentFilter);\n this._includeText = false;\n }\n get registrationType() {\n return vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type;\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'synchronization').didSave = true;\n }\n initialize(capabilities, documentSelector) {\n const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;\n if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.save) {\n const saveOptions = typeof textDocumentSyncOptions.save === 'boolean'\n ? { includeText: false }\n : { includeText: !!textDocumentSyncOptions.save.includeText };\n this.register({\n id: UUID.generateUuid(),\n registerOptions: Object.assign({}, { documentSelector: documentSelector }, saveOptions)\n });\n }\n }\n register(data) {\n this._includeText = !!data.registerOptions.includeText;\n super.register(data);\n }\n getTextDocument(data) {\n return data;\n }\n}\nexports.DidSaveTextDocumentFeature = DidSaveTextDocumentFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CompletionItemFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst UUID = require(\"./utils/uuid\");\nconst SupportedCompletionItemKinds = [\n vscode_languageserver_protocol_1.CompletionItemKind.Text,\n vscode_languageserver_protocol_1.CompletionItemKind.Method,\n vscode_languageserver_protocol_1.CompletionItemKind.Function,\n vscode_languageserver_protocol_1.CompletionItemKind.Constructor,\n vscode_languageserver_protocol_1.CompletionItemKind.Field,\n vscode_languageserver_protocol_1.CompletionItemKind.Variable,\n vscode_languageserver_protocol_1.CompletionItemKind.Class,\n vscode_languageserver_protocol_1.CompletionItemKind.Interface,\n vscode_languageserver_protocol_1.CompletionItemKind.Module,\n vscode_languageserver_protocol_1.CompletionItemKind.Property,\n vscode_languageserver_protocol_1.CompletionItemKind.Unit,\n vscode_languageserver_protocol_1.CompletionItemKind.Value,\n vscode_languageserver_protocol_1.CompletionItemKind.Enum,\n vscode_languageserver_protocol_1.CompletionItemKind.Keyword,\n vscode_languageserver_protocol_1.CompletionItemKind.Snippet,\n vscode_languageserver_protocol_1.CompletionItemKind.Color,\n vscode_languageserver_protocol_1.CompletionItemKind.File,\n vscode_languageserver_protocol_1.CompletionItemKind.Reference,\n vscode_languageserver_protocol_1.CompletionItemKind.Folder,\n vscode_languageserver_protocol_1.CompletionItemKind.EnumMember,\n vscode_languageserver_protocol_1.CompletionItemKind.Constant,\n vscode_languageserver_protocol_1.CompletionItemKind.Struct,\n vscode_languageserver_protocol_1.CompletionItemKind.Event,\n vscode_languageserver_protocol_1.CompletionItemKind.Operator,\n vscode_languageserver_protocol_1.CompletionItemKind.TypeParameter\n];\nclass CompletionItemFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.CompletionRequest.type);\n this.labelDetailsSupport = new Map();\n }\n fillClientCapabilities(capabilities) {\n let completion = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'completion');\n completion.dynamicRegistration = true;\n completion.contextSupport = true;\n completion.completionItem = {\n snippetSupport: true,\n commitCharactersSupport: true,\n documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText],\n deprecatedSupport: true,\n preselectSupport: true,\n tagSupport: { valueSet: [vscode_languageserver_protocol_1.CompletionItemTag.Deprecated] },\n insertReplaceSupport: true,\n resolveSupport: {\n properties: ['documentation', 'detail', 'additionalTextEdits']\n },\n insertTextModeSupport: { valueSet: [vscode_languageserver_protocol_1.InsertTextMode.asIs, vscode_languageserver_protocol_1.InsertTextMode.adjustIndentation] },\n labelDetailsSupport: true\n };\n completion.insertTextMode = vscode_languageserver_protocol_1.InsertTextMode.adjustIndentation;\n completion.completionItemKind = { valueSet: SupportedCompletionItemKinds };\n completion.completionList = {\n itemDefaults: [\n 'commitCharacters', 'editRange', 'insertTextFormat', 'insertTextMode', 'data'\n ]\n };\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.completionProvider);\n if (!options) {\n return;\n }\n this.register({\n id: UUID.generateUuid(),\n registerOptions: options\n });\n }\n registerLanguageProvider(options, id) {\n this.labelDetailsSupport.set(id, !!options.completionItem?.labelDetailsSupport);\n const triggerCharacters = options.triggerCharacters ?? [];\n const defaultCommitCharacters = options.allCommitCharacters;\n const selector = options.documentSelector;\n const provider = {\n provideCompletionItems: (document, position, token, context) => {\n const client = this._client;\n const middleware = this._client.middleware;\n const provideCompletionItems = (document, position, context, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.CompletionRequest.type, client.code2ProtocolConverter.asCompletionParams(document, position, context), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asCompletionResult(result, defaultCommitCharacters, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.CompletionRequest.type, token, error, null);\n });\n };\n return middleware.provideCompletionItem\n ? middleware.provideCompletionItem(document, position, context, token, provideCompletionItems)\n : provideCompletionItems(document, position, context, token);\n },\n resolveCompletionItem: options.resolveProvider\n ? (item, token) => {\n const client = this._client;\n const middleware = this._client.middleware;\n const resolveCompletionItem = (item, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, client.code2ProtocolConverter.asCompletionItem(item, !!this.labelDetailsSupport.get(id)), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asCompletionItem(result);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, token, error, item);\n });\n };\n return middleware.resolveCompletionItem\n ? middleware.resolveCompletionItem(item, token, resolveCompletionItem)\n : resolveCompletionItem(item, token);\n }\n : undefined\n };\n return [vscode_1.languages.registerCompletionItemProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, ...triggerCharacters), provider];\n }\n}\nexports.CompletionItemFeature = CompletionItemFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.HoverFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst UUID = require(\"./utils/uuid\");\nclass HoverFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.HoverRequest.type);\n }\n fillClientCapabilities(capabilities) {\n const hoverCapability = ((0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'hover'));\n hoverCapability.dynamicRegistration = true;\n hoverCapability.contentFormat = [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText];\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.hoverProvider);\n if (!options) {\n return;\n }\n this.register({\n id: UUID.generateUuid(),\n registerOptions: options\n });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideHover: (document, position, token) => {\n const client = this._client;\n const provideHover = (document, position, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asHover(result);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.HoverRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideHover\n ? middleware.provideHover(document, position, token, provideHover)\n : provideHover(document, position, token);\n }\n };\n return [this.registerProvider(selector, provider), provider];\n }\n registerProvider(selector, provider) {\n return vscode_1.languages.registerHoverProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);\n }\n}\nexports.HoverFeature = HoverFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DefinitionFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst UUID = require(\"./utils/uuid\");\nclass DefinitionFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.DefinitionRequest.type);\n }\n fillClientCapabilities(capabilities) {\n let definitionSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'definition');\n definitionSupport.dynamicRegistration = true;\n definitionSupport.linkSupport = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.definitionProvider);\n if (!options) {\n return;\n }\n this.register({ id: UUID.generateUuid(), registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideDefinition: (document, position, token) => {\n const client = this._client;\n const provideDefinition = (document, position, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asDefinitionResult(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideDefinition\n ? middleware.provideDefinition(document, position, token, provideDefinition)\n : provideDefinition(document, position, token);\n }\n };\n return [this.registerProvider(selector, provider), provider];\n }\n registerProvider(selector, provider) {\n return vscode_1.languages.registerDefinitionProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);\n }\n}\nexports.DefinitionFeature = DefinitionFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SignatureHelpFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst UUID = require(\"./utils/uuid\");\nclass SignatureHelpFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.SignatureHelpRequest.type);\n }\n fillClientCapabilities(capabilities) {\n let config = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'signatureHelp');\n config.dynamicRegistration = true;\n config.signatureInformation = { documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText] };\n config.signatureInformation.parameterInformation = { labelOffsetSupport: true };\n config.signatureInformation.activeParameterSupport = true;\n config.contextSupport = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.signatureHelpProvider);\n if (!options) {\n return;\n }\n this.register({\n id: UUID.generateUuid(),\n registerOptions: options\n });\n }\n registerLanguageProvider(options) {\n const provider = {\n provideSignatureHelp: (document, position, token, context) => {\n const client = this._client;\n const providerSignatureHelp = (document, position, context, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, client.code2ProtocolConverter.asSignatureHelpParams(document, position, context), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asSignatureHelp(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideSignatureHelp\n ? middleware.provideSignatureHelp(document, position, context, token, providerSignatureHelp)\n : providerSignatureHelp(document, position, context, token);\n }\n };\n return [this.registerProvider(options, provider), provider];\n }\n registerProvider(options, provider) {\n const selector = this._client.protocol2CodeConverter.asDocumentSelector(options.documentSelector);\n if (options.retriggerCharacters === undefined) {\n const triggerCharacters = options.triggerCharacters || [];\n return vscode_1.languages.registerSignatureHelpProvider(selector, provider, ...triggerCharacters);\n }\n else {\n const metaData = {\n triggerCharacters: options.triggerCharacters || [],\n retriggerCharacters: options.retriggerCharacters || []\n };\n return vscode_1.languages.registerSignatureHelpProvider(selector, provider, metaData);\n }\n }\n}\nexports.SignatureHelpFeature = SignatureHelpFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DocumentHighlightFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst UUID = require(\"./utils/uuid\");\nclass DocumentHighlightFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.DocumentHighlightRequest.type);\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'documentHighlight').dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.documentHighlightProvider);\n if (!options) {\n return;\n }\n this.register({ id: UUID.generateUuid(), registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideDocumentHighlights: (document, position, token) => {\n const client = this._client;\n const _provideDocumentHighlights = (document, position, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asDocumentHighlights(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideDocumentHighlights\n ? middleware.provideDocumentHighlights(document, position, token, _provideDocumentHighlights)\n : _provideDocumentHighlights(document, position, token);\n }\n };\n return [vscode_1.languages.registerDocumentHighlightProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];\n }\n}\nexports.DocumentHighlightFeature = DocumentHighlightFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DocumentSymbolFeature = exports.SupportedSymbolTags = exports.SupportedSymbolKinds = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst UUID = require(\"./utils/uuid\");\nexports.SupportedSymbolKinds = [\n vscode_languageserver_protocol_1.SymbolKind.File,\n vscode_languageserver_protocol_1.SymbolKind.Module,\n vscode_languageserver_protocol_1.SymbolKind.Namespace,\n vscode_languageserver_protocol_1.SymbolKind.Package,\n vscode_languageserver_protocol_1.SymbolKind.Class,\n vscode_languageserver_protocol_1.SymbolKind.Method,\n vscode_languageserver_protocol_1.SymbolKind.Property,\n vscode_languageserver_protocol_1.SymbolKind.Field,\n vscode_languageserver_protocol_1.SymbolKind.Constructor,\n vscode_languageserver_protocol_1.SymbolKind.Enum,\n vscode_languageserver_protocol_1.SymbolKind.Interface,\n vscode_languageserver_protocol_1.SymbolKind.Function,\n vscode_languageserver_protocol_1.SymbolKind.Variable,\n vscode_languageserver_protocol_1.SymbolKind.Constant,\n vscode_languageserver_protocol_1.SymbolKind.String,\n vscode_languageserver_protocol_1.SymbolKind.Number,\n vscode_languageserver_protocol_1.SymbolKind.Boolean,\n vscode_languageserver_protocol_1.SymbolKind.Array,\n vscode_languageserver_protocol_1.SymbolKind.Object,\n vscode_languageserver_protocol_1.SymbolKind.Key,\n vscode_languageserver_protocol_1.SymbolKind.Null,\n vscode_languageserver_protocol_1.SymbolKind.EnumMember,\n vscode_languageserver_protocol_1.SymbolKind.Struct,\n vscode_languageserver_protocol_1.SymbolKind.Event,\n vscode_languageserver_protocol_1.SymbolKind.Operator,\n vscode_languageserver_protocol_1.SymbolKind.TypeParameter\n];\nexports.SupportedSymbolTags = [\n vscode_languageserver_protocol_1.SymbolTag.Deprecated\n];\nclass DocumentSymbolFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.DocumentSymbolRequest.type);\n }\n fillClientCapabilities(capabilities) {\n let symbolCapabilities = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'documentSymbol');\n symbolCapabilities.dynamicRegistration = true;\n symbolCapabilities.symbolKind = {\n valueSet: exports.SupportedSymbolKinds\n };\n symbolCapabilities.hierarchicalDocumentSymbolSupport = true;\n symbolCapabilities.tagSupport = {\n valueSet: exports.SupportedSymbolTags\n };\n symbolCapabilities.labelSupport = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.documentSymbolProvider);\n if (!options) {\n return;\n }\n this.register({ id: UUID.generateUuid(), registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideDocumentSymbols: (document, token) => {\n const client = this._client;\n const _provideDocumentSymbols = async (document, token) => {\n try {\n const data = await client.sendRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, client.code2ProtocolConverter.asDocumentSymbolParams(document), token);\n if (token.isCancellationRequested || data === undefined || data === null) {\n return null;\n }\n if (data.length === 0) {\n return [];\n }\n else {\n const first = data[0];\n if (vscode_languageserver_protocol_1.DocumentSymbol.is(first)) {\n return await client.protocol2CodeConverter.asDocumentSymbols(data, token);\n }\n else {\n return await client.protocol2CodeConverter.asSymbolInformations(data, token);\n }\n }\n }\n catch (error) {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, token, error, null);\n }\n };\n const middleware = client.middleware;\n return middleware.provideDocumentSymbols\n ? middleware.provideDocumentSymbols(document, token, _provideDocumentSymbols)\n : _provideDocumentSymbols(document, token);\n }\n };\n const metaData = options.label !== undefined ? { label: options.label } : undefined;\n return [vscode_1.languages.registerDocumentSymbolProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, metaData), provider];\n }\n}\nexports.DocumentSymbolFeature = DocumentSymbolFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WorkspaceSymbolFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst documentSymbol_1 = require(\"./documentSymbol\");\nconst UUID = require(\"./utils/uuid\");\nclass WorkspaceSymbolFeature extends features_1.WorkspaceFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type);\n }\n fillClientCapabilities(capabilities) {\n let symbolCapabilities = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'workspace'), 'symbol');\n symbolCapabilities.dynamicRegistration = true;\n symbolCapabilities.symbolKind = {\n valueSet: documentSymbol_1.SupportedSymbolKinds\n };\n symbolCapabilities.tagSupport = {\n valueSet: documentSymbol_1.SupportedSymbolTags\n };\n symbolCapabilities.resolveSupport = { properties: ['location.range'] };\n }\n initialize(capabilities) {\n if (!capabilities.workspaceSymbolProvider) {\n return;\n }\n this.register({\n id: UUID.generateUuid(),\n registerOptions: capabilities.workspaceSymbolProvider === true ? { workDoneProgress: false } : capabilities.workspaceSymbolProvider\n });\n }\n registerLanguageProvider(options) {\n const provider = {\n provideWorkspaceSymbols: (query, token) => {\n const client = this._client;\n const provideWorkspaceSymbols = (query, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, { query }, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asSymbolInformations(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideWorkspaceSymbols\n ? middleware.provideWorkspaceSymbols(query, token, provideWorkspaceSymbols)\n : provideWorkspaceSymbols(query, token);\n },\n resolveWorkspaceSymbol: options.resolveProvider === true\n ? (item, token) => {\n const client = this._client;\n const resolveWorkspaceSymbol = (item, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.type, client.code2ProtocolConverter.asWorkspaceSymbol(item), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asSymbolInformation(result);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.resolveWorkspaceSymbol\n ? middleware.resolveWorkspaceSymbol(item, token, resolveWorkspaceSymbol)\n : resolveWorkspaceSymbol(item, token);\n }\n : undefined\n };\n return [vscode_1.languages.registerWorkspaceSymbolProvider(provider), provider];\n }\n}\nexports.WorkspaceSymbolFeature = WorkspaceSymbolFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ReferencesFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst UUID = require(\"./utils/uuid\");\nclass ReferencesFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.ReferencesRequest.type);\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'references').dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.referencesProvider);\n if (!options) {\n return;\n }\n this.register({ id: UUID.generateUuid(), registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideReferences: (document, position, options, token) => {\n const client = this._client;\n const _providerReferences = (document, position, options, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, client.code2ProtocolConverter.asReferenceParams(document, position, options), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asReferences(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideReferences\n ? middleware.provideReferences(document, position, options, token, _providerReferences)\n : _providerReferences(document, position, options, token);\n }\n };\n return [this.registerProvider(selector, provider), provider];\n }\n registerProvider(selector, provider) {\n return vscode_1.languages.registerReferenceProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);\n }\n}\nexports.ReferencesFeature = ReferencesFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CodeActionFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst UUID = require(\"./utils/uuid\");\nconst features_1 = require(\"./features\");\nclass CodeActionFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.CodeActionRequest.type);\n }\n fillClientCapabilities(capabilities) {\n const cap = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'codeAction');\n cap.dynamicRegistration = true;\n cap.isPreferredSupport = true;\n cap.disabledSupport = true;\n cap.dataSupport = true;\n // We can only resolve the edit property.\n cap.resolveSupport = {\n properties: ['edit']\n };\n cap.codeActionLiteralSupport = {\n codeActionKind: {\n valueSet: [\n vscode_languageserver_protocol_1.CodeActionKind.Empty,\n vscode_languageserver_protocol_1.CodeActionKind.QuickFix,\n vscode_languageserver_protocol_1.CodeActionKind.Refactor,\n vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract,\n vscode_languageserver_protocol_1.CodeActionKind.RefactorInline,\n vscode_languageserver_protocol_1.CodeActionKind.RefactorRewrite,\n vscode_languageserver_protocol_1.CodeActionKind.Source,\n vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports\n ]\n }\n };\n cap.honorsChangeAnnotations = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.codeActionProvider);\n if (!options) {\n return;\n }\n this.register({ id: UUID.generateUuid(), registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideCodeActions: (document, range, context, token) => {\n const client = this._client;\n const _provideCodeActions = async (document, range, context, token) => {\n const params = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n range: client.code2ProtocolConverter.asRange(range),\n context: client.code2ProtocolConverter.asCodeActionContextSync(context)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, params, token).then((values) => {\n if (token.isCancellationRequested || values === null || values === undefined) {\n return null;\n }\n return client.protocol2CodeConverter.asCodeActionResult(values, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideCodeActions\n ? middleware.provideCodeActions(document, range, context, token, _provideCodeActions)\n : _provideCodeActions(document, range, context, token);\n },\n resolveCodeAction: options.resolveProvider\n ? (item, token) => {\n const client = this._client;\n const middleware = this._client.middleware;\n const resolveCodeAction = async (item, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, client.code2ProtocolConverter.asCodeActionSync(item), token).then((result) => {\n if (token.isCancellationRequested) {\n return item;\n }\n return client.protocol2CodeConverter.asCodeAction(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, token, error, item);\n });\n };\n return middleware.resolveCodeAction\n ? middleware.resolveCodeAction(item, token, resolveCodeAction)\n : resolveCodeAction(item, token);\n }\n : undefined\n };\n return [vscode_1.languages.registerCodeActionsProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, (options.codeActionKinds\n ? { providedCodeActionKinds: this._client.protocol2CodeConverter.asCodeActionKinds(options.codeActionKinds) }\n : undefined)), provider];\n }\n}\nexports.CodeActionFeature = CodeActionFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CodeLensFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst UUID = require(\"./utils/uuid\");\nconst features_1 = require(\"./features\");\nclass CodeLensFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.CodeLensRequest.type);\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'codeLens').dynamicRegistration = true;\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'workspace'), 'codeLens').refreshSupport = true;\n }\n initialize(capabilities, documentSelector) {\n const client = this._client;\n client.onRequest(vscode_languageserver_protocol_1.CodeLensRefreshRequest.type, async () => {\n for (const provider of this.getAllProviders()) {\n provider.onDidChangeCodeLensEmitter.fire();\n }\n });\n const options = this.getRegistrationOptions(documentSelector, capabilities.codeLensProvider);\n if (!options) {\n return;\n }\n this.register({ id: UUID.generateUuid(), registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const eventEmitter = new vscode_1.EventEmitter();\n const provider = {\n onDidChangeCodeLenses: eventEmitter.event,\n provideCodeLenses: (document, token) => {\n const client = this._client;\n const provideCodeLenses = (document, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, client.code2ProtocolConverter.asCodeLensParams(document), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asCodeLenses(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideCodeLenses\n ? middleware.provideCodeLenses(document, token, provideCodeLenses)\n : provideCodeLenses(document, token);\n },\n resolveCodeLens: (options.resolveProvider)\n ? (codeLens, token) => {\n const client = this._client;\n const resolveCodeLens = (codeLens, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, client.code2ProtocolConverter.asCodeLens(codeLens), token).then((result) => {\n if (token.isCancellationRequested) {\n return codeLens;\n }\n return client.protocol2CodeConverter.asCodeLens(result);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, token, error, codeLens);\n });\n };\n const middleware = client.middleware;\n return middleware.resolveCodeLens\n ? middleware.resolveCodeLens(codeLens, token, resolveCodeLens)\n : resolveCodeLens(codeLens, token);\n }\n : undefined\n };\n return [vscode_1.languages.registerCodeLensProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), { provider, onDidChangeCodeLensEmitter: eventEmitter }];\n }\n}\nexports.CodeLensFeature = CodeLensFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DocumentOnTypeFormattingFeature = exports.DocumentRangeFormattingFeature = exports.DocumentFormattingFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst UUID = require(\"./utils/uuid\");\nconst features_1 = require(\"./features\");\nvar FileFormattingOptions;\n(function (FileFormattingOptions) {\n function fromConfiguration(document) {\n const filesConfig = vscode_1.workspace.getConfiguration('files', document);\n return {\n trimTrailingWhitespace: filesConfig.get('trimTrailingWhitespace'),\n trimFinalNewlines: filesConfig.get('trimFinalNewlines'),\n insertFinalNewline: filesConfig.get('insertFinalNewline'),\n };\n }\n FileFormattingOptions.fromConfiguration = fromConfiguration;\n})(FileFormattingOptions || (FileFormattingOptions = {}));\nclass DocumentFormattingFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.DocumentFormattingRequest.type);\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'formatting').dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.documentFormattingProvider);\n if (!options) {\n return;\n }\n this.register({ id: UUID.generateUuid(), registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideDocumentFormattingEdits: (document, options, token) => {\n const client = this._client;\n const provideDocumentFormattingEdits = (document, options, token) => {\n const params = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n options: client.code2ProtocolConverter.asFormattingOptions(options, FileFormattingOptions.fromConfiguration(document))\n };\n return client.sendRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asTextEdits(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideDocumentFormattingEdits\n ? middleware.provideDocumentFormattingEdits(document, options, token, provideDocumentFormattingEdits)\n : provideDocumentFormattingEdits(document, options, token);\n }\n };\n return [vscode_1.languages.registerDocumentFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];\n }\n}\nexports.DocumentFormattingFeature = DocumentFormattingFeature;\nclass DocumentRangeFormattingFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type);\n }\n fillClientCapabilities(capabilities) {\n const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'rangeFormatting');\n capability.dynamicRegistration = true;\n capability.rangesSupport = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.documentRangeFormattingProvider);\n if (!options) {\n return;\n }\n this.register({ id: UUID.generateUuid(), registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideDocumentRangeFormattingEdits: (document, range, options, token) => {\n const client = this._client;\n const provideDocumentRangeFormattingEdits = (document, range, options, token) => {\n const params = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n range: client.code2ProtocolConverter.asRange(range),\n options: client.code2ProtocolConverter.asFormattingOptions(options, FileFormattingOptions.fromConfiguration(document))\n };\n return client.sendRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asTextEdits(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideDocumentRangeFormattingEdits\n ? middleware.provideDocumentRangeFormattingEdits(document, range, options, token, provideDocumentRangeFormattingEdits)\n : provideDocumentRangeFormattingEdits(document, range, options, token);\n }\n };\n if (options.rangesSupport) {\n provider.provideDocumentRangesFormattingEdits = (document, ranges, options, token) => {\n const client = this._client;\n const provideDocumentRangesFormattingEdits = (document, ranges, options, token) => {\n const params = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n ranges: client.code2ProtocolConverter.asRanges(ranges),\n options: client.code2ProtocolConverter.asFormattingOptions(options, FileFormattingOptions.fromConfiguration(document))\n };\n return client.sendRequest(vscode_languageserver_protocol_1.DocumentRangesFormattingRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asTextEdits(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentRangesFormattingRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideDocumentRangesFormattingEdits\n ? middleware.provideDocumentRangesFormattingEdits(document, ranges, options, token, provideDocumentRangesFormattingEdits)\n : provideDocumentRangesFormattingEdits(document, ranges, options, token);\n };\n }\n return [vscode_1.languages.registerDocumentRangeFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];\n }\n}\nexports.DocumentRangeFormattingFeature = DocumentRangeFormattingFeature;\nclass DocumentOnTypeFormattingFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type);\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'onTypeFormatting').dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.documentOnTypeFormattingProvider);\n if (!options) {\n return;\n }\n this.register({ id: UUID.generateUuid(), registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideOnTypeFormattingEdits: (document, position, ch, options, token) => {\n const client = this._client;\n const provideOnTypeFormattingEdits = (document, position, ch, options, token) => {\n let params = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n position: client.code2ProtocolConverter.asPosition(position),\n ch: ch,\n options: client.code2ProtocolConverter.asFormattingOptions(options, FileFormattingOptions.fromConfiguration(document))\n };\n return client.sendRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asTextEdits(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideOnTypeFormattingEdits\n ? middleware.provideOnTypeFormattingEdits(document, position, ch, options, token, provideOnTypeFormattingEdits)\n : provideOnTypeFormattingEdits(document, position, ch, options, token);\n }\n };\n const moreTriggerCharacter = options.moreTriggerCharacter || [];\n return [vscode_1.languages.registerOnTypeFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, options.firstTriggerCharacter, ...moreTriggerCharacter), provider];\n }\n}\nexports.DocumentOnTypeFormattingFeature = DocumentOnTypeFormattingFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RenameFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst UUID = require(\"./utils/uuid\");\nconst Is = require(\"./utils/is\");\nconst features_1 = require(\"./features\");\nclass RenameFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.RenameRequest.type);\n }\n fillClientCapabilities(capabilities) {\n let rename = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'rename');\n rename.dynamicRegistration = true;\n rename.prepareSupport = true;\n rename.prepareSupportDefaultBehavior = vscode_languageserver_protocol_1.PrepareSupportDefaultBehavior.Identifier;\n rename.honorsChangeAnnotations = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.renameProvider);\n if (!options) {\n return;\n }\n if (Is.boolean(capabilities.renameProvider)) {\n options.prepareProvider = false;\n }\n this.register({ id: UUID.generateUuid(), registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideRenameEdits: (document, position, newName, token) => {\n const client = this._client;\n const provideRenameEdits = (document, position, newName, token) => {\n let params = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n position: client.code2ProtocolConverter.asPosition(position),\n newName: newName\n };\n return client.sendRequest(vscode_languageserver_protocol_1.RenameRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asWorkspaceEdit(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.RenameRequest.type, token, error, null, false);\n });\n };\n const middleware = client.middleware;\n return middleware.provideRenameEdits\n ? middleware.provideRenameEdits(document, position, newName, token, provideRenameEdits)\n : provideRenameEdits(document, position, newName, token);\n },\n prepareRename: options.prepareProvider\n ? (document, position, token) => {\n const client = this._client;\n const prepareRename = (document, position, token) => {\n let params = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n position: client.code2ProtocolConverter.asPosition(position),\n };\n return client.sendRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n if (vscode_languageserver_protocol_1.Range.is(result)) {\n return client.protocol2CodeConverter.asRange(result);\n }\n else if (this.isDefaultBehavior(result)) {\n return result.defaultBehavior === true\n ? null\n : Promise.reject(new Error(`The element can't be renamed.`));\n }\n else if (result && vscode_languageserver_protocol_1.Range.is(result.range)) {\n return {\n range: client.protocol2CodeConverter.asRange(result.range),\n placeholder: result.placeholder\n };\n }\n // To cancel the rename vscode API expects a rejected promise.\n return Promise.reject(new Error(`The element can't be renamed.`));\n }, (error) => {\n if (typeof error.message === 'string') {\n throw new Error(error.message);\n }\n else {\n throw new Error(`The element can't be renamed.`);\n }\n });\n };\n const middleware = client.middleware;\n return middleware.prepareRename\n ? middleware.prepareRename(document, position, token, prepareRename)\n : prepareRename(document, position, token);\n }\n : undefined\n };\n return [this.registerProvider(selector, provider), provider];\n }\n registerProvider(selector, provider) {\n return vscode_1.languages.registerRenameProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);\n }\n isDefaultBehavior(value) {\n const candidate = value;\n return candidate && Is.boolean(candidate.defaultBehavior);\n }\n}\nexports.RenameFeature = RenameFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DocumentLinkFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst UUID = require(\"./utils/uuid\");\nclass DocumentLinkFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.DocumentLinkRequest.type);\n }\n fillClientCapabilities(capabilities) {\n const documentLinkCapabilities = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'documentLink');\n documentLinkCapabilities.dynamicRegistration = true;\n documentLinkCapabilities.tooltipSupport = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.documentLinkProvider);\n if (!options) {\n return;\n }\n this.register({ id: UUID.generateUuid(), registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideDocumentLinks: (document, token) => {\n const client = this._client;\n const provideDocumentLinks = (document, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, client.code2ProtocolConverter.asDocumentLinkParams(document), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asDocumentLinks(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideDocumentLinks\n ? middleware.provideDocumentLinks(document, token, provideDocumentLinks)\n : provideDocumentLinks(document, token);\n },\n resolveDocumentLink: options.resolveProvider\n ? (link, token) => {\n const client = this._client;\n let resolveDocumentLink = (link, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, client.code2ProtocolConverter.asDocumentLink(link), token).then((result) => {\n if (token.isCancellationRequested) {\n return link;\n }\n return client.protocol2CodeConverter.asDocumentLink(result);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, token, error, link);\n });\n };\n const middleware = client.middleware;\n return middleware.resolveDocumentLink\n ? middleware.resolveDocumentLink(link, token, resolveDocumentLink)\n : resolveDocumentLink(link, token);\n }\n : undefined\n };\n return [vscode_1.languages.registerDocumentLinkProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];\n }\n}\nexports.DocumentLinkFeature = DocumentLinkFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ExecuteCommandFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst UUID = require(\"./utils/uuid\");\nconst features_1 = require(\"./features\");\nclass ExecuteCommandFeature {\n constructor(client) {\n this._client = client;\n this._commands = new Map();\n }\n getState() {\n return { kind: 'workspace', id: this.registrationType.method, registrations: this._commands.size > 0 };\n }\n get registrationType() {\n return vscode_languageserver_protocol_1.ExecuteCommandRequest.type;\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'workspace'), 'executeCommand').dynamicRegistration = true;\n }\n initialize(capabilities) {\n if (!capabilities.executeCommandProvider) {\n return;\n }\n this.register({\n id: UUID.generateUuid(),\n registerOptions: Object.assign({}, capabilities.executeCommandProvider)\n });\n }\n register(data) {\n const client = this._client;\n const middleware = client.middleware;\n const executeCommand = (command, args) => {\n let params = {\n command,\n arguments: args\n };\n return client.sendRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, params).then(undefined, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, undefined, error, undefined);\n });\n };\n if (data.registerOptions.commands) {\n const disposables = [];\n for (const command of data.registerOptions.commands) {\n disposables.push(vscode_1.commands.registerCommand(command, (...args) => {\n return middleware.executeCommand\n ? middleware.executeCommand(command, args, executeCommand)\n : executeCommand(command, args);\n }));\n }\n this._commands.set(data.id, disposables);\n }\n }\n unregister(id) {\n let disposables = this._commands.get(id);\n if (disposables) {\n disposables.forEach(disposable => disposable.dispose());\n }\n }\n clear() {\n this._commands.forEach((value) => {\n value.forEach(disposable => disposable.dispose());\n });\n this._commands.clear();\n }\n}\nexports.ExecuteCommandFeature = ExecuteCommandFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FileSystemWatcherFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass FileSystemWatcherFeature {\n constructor(client, notifyFileEvent) {\n this._client = client;\n this._notifyFileEvent = notifyFileEvent;\n this._watchers = new Map();\n }\n getState() {\n return { kind: 'workspace', id: this.registrationType.method, registrations: this._watchers.size > 0 };\n }\n get registrationType() {\n return vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type;\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'workspace'), 'didChangeWatchedFiles').dynamicRegistration = true;\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'workspace'), 'didChangeWatchedFiles').relativePatternSupport = true;\n }\n initialize(_capabilities, _documentSelector) {\n }\n register(data) {\n if (!Array.isArray(data.registerOptions.watchers)) {\n return;\n }\n const disposables = [];\n for (const watcher of data.registerOptions.watchers) {\n const globPattern = this._client.protocol2CodeConverter.asGlobPattern(watcher.globPattern);\n if (globPattern === undefined) {\n continue;\n }\n let watchCreate = true, watchChange = true, watchDelete = true;\n if (watcher.kind !== undefined && watcher.kind !== null) {\n watchCreate = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Create) !== 0;\n watchChange = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Change) !== 0;\n watchDelete = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Delete) !== 0;\n }\n const fileSystemWatcher = vscode_1.workspace.createFileSystemWatcher(globPattern, !watchCreate, !watchChange, !watchDelete);\n this.hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, disposables);\n disposables.push(fileSystemWatcher);\n }\n this._watchers.set(data.id, disposables);\n }\n registerRaw(id, fileSystemWatchers) {\n let disposables = [];\n for (let fileSystemWatcher of fileSystemWatchers) {\n this.hookListeners(fileSystemWatcher, true, true, true, disposables);\n }\n this._watchers.set(id, disposables);\n }\n hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, listeners) {\n if (watchCreate) {\n fileSystemWatcher.onDidCreate((resource) => this._notifyFileEvent({\n uri: this._client.code2ProtocolConverter.asUri(resource),\n type: vscode_languageserver_protocol_1.FileChangeType.Created\n }), null, listeners);\n }\n if (watchChange) {\n fileSystemWatcher.onDidChange((resource) => this._notifyFileEvent({\n uri: this._client.code2ProtocolConverter.asUri(resource),\n type: vscode_languageserver_protocol_1.FileChangeType.Changed\n }), null, listeners);\n }\n if (watchDelete) {\n fileSystemWatcher.onDidDelete((resource) => this._notifyFileEvent({\n uri: this._client.code2ProtocolConverter.asUri(resource),\n type: vscode_languageserver_protocol_1.FileChangeType.Deleted\n }), null, listeners);\n }\n }\n unregister(id) {\n let disposables = this._watchers.get(id);\n if (disposables) {\n for (let disposable of disposables) {\n disposable.dispose();\n }\n }\n }\n clear() {\n this._watchers.forEach((disposables) => {\n for (let disposable of disposables) {\n disposable.dispose();\n }\n });\n this._watchers.clear();\n }\n}\nexports.FileSystemWatcherFeature = FileSystemWatcherFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ColorProviderFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass ColorProviderFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.DocumentColorRequest.type);\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'colorProvider').dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n let [id, options] = this.getRegistration(documentSelector, capabilities.colorProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideColorPresentations: (color, context, token) => {\n const client = this._client;\n const provideColorPresentations = (color, context, token) => {\n const requestParams = {\n color,\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(context.document),\n range: client.code2ProtocolConverter.asRange(context.range)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, requestParams, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return this._client.protocol2CodeConverter.asColorPresentations(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideColorPresentations\n ? middleware.provideColorPresentations(color, context, token, provideColorPresentations)\n : provideColorPresentations(color, context, token);\n },\n provideDocumentColors: (document, token) => {\n const client = this._client;\n const provideDocumentColors = (document, token) => {\n const requestParams = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, requestParams, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return this._client.protocol2CodeConverter.asColorInformations(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideDocumentColors\n ? middleware.provideDocumentColors(document, token, provideDocumentColors)\n : provideDocumentColors(document, token);\n }\n };\n return [vscode_1.languages.registerColorProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];\n }\n}\nexports.ColorProviderFeature = ColorProviderFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ImplementationFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass ImplementationFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.ImplementationRequest.type);\n }\n fillClientCapabilities(capabilities) {\n let implementationSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'implementation');\n implementationSupport.dynamicRegistration = true;\n implementationSupport.linkSupport = true;\n }\n initialize(capabilities, documentSelector) {\n let [id, options] = this.getRegistration(documentSelector, capabilities.implementationProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideImplementation: (document, position, token) => {\n const client = this._client;\n const provideImplementation = (document, position, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asDefinitionResult(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideImplementation\n ? middleware.provideImplementation(document, position, token, provideImplementation)\n : provideImplementation(document, position, token);\n }\n };\n return [this.registerProvider(selector, provider), provider];\n }\n registerProvider(selector, provider) {\n return vscode_1.languages.registerImplementationProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);\n }\n}\nexports.ImplementationFeature = ImplementationFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TypeDefinitionFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass TypeDefinitionFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.TypeDefinitionRequest.type);\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'typeDefinition').dynamicRegistration = true;\n let typeDefinitionSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'typeDefinition');\n typeDefinitionSupport.dynamicRegistration = true;\n typeDefinitionSupport.linkSupport = true;\n }\n initialize(capabilities, documentSelector) {\n let [id, options] = this.getRegistration(documentSelector, capabilities.typeDefinitionProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideTypeDefinition: (document, position, token) => {\n const client = this._client;\n const provideTypeDefinition = (document, position, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asDefinitionResult(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideTypeDefinition\n ? middleware.provideTypeDefinition(document, position, token, provideTypeDefinition)\n : provideTypeDefinition(document, position, token);\n }\n };\n return [this.registerProvider(selector, provider), provider];\n }\n registerProvider(selector, provider) {\n return vscode_1.languages.registerTypeDefinitionProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);\n }\n}\nexports.TypeDefinitionFeature = TypeDefinitionFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WorkspaceFoldersFeature = exports.arrayDiff = void 0;\nconst UUID = require(\"./utils/uuid\");\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nfunction access(target, key) {\n if (target === undefined || target === null) {\n return undefined;\n }\n return target[key];\n}\nfunction arrayDiff(left, right) {\n return left.filter(element => right.indexOf(element) < 0);\n}\nexports.arrayDiff = arrayDiff;\nclass WorkspaceFoldersFeature {\n constructor(client) {\n this._client = client;\n this._listeners = new Map();\n }\n getState() {\n return { kind: 'workspace', id: this.registrationType.method, registrations: this._listeners.size > 0 };\n }\n get registrationType() {\n return vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type;\n }\n fillInitializeParams(params) {\n const folders = vscode_1.workspace.workspaceFolders;\n this.initializeWithFolders(folders);\n if (folders === void 0) {\n params.workspaceFolders = null;\n }\n else {\n params.workspaceFolders = folders.map(folder => this.asProtocol(folder));\n }\n }\n initializeWithFolders(currentWorkspaceFolders) {\n this._initialFolders = currentWorkspaceFolders;\n }\n fillClientCapabilities(capabilities) {\n capabilities.workspace = capabilities.workspace || {};\n capabilities.workspace.workspaceFolders = true;\n }\n initialize(capabilities) {\n const client = this._client;\n client.onRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type, (token) => {\n const workspaceFolders = () => {\n const folders = vscode_1.workspace.workspaceFolders;\n if (folders === undefined) {\n return null;\n }\n const result = folders.map((folder) => {\n return this.asProtocol(folder);\n });\n return result;\n };\n const middleware = client.middleware.workspace;\n return middleware && middleware.workspaceFolders\n ? middleware.workspaceFolders(token, workspaceFolders)\n : workspaceFolders(token);\n });\n const value = access(access(access(capabilities, 'workspace'), 'workspaceFolders'), 'changeNotifications');\n let id;\n if (typeof value === 'string') {\n id = value;\n }\n else if (value === true) {\n id = UUID.generateUuid();\n }\n if (id) {\n this.register({ id: id, registerOptions: undefined });\n }\n }\n sendInitialEvent(currentWorkspaceFolders) {\n let promise;\n if (this._initialFolders && currentWorkspaceFolders) {\n const removed = arrayDiff(this._initialFolders, currentWorkspaceFolders);\n const added = arrayDiff(currentWorkspaceFolders, this._initialFolders);\n if (added.length > 0 || removed.length > 0) {\n promise = this.doSendEvent(added, removed);\n }\n }\n else if (this._initialFolders) {\n promise = this.doSendEvent([], this._initialFolders);\n }\n else if (currentWorkspaceFolders) {\n promise = this.doSendEvent(currentWorkspaceFolders, []);\n }\n if (promise !== undefined) {\n promise.catch((error) => {\n this._client.error(`Sending notification ${vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type.method} failed`, error);\n });\n }\n }\n doSendEvent(addedFolders, removedFolders) {\n let params = {\n event: {\n added: addedFolders.map(folder => this.asProtocol(folder)),\n removed: removedFolders.map(folder => this.asProtocol(folder))\n }\n };\n return this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, params);\n }\n register(data) {\n let id = data.id;\n let client = this._client;\n let disposable = vscode_1.workspace.onDidChangeWorkspaceFolders((event) => {\n let didChangeWorkspaceFolders = (event) => {\n return this.doSendEvent(event.added, event.removed);\n };\n let middleware = client.middleware.workspace;\n const promise = middleware && middleware.didChangeWorkspaceFolders\n ? middleware.didChangeWorkspaceFolders(event, didChangeWorkspaceFolders)\n : didChangeWorkspaceFolders(event);\n promise.catch((error) => {\n this._client.error(`Sending notification ${vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type.method} failed`, error);\n });\n });\n this._listeners.set(id, disposable);\n this.sendInitialEvent(vscode_1.workspace.workspaceFolders);\n }\n unregister(id) {\n let disposable = this._listeners.get(id);\n if (disposable === void 0) {\n return;\n }\n this._listeners.delete(id);\n disposable.dispose();\n }\n clear() {\n for (let disposable of this._listeners.values()) {\n disposable.dispose();\n }\n this._listeners.clear();\n }\n asProtocol(workspaceFolder) {\n if (workspaceFolder === void 0) {\n return null;\n }\n return { uri: this._client.code2ProtocolConverter.asUri(workspaceFolder.uri), name: workspaceFolder.name };\n }\n}\nexports.WorkspaceFoldersFeature = WorkspaceFoldersFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FoldingRangeFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass FoldingRangeFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.FoldingRangeRequest.type);\n }\n fillClientCapabilities(capabilities) {\n let capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'foldingRange');\n capability.dynamicRegistration = true;\n capability.rangeLimit = 5000;\n capability.lineFoldingOnly = true;\n capability.foldingRangeKind = { valueSet: [vscode_languageserver_protocol_1.FoldingRangeKind.Comment, vscode_languageserver_protocol_1.FoldingRangeKind.Imports, vscode_languageserver_protocol_1.FoldingRangeKind.Region] };\n capability.foldingRange = { collapsedText: false };\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'workspace'), 'foldingRange').refreshSupport = true;\n }\n initialize(capabilities, documentSelector) {\n this._client.onRequest(vscode_languageserver_protocol_1.FoldingRangeRefreshRequest.type, async () => {\n for (const provider of this.getAllProviders()) {\n provider.onDidChangeFoldingRange.fire();\n }\n });\n let [id, options] = this.getRegistration(documentSelector, capabilities.foldingRangeProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const eventEmitter = new vscode_1.EventEmitter();\n const provider = {\n onDidChangeFoldingRanges: eventEmitter.event,\n provideFoldingRanges: (document, context, token) => {\n const client = this._client;\n const provideFoldingRanges = (document, _, token) => {\n const requestParams = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, requestParams, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asFoldingRanges(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideFoldingRanges\n ? middleware.provideFoldingRanges(document, context, token, provideFoldingRanges)\n : provideFoldingRanges(document, context, token);\n }\n };\n return [vscode_1.languages.registerFoldingRangeProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), { provider: provider, onDidChangeFoldingRange: eventEmitter }];\n }\n}\nexports.FoldingRangeFeature = FoldingRangeFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DeclarationFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass DeclarationFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.DeclarationRequest.type);\n }\n fillClientCapabilities(capabilities) {\n const declarationSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'declaration');\n declarationSupport.dynamicRegistration = true;\n declarationSupport.linkSupport = true;\n }\n initialize(capabilities, documentSelector) {\n const [id, options] = this.getRegistration(documentSelector, capabilities.declarationProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideDeclaration: (document, position, token) => {\n const client = this._client;\n const provideDeclaration = (document, position, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asDeclarationResult(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideDeclaration\n ? middleware.provideDeclaration(document, position, token, provideDeclaration)\n : provideDeclaration(document, position, token);\n }\n };\n return [this.registerProvider(selector, provider), provider];\n }\n registerProvider(selector, provider) {\n return vscode_1.languages.registerDeclarationProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);\n }\n}\nexports.DeclarationFeature = DeclarationFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SelectionRangeFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass SelectionRangeFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.SelectionRangeRequest.type);\n }\n fillClientCapabilities(capabilities) {\n const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'selectionRange');\n capability.dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n const [id, options] = this.getRegistration(documentSelector, capabilities.selectionRangeProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideSelectionRanges: (document, positions, token) => {\n const client = this._client;\n const provideSelectionRanges = async (document, positions, token) => {\n const requestParams = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n positions: client.code2ProtocolConverter.asPositionsSync(positions, token)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, requestParams, token).then((ranges) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asSelectionRanges(ranges, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideSelectionRanges\n ? middleware.provideSelectionRanges(document, positions, token, provideSelectionRanges)\n : provideSelectionRanges(document, positions, token);\n }\n };\n return [this.registerProvider(selector, provider), provider];\n }\n registerProvider(selector, provider) {\n return vscode_1.languages.registerSelectionRangeProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);\n }\n}\nexports.SelectionRangeFeature = SelectionRangeFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ProgressFeature = void 0;\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst progressPart_1 = require(\"./progressPart\");\nfunction ensure(target, key) {\n if (target[key] === void 0) {\n target[key] = Object.create(null);\n }\n return target[key];\n}\nclass ProgressFeature {\n constructor(_client) {\n this._client = _client;\n this.activeParts = new Set();\n }\n getState() {\n return { kind: 'window', id: vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.method, registrations: this.activeParts.size > 0 };\n }\n fillClientCapabilities(capabilities) {\n ensure(capabilities, 'window').workDoneProgress = true;\n }\n initialize() {\n const client = this._client;\n const deleteHandler = (part) => {\n this.activeParts.delete(part);\n };\n const createHandler = (params) => {\n this.activeParts.add(new progressPart_1.ProgressPart(this._client, params.token, deleteHandler));\n };\n client.onRequest(vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.type, createHandler);\n }\n clear() {\n for (const part of this.activeParts) {\n part.done();\n }\n this.activeParts.clear();\n }\n}\nexports.ProgressFeature = ProgressFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CallHierarchyFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass CallHierarchyProvider {\n constructor(client) {\n this.client = client;\n this.middleware = client.middleware;\n }\n prepareCallHierarchy(document, position, token) {\n const client = this.client;\n const middleware = this.middleware;\n const prepareCallHierarchy = (document, position, token) => {\n const params = client.code2ProtocolConverter.asTextDocumentPositionParams(document, position);\n return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asCallHierarchyItems(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, token, error, null);\n });\n };\n return middleware.prepareCallHierarchy\n ? middleware.prepareCallHierarchy(document, position, token, prepareCallHierarchy)\n : prepareCallHierarchy(document, position, token);\n }\n provideCallHierarchyIncomingCalls(item, token) {\n const client = this.client;\n const middleware = this.middleware;\n const provideCallHierarchyIncomingCalls = (item, token) => {\n const params = {\n item: client.code2ProtocolConverter.asCallHierarchyItem(item)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asCallHierarchyIncomingCalls(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type, token, error, null);\n });\n };\n return middleware.provideCallHierarchyIncomingCalls\n ? middleware.provideCallHierarchyIncomingCalls(item, token, provideCallHierarchyIncomingCalls)\n : provideCallHierarchyIncomingCalls(item, token);\n }\n provideCallHierarchyOutgoingCalls(item, token) {\n const client = this.client;\n const middleware = this.middleware;\n const provideCallHierarchyOutgoingCalls = (item, token) => {\n const params = {\n item: client.code2ProtocolConverter.asCallHierarchyItem(item)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asCallHierarchyOutgoingCalls(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type, token, error, null);\n });\n };\n return middleware.provideCallHierarchyOutgoingCalls\n ? middleware.provideCallHierarchyOutgoingCalls(item, token, provideCallHierarchyOutgoingCalls)\n : provideCallHierarchyOutgoingCalls(item, token);\n }\n}\nclass CallHierarchyFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type);\n }\n fillClientCapabilities(cap) {\n const capabilities = cap;\n const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'callHierarchy');\n capability.dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n const [id, options] = this.getRegistration(documentSelector, capabilities.callHierarchyProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const client = this._client;\n const provider = new CallHierarchyProvider(client);\n return [vscode_1.languages.registerCallHierarchyProvider(this._client.protocol2CodeConverter.asDocumentSelector(options.documentSelector), provider), provider];\n }\n}\nexports.CallHierarchyFeature = CallHierarchyFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SemanticTokensFeature = void 0;\nconst vscode = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst Is = require(\"./utils/is\");\nclass SemanticTokensFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.SemanticTokensRegistrationType.type);\n }\n fillClientCapabilities(capabilities) {\n const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'semanticTokens');\n capability.dynamicRegistration = true;\n capability.tokenTypes = [\n vscode_languageserver_protocol_1.SemanticTokenTypes.namespace,\n vscode_languageserver_protocol_1.SemanticTokenTypes.type,\n vscode_languageserver_protocol_1.SemanticTokenTypes.class,\n vscode_languageserver_protocol_1.SemanticTokenTypes.enum,\n vscode_languageserver_protocol_1.SemanticTokenTypes.interface,\n vscode_languageserver_protocol_1.SemanticTokenTypes.struct,\n vscode_languageserver_protocol_1.SemanticTokenTypes.typeParameter,\n vscode_languageserver_protocol_1.SemanticTokenTypes.parameter,\n vscode_languageserver_protocol_1.SemanticTokenTypes.variable,\n vscode_languageserver_protocol_1.SemanticTokenTypes.property,\n vscode_languageserver_protocol_1.SemanticTokenTypes.enumMember,\n vscode_languageserver_protocol_1.SemanticTokenTypes.event,\n vscode_languageserver_protocol_1.SemanticTokenTypes.function,\n vscode_languageserver_protocol_1.SemanticTokenTypes.method,\n vscode_languageserver_protocol_1.SemanticTokenTypes.macro,\n vscode_languageserver_protocol_1.SemanticTokenTypes.keyword,\n vscode_languageserver_protocol_1.SemanticTokenTypes.modifier,\n vscode_languageserver_protocol_1.SemanticTokenTypes.comment,\n vscode_languageserver_protocol_1.SemanticTokenTypes.string,\n vscode_languageserver_protocol_1.SemanticTokenTypes.number,\n vscode_languageserver_protocol_1.SemanticTokenTypes.regexp,\n vscode_languageserver_protocol_1.SemanticTokenTypes.operator,\n vscode_languageserver_protocol_1.SemanticTokenTypes.decorator\n ];\n capability.tokenModifiers = [\n vscode_languageserver_protocol_1.SemanticTokenModifiers.declaration,\n vscode_languageserver_protocol_1.SemanticTokenModifiers.definition,\n vscode_languageserver_protocol_1.SemanticTokenModifiers.readonly,\n vscode_languageserver_protocol_1.SemanticTokenModifiers.static,\n vscode_languageserver_protocol_1.SemanticTokenModifiers.deprecated,\n vscode_languageserver_protocol_1.SemanticTokenModifiers.abstract,\n vscode_languageserver_protocol_1.SemanticTokenModifiers.async,\n vscode_languageserver_protocol_1.SemanticTokenModifiers.modification,\n vscode_languageserver_protocol_1.SemanticTokenModifiers.documentation,\n vscode_languageserver_protocol_1.SemanticTokenModifiers.defaultLibrary\n ];\n capability.formats = [vscode_languageserver_protocol_1.TokenFormat.Relative];\n capability.requests = {\n range: true,\n full: {\n delta: true\n }\n };\n capability.multilineTokenSupport = false;\n capability.overlappingTokenSupport = false;\n capability.serverCancelSupport = true;\n capability.augmentsSyntaxTokens = true;\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'workspace'), 'semanticTokens').refreshSupport = true;\n }\n initialize(capabilities, documentSelector) {\n const client = this._client;\n client.onRequest(vscode_languageserver_protocol_1.SemanticTokensRefreshRequest.type, async () => {\n for (const provider of this.getAllProviders()) {\n provider.onDidChangeSemanticTokensEmitter.fire();\n }\n });\n const [id, options] = this.getRegistration(documentSelector, capabilities.semanticTokensProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const fullProvider = Is.boolean(options.full) ? options.full : options.full !== undefined;\n const hasEditProvider = options.full !== undefined && typeof options.full !== 'boolean' && options.full.delta === true;\n const eventEmitter = new vscode.EventEmitter();\n const documentProvider = fullProvider\n ? {\n onDidChangeSemanticTokens: eventEmitter.event,\n provideDocumentSemanticTokens: (document, token) => {\n const client = this._client;\n const middleware = client.middleware;\n const provideDocumentSemanticTokens = (document, token) => {\n const params = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asSemanticTokens(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensRequest.type, token, error, null);\n });\n };\n return middleware.provideDocumentSemanticTokens\n ? middleware.provideDocumentSemanticTokens(document, token, provideDocumentSemanticTokens)\n : provideDocumentSemanticTokens(document, token);\n },\n provideDocumentSemanticTokensEdits: hasEditProvider\n ? (document, previousResultId, token) => {\n const client = this._client;\n const middleware = client.middleware;\n const provideDocumentSemanticTokensEdits = (document, previousResultId, token) => {\n const params = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n previousResultId\n };\n return client.sendRequest(vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type, params, token).then(async (result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n if (vscode_languageserver_protocol_1.SemanticTokens.is(result)) {\n return await client.protocol2CodeConverter.asSemanticTokens(result, token);\n }\n else {\n return await client.protocol2CodeConverter.asSemanticTokensEdits(result, token);\n }\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type, token, error, null);\n });\n };\n return middleware.provideDocumentSemanticTokensEdits\n ? middleware.provideDocumentSemanticTokensEdits(document, previousResultId, token, provideDocumentSemanticTokensEdits)\n : provideDocumentSemanticTokensEdits(document, previousResultId, token);\n }\n : undefined\n }\n : undefined;\n const hasRangeProvider = options.range === true;\n const rangeProvider = hasRangeProvider\n ? {\n provideDocumentRangeSemanticTokens: (document, range, token) => {\n const client = this._client;\n const middleware = client.middleware;\n const provideDocumentRangeSemanticTokens = (document, range, token) => {\n const params = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n range: client.code2ProtocolConverter.asRange(range)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asSemanticTokens(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type, token, error, null);\n });\n };\n return middleware.provideDocumentRangeSemanticTokens\n ? middleware.provideDocumentRangeSemanticTokens(document, range, token, provideDocumentRangeSemanticTokens)\n : provideDocumentRangeSemanticTokens(document, range, token);\n }\n }\n : undefined;\n const disposables = [];\n const client = this._client;\n const legend = client.protocol2CodeConverter.asSemanticTokensLegend(options.legend);\n const documentSelector = client.protocol2CodeConverter.asDocumentSelector(selector);\n if (documentProvider !== undefined) {\n disposables.push(vscode.languages.registerDocumentSemanticTokensProvider(documentSelector, documentProvider, legend));\n }\n if (rangeProvider !== undefined) {\n disposables.push(vscode.languages.registerDocumentRangeSemanticTokensProvider(documentSelector, rangeProvider, legend));\n }\n return [new vscode.Disposable(() => disposables.forEach(item => item.dispose())), { range: rangeProvider, full: documentProvider, onDidChangeSemanticTokensEmitter: eventEmitter }];\n }\n}\nexports.SemanticTokensFeature = SemanticTokensFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WillDeleteFilesFeature = exports.WillRenameFilesFeature = exports.WillCreateFilesFeature = exports.DidDeleteFilesFeature = exports.DidRenameFilesFeature = exports.DidCreateFilesFeature = void 0;\nconst code = require(\"vscode\");\nconst minimatch = require(\"minimatch\");\nconst proto = require(\"vscode-languageserver-protocol\");\nconst UUID = require(\"./utils/uuid\");\nfunction ensure(target, key) {\n if (target[key] === void 0) {\n target[key] = {};\n }\n return target[key];\n}\nfunction access(target, key) {\n return target[key];\n}\nfunction assign(target, key, value) {\n target[key] = value;\n}\nclass FileOperationFeature {\n constructor(client, event, registrationType, clientCapability, serverCapability) {\n this._client = client;\n this._event = event;\n this._registrationType = registrationType;\n this._clientCapability = clientCapability;\n this._serverCapability = serverCapability;\n this._filters = new Map();\n }\n getState() {\n return { kind: 'workspace', id: this._registrationType.method, registrations: this._filters.size > 0 };\n }\n filterSize() {\n return this._filters.size;\n }\n get registrationType() {\n return this._registrationType;\n }\n fillClientCapabilities(capabilities) {\n const value = ensure(ensure(capabilities, 'workspace'), 'fileOperations');\n // this happens n times but it is the same value so we tolerate this.\n assign(value, 'dynamicRegistration', true);\n assign(value, this._clientCapability, true);\n }\n initialize(capabilities) {\n const options = capabilities.workspace?.fileOperations;\n const capability = options !== undefined ? access(options, this._serverCapability) : undefined;\n if (capability?.filters !== undefined) {\n try {\n this.register({\n id: UUID.generateUuid(),\n registerOptions: { filters: capability.filters }\n });\n }\n catch (e) {\n this._client.warn(`Ignoring invalid glob pattern for ${this._serverCapability} registration: ${e}`);\n }\n }\n }\n register(data) {\n if (!this._listener) {\n this._listener = this._event(this.send, this);\n }\n const minimatchFilter = data.registerOptions.filters.map((filter) => {\n const matcher = new minimatch.Minimatch(filter.pattern.glob, FileOperationFeature.asMinimatchOptions(filter.pattern.options));\n if (!matcher.makeRe()) {\n throw new Error(`Invalid pattern ${filter.pattern.glob}!`);\n }\n return { scheme: filter.scheme, matcher, kind: filter.pattern.matches };\n });\n this._filters.set(data.id, minimatchFilter);\n }\n unregister(id) {\n this._filters.delete(id);\n if (this._filters.size === 0 && this._listener) {\n this._listener.dispose();\n this._listener = undefined;\n }\n }\n clear() {\n this._filters.clear();\n if (this._listener) {\n this._listener.dispose();\n this._listener = undefined;\n }\n }\n getFileType(uri) {\n return FileOperationFeature.getFileType(uri);\n }\n async filter(event, prop) {\n // (Asynchronously) map each file onto a boolean of whether it matches\n // any of the globs.\n const fileMatches = await Promise.all(event.files.map(async (item) => {\n const uri = prop(item);\n // Use fsPath to make this consistent with file system watchers but help\n // minimatch to use '/' instead of `\\\\` if present.\n const path = uri.fsPath.replace(/\\\\/g, '/');\n for (const filters of this._filters.values()) {\n for (const filter of filters) {\n if (filter.scheme !== undefined && filter.scheme !== uri.scheme) {\n continue;\n }\n if (filter.matcher.match(path)) {\n // The pattern matches. If kind is undefined then everything is ok\n if (filter.kind === undefined) {\n return true;\n }\n const fileType = await this.getFileType(uri);\n // If we can't determine the file type than we treat it as a match.\n // Dropping it would be another alternative.\n if (fileType === undefined) {\n this._client.error(`Failed to determine file type for ${uri.toString()}.`);\n return true;\n }\n if ((fileType === code.FileType.File && filter.kind === proto.FileOperationPatternKind.file) || (fileType === code.FileType.Directory && filter.kind === proto.FileOperationPatternKind.folder)) {\n return true;\n }\n }\n else if (filter.kind === proto.FileOperationPatternKind.folder) {\n const fileType = await FileOperationFeature.getFileType(uri);\n if (fileType === code.FileType.Directory && filter.matcher.match(`${path}/`)) {\n return true;\n }\n }\n }\n }\n return false;\n }));\n // Filter the files to those that matched.\n const files = event.files.filter((_, index) => fileMatches[index]);\n return { ...event, files };\n }\n static async getFileType(uri) {\n try {\n return (await code.workspace.fs.stat(uri)).type;\n }\n catch (e) {\n return undefined;\n }\n }\n static asMinimatchOptions(options) {\n // The spec doesn't state that dot files don't match. So we make\n // matching those the default.\n const result = { dot: true };\n if (options?.ignoreCase === true) {\n result.nocase = true;\n }\n return result;\n }\n}\nclass NotificationFileOperationFeature extends FileOperationFeature {\n constructor(client, event, notificationType, clientCapability, serverCapability, accessUri, createParams) {\n super(client, event, notificationType, clientCapability, serverCapability);\n this._notificationType = notificationType;\n this._accessUri = accessUri;\n this._createParams = createParams;\n }\n async send(originalEvent) {\n // Create a copy of the event that has the files filtered to match what the\n // server wants.\n const filteredEvent = await this.filter(originalEvent, this._accessUri);\n if (filteredEvent.files.length) {\n const next = async (event) => {\n return this._client.sendNotification(this._notificationType, this._createParams(event));\n };\n return this.doSend(filteredEvent, next);\n }\n }\n}\nclass CachingNotificationFileOperationFeature extends NotificationFileOperationFeature {\n constructor() {\n super(...arguments);\n this._fsPathFileTypes = new Map();\n }\n async getFileType(uri) {\n const fsPath = uri.fsPath;\n if (this._fsPathFileTypes.has(fsPath)) {\n return this._fsPathFileTypes.get(fsPath);\n }\n const type = await FileOperationFeature.getFileType(uri);\n if (type) {\n this._fsPathFileTypes.set(fsPath, type);\n }\n return type;\n }\n async cacheFileTypes(event, prop) {\n // Calling filter will force the matching logic to run. For any item\n // that requires a getFileType lookup, the overriden getFileType will\n // be called that will cache the result so that when onDidRename fires,\n // it can still be checked even though the item no longer exists on disk\n // in its original location.\n await this.filter(event, prop);\n }\n clearFileTypeCache() {\n this._fsPathFileTypes.clear();\n }\n unregister(id) {\n super.unregister(id);\n if (this.filterSize() === 0 && this._willListener) {\n this._willListener.dispose();\n this._willListener = undefined;\n }\n }\n clear() {\n super.clear();\n if (this._willListener) {\n this._willListener.dispose();\n this._willListener = undefined;\n }\n }\n}\nclass DidCreateFilesFeature extends NotificationFileOperationFeature {\n constructor(client) {\n super(client, code.workspace.onDidCreateFiles, proto.DidCreateFilesNotification.type, 'didCreate', 'didCreate', (i) => i, client.code2ProtocolConverter.asDidCreateFilesParams);\n }\n doSend(event, next) {\n const middleware = this._client.middleware.workspace;\n return middleware?.didCreateFiles\n ? middleware.didCreateFiles(event, next)\n : next(event);\n }\n}\nexports.DidCreateFilesFeature = DidCreateFilesFeature;\nclass DidRenameFilesFeature extends CachingNotificationFileOperationFeature {\n constructor(client) {\n super(client, code.workspace.onDidRenameFiles, proto.DidRenameFilesNotification.type, 'didRename', 'didRename', (i) => i.oldUri, client.code2ProtocolConverter.asDidRenameFilesParams);\n }\n register(data) {\n if (!this._willListener) {\n this._willListener = code.workspace.onWillRenameFiles(this.willRename, this);\n }\n super.register(data);\n }\n willRename(e) {\n e.waitUntil(this.cacheFileTypes(e, (i) => i.oldUri));\n }\n doSend(event, next) {\n this.clearFileTypeCache();\n const middleware = this._client.middleware.workspace;\n return middleware?.didRenameFiles\n ? middleware.didRenameFiles(event, next)\n : next(event);\n }\n}\nexports.DidRenameFilesFeature = DidRenameFilesFeature;\nclass DidDeleteFilesFeature extends CachingNotificationFileOperationFeature {\n constructor(client) {\n super(client, code.workspace.onDidDeleteFiles, proto.DidDeleteFilesNotification.type, 'didDelete', 'didDelete', (i) => i, client.code2ProtocolConverter.asDidDeleteFilesParams);\n }\n register(data) {\n if (!this._willListener) {\n this._willListener = code.workspace.onWillDeleteFiles(this.willDelete, this);\n }\n super.register(data);\n }\n willDelete(e) {\n e.waitUntil(this.cacheFileTypes(e, (i) => i));\n }\n doSend(event, next) {\n this.clearFileTypeCache();\n const middleware = this._client.middleware.workspace;\n return middleware?.didDeleteFiles\n ? middleware.didDeleteFiles(event, next)\n : next(event);\n }\n}\nexports.DidDeleteFilesFeature = DidDeleteFilesFeature;\nclass RequestFileOperationFeature extends FileOperationFeature {\n constructor(client, event, requestType, clientCapability, serverCapability, accessUri, createParams) {\n super(client, event, requestType, clientCapability, serverCapability);\n this._requestType = requestType;\n this._accessUri = accessUri;\n this._createParams = createParams;\n }\n async send(originalEvent) {\n const waitUntil = this.waitUntil(originalEvent);\n originalEvent.waitUntil(waitUntil);\n }\n async waitUntil(originalEvent) {\n // Create a copy of the event that has the files filtered to match what the\n // server wants.\n const filteredEvent = await this.filter(originalEvent, this._accessUri);\n if (filteredEvent.files.length) {\n const next = (event) => {\n return this._client.sendRequest(this._requestType, this._createParams(event), event.token)\n .then(this._client.protocol2CodeConverter.asWorkspaceEdit);\n };\n return this.doSend(filteredEvent, next);\n }\n else {\n return undefined;\n }\n }\n}\nclass WillCreateFilesFeature extends RequestFileOperationFeature {\n constructor(client) {\n super(client, code.workspace.onWillCreateFiles, proto.WillCreateFilesRequest.type, 'willCreate', 'willCreate', (i) => i, client.code2ProtocolConverter.asWillCreateFilesParams);\n }\n doSend(event, next) {\n const middleware = this._client.middleware.workspace;\n return middleware?.willCreateFiles\n ? middleware.willCreateFiles(event, next)\n : next(event);\n }\n}\nexports.WillCreateFilesFeature = WillCreateFilesFeature;\nclass WillRenameFilesFeature extends RequestFileOperationFeature {\n constructor(client) {\n super(client, code.workspace.onWillRenameFiles, proto.WillRenameFilesRequest.type, 'willRename', 'willRename', (i) => i.oldUri, client.code2ProtocolConverter.asWillRenameFilesParams);\n }\n doSend(event, next) {\n const middleware = this._client.middleware.workspace;\n return middleware?.willRenameFiles\n ? middleware.willRenameFiles(event, next)\n : next(event);\n }\n}\nexports.WillRenameFilesFeature = WillRenameFilesFeature;\nclass WillDeleteFilesFeature extends RequestFileOperationFeature {\n constructor(client) {\n super(client, code.workspace.onWillDeleteFiles, proto.WillDeleteFilesRequest.type, 'willDelete', 'willDelete', (i) => i, client.code2ProtocolConverter.asWillDeleteFilesParams);\n }\n doSend(event, next) {\n const middleware = this._client.middleware.workspace;\n return middleware?.willDeleteFiles\n ? middleware.willDeleteFiles(event, next)\n : next(event);\n }\n}\nexports.WillDeleteFilesFeature = WillDeleteFilesFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LinkedEditingFeature = void 0;\nconst code = require(\"vscode\");\nconst proto = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass LinkedEditingFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, proto.LinkedEditingRangeRequest.type);\n }\n fillClientCapabilities(capabilities) {\n const linkedEditingSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'linkedEditingRange');\n linkedEditingSupport.dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n let [id, options] = this.getRegistration(documentSelector, capabilities.linkedEditingRangeProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideLinkedEditingRanges: (document, position, token) => {\n const client = this._client;\n const provideLinkedEditing = (document, position, token) => {\n return client.sendRequest(proto.LinkedEditingRangeRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asLinkedEditingRanges(result, token);\n }, (error) => {\n return client.handleFailedRequest(proto.LinkedEditingRangeRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideLinkedEditingRange\n ? middleware.provideLinkedEditingRange(document, position, token, provideLinkedEditing)\n : provideLinkedEditing(document, position, token);\n }\n };\n return [this.registerProvider(selector, provider), provider];\n }\n registerProvider(selector, provider) {\n return code.languages.registerLinkedEditingRangeProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);\n }\n}\nexports.LinkedEditingFeature = LinkedEditingFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TypeHierarchyFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass TypeHierarchyProvider {\n constructor(client) {\n this.client = client;\n this.middleware = client.middleware;\n }\n prepareTypeHierarchy(document, position, token) {\n const client = this.client;\n const middleware = this.middleware;\n const prepareTypeHierarchy = (document, position, token) => {\n const params = client.code2ProtocolConverter.asTextDocumentPositionParams(document, position);\n return client.sendRequest(vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asTypeHierarchyItems(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type, token, error, null);\n });\n };\n return middleware.prepareTypeHierarchy\n ? middleware.prepareTypeHierarchy(document, position, token, prepareTypeHierarchy)\n : prepareTypeHierarchy(document, position, token);\n }\n provideTypeHierarchySupertypes(item, token) {\n const client = this.client;\n const middleware = this.middleware;\n const provideTypeHierarchySupertypes = (item, token) => {\n const params = {\n item: client.code2ProtocolConverter.asTypeHierarchyItem(item)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.TypeHierarchySupertypesRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asTypeHierarchyItems(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.TypeHierarchySupertypesRequest.type, token, error, null);\n });\n };\n return middleware.provideTypeHierarchySupertypes\n ? middleware.provideTypeHierarchySupertypes(item, token, provideTypeHierarchySupertypes)\n : provideTypeHierarchySupertypes(item, token);\n }\n provideTypeHierarchySubtypes(item, token) {\n const client = this.client;\n const middleware = this.middleware;\n const provideTypeHierarchySubtypes = (item, token) => {\n const params = {\n item: client.code2ProtocolConverter.asTypeHierarchyItem(item)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.TypeHierarchySubtypesRequest.type, params, token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asTypeHierarchyItems(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.TypeHierarchySubtypesRequest.type, token, error, null);\n });\n };\n return middleware.provideTypeHierarchySubtypes\n ? middleware.provideTypeHierarchySubtypes(item, token, provideTypeHierarchySubtypes)\n : provideTypeHierarchySubtypes(item, token);\n }\n}\nclass TypeHierarchyFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type);\n }\n fillClientCapabilities(capabilities) {\n const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'typeHierarchy');\n capability.dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n const [id, options] = this.getRegistration(documentSelector, capabilities.typeHierarchyProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const client = this._client;\n const provider = new TypeHierarchyProvider(client);\n return [vscode_1.languages.registerTypeHierarchyProvider(client.protocol2CodeConverter.asDocumentSelector(options.documentSelector), provider), provider];\n }\n}\nexports.TypeHierarchyFeature = TypeHierarchyFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InlineValueFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass InlineValueFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.InlineValueRequest.type);\n }\n fillClientCapabilities(capabilities) {\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'inlineValue').dynamicRegistration = true;\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'workspace'), 'inlineValue').refreshSupport = true;\n }\n initialize(capabilities, documentSelector) {\n this._client.onRequest(vscode_languageserver_protocol_1.InlineValueRefreshRequest.type, async () => {\n for (const provider of this.getAllProviders()) {\n provider.onDidChangeInlineValues.fire();\n }\n });\n const [id, options] = this.getRegistration(documentSelector, capabilities.inlineValueProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const eventEmitter = new vscode_1.EventEmitter();\n const provider = {\n onDidChangeInlineValues: eventEmitter.event,\n provideInlineValues: (document, viewPort, context, token) => {\n const client = this._client;\n const provideInlineValues = (document, viewPort, context, token) => {\n const requestParams = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n range: client.code2ProtocolConverter.asRange(viewPort),\n context: client.code2ProtocolConverter.asInlineValueContext(context)\n };\n return client.sendRequest(vscode_languageserver_protocol_1.InlineValueRequest.type, requestParams, token).then((values) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asInlineValues(values, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.InlineValueRequest.type, token, error, null);\n });\n };\n const middleware = client.middleware;\n return middleware.provideInlineValues\n ? middleware.provideInlineValues(document, viewPort, context, token, provideInlineValues)\n : provideInlineValues(document, viewPort, context, token);\n }\n };\n return [this.registerProvider(selector, provider), { provider: provider, onDidChangeInlineValues: eventEmitter }];\n }\n registerProvider(selector, provider) {\n return vscode_1.languages.registerInlineValuesProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);\n }\n}\nexports.InlineValueFeature = InlineValueFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InlayHintsFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nclass InlayHintsFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.InlayHintRequest.type);\n }\n fillClientCapabilities(capabilities) {\n const inlayHint = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'inlayHint');\n inlayHint.dynamicRegistration = true;\n inlayHint.resolveSupport = {\n properties: ['tooltip', 'textEdits', 'label.tooltip', 'label.location', 'label.command']\n };\n (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'workspace'), 'inlayHint').refreshSupport = true;\n }\n initialize(capabilities, documentSelector) {\n this._client.onRequest(vscode_languageserver_protocol_1.InlayHintRefreshRequest.type, async () => {\n for (const provider of this.getAllProviders()) {\n provider.onDidChangeInlayHints.fire();\n }\n });\n const [id, options] = this.getRegistration(documentSelector, capabilities.inlayHintProvider);\n if (!id || !options) {\n return;\n }\n this.register({ id: id, registerOptions: options });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const eventEmitter = new vscode_1.EventEmitter();\n const provider = {\n onDidChangeInlayHints: eventEmitter.event,\n provideInlayHints: (document, viewPort, token) => {\n const client = this._client;\n const provideInlayHints = async (document, viewPort, token) => {\n const requestParams = {\n textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),\n range: client.code2ProtocolConverter.asRange(viewPort)\n };\n try {\n const values = await client.sendRequest(vscode_languageserver_protocol_1.InlayHintRequest.type, requestParams, token);\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asInlayHints(values, token);\n }\n catch (error) {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.InlayHintRequest.type, token, error, null);\n }\n };\n const middleware = client.middleware;\n return middleware.provideInlayHints\n ? middleware.provideInlayHints(document, viewPort, token, provideInlayHints)\n : provideInlayHints(document, viewPort, token);\n }\n };\n provider.resolveInlayHint = options.resolveProvider === true\n ? (hint, token) => {\n const client = this._client;\n const resolveInlayHint = async (item, token) => {\n try {\n const value = await client.sendRequest(vscode_languageserver_protocol_1.InlayHintResolveRequest.type, client.code2ProtocolConverter.asInlayHint(item), token);\n if (token.isCancellationRequested) {\n return null;\n }\n const result = client.protocol2CodeConverter.asInlayHint(value, token);\n return token.isCancellationRequested ? null : result;\n }\n catch (error) {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.InlayHintResolveRequest.type, token, error, null);\n }\n };\n const middleware = client.middleware;\n return middleware.resolveInlayHint\n ? middleware.resolveInlayHint(hint, token, resolveInlayHint)\n : resolveInlayHint(hint, token);\n }\n : undefined;\n return [this.registerProvider(selector, provider), { provider: provider, onDidChangeInlayHints: eventEmitter }];\n }\n registerProvider(selector, provider) {\n return vscode_1.languages.registerInlayHintsProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);\n }\n}\nexports.InlayHintsFeature = InlayHintsFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InlineCompletionItemFeature = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst features_1 = require(\"./features\");\nconst UUID = require(\"./utils/uuid\");\nclass InlineCompletionItemFeature extends features_1.TextDocumentLanguageFeature {\n constructor(client) {\n super(client, vscode_languageserver_protocol_1.InlineCompletionRequest.type);\n }\n fillClientCapabilities(capabilities) {\n let inlineCompletion = (0, features_1.ensure)((0, features_1.ensure)(capabilities, 'textDocument'), 'inlineCompletion');\n inlineCompletion.dynamicRegistration = true;\n }\n initialize(capabilities, documentSelector) {\n const options = this.getRegistrationOptions(documentSelector, capabilities.inlineCompletionProvider);\n if (!options) {\n return;\n }\n this.register({\n id: UUID.generateUuid(),\n registerOptions: options\n });\n }\n registerLanguageProvider(options) {\n const selector = options.documentSelector;\n const provider = {\n provideInlineCompletionItems: (document, position, context, token) => {\n const client = this._client;\n const middleware = this._client.middleware;\n const provideInlineCompletionItems = (document, position, context, token) => {\n return client.sendRequest(vscode_languageserver_protocol_1.InlineCompletionRequest.type, client.code2ProtocolConverter.asInlineCompletionParams(document, position, context), token).then((result) => {\n if (token.isCancellationRequested) {\n return null;\n }\n return client.protocol2CodeConverter.asInlineCompletionResult(result, token);\n }, (error) => {\n return client.handleFailedRequest(vscode_languageserver_protocol_1.InlineCompletionRequest.type, token, error, null);\n });\n };\n return middleware.provideInlineCompletionItems\n ? middleware.provideInlineCompletionItems(document, position, context, token, provideInlineCompletionItems)\n : provideInlineCompletionItems(document, position, context, token);\n }\n };\n return [vscode_1.languages.registerInlineCompletionItemProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];\n }\n}\nexports.InlineCompletionItemFeature = InlineCompletionItemFeature;\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ProposedFeatures = exports.BaseLanguageClient = exports.MessageTransports = exports.SuspendMode = exports.State = exports.CloseAction = exports.ErrorAction = exports.RevealOutputChannelOn = void 0;\nconst vscode_1 = require(\"vscode\");\nconst vscode_languageserver_protocol_1 = require(\"vscode-languageserver-protocol\");\nconst c2p = require(\"./codeConverter\");\nconst p2c = require(\"./protocolConverter\");\nconst Is = require(\"./utils/is\");\nconst async_1 = require(\"./utils/async\");\nconst UUID = require(\"./utils/uuid\");\nconst progressPart_1 = require(\"./progressPart\");\nconst features_1 = require(\"./features\");\nconst diagnostic_1 = require(\"./diagnostic\");\nconst notebook_1 = require(\"./notebook\");\nconst configuration_1 = require(\"./configuration\");\nconst textSynchronization_1 = require(\"./textSynchronization\");\nconst completion_1 = require(\"./completion\");\nconst hover_1 = require(\"./hover\");\nconst definition_1 = require(\"./definition\");\nconst signatureHelp_1 = require(\"./signatureHelp\");\nconst documentHighlight_1 = require(\"./documentHighlight\");\nconst documentSymbol_1 = require(\"./documentSymbol\");\nconst workspaceSymbol_1 = require(\"./workspaceSymbol\");\nconst reference_1 = require(\"./reference\");\nconst codeAction_1 = require(\"./codeAction\");\nconst codeLens_1 = require(\"./codeLens\");\nconst formatting_1 = require(\"./formatting\");\nconst rename_1 = require(\"./rename\");\nconst documentLink_1 = require(\"./documentLink\");\nconst executeCommand_1 = require(\"./executeCommand\");\nconst fileSystemWatcher_1 = require(\"./fileSystemWatcher\");\nconst colorProvider_1 = require(\"./colorProvider\");\nconst implementation_1 = require(\"./implementation\");\nconst typeDefinition_1 = require(\"./typeDefinition\");\nconst workspaceFolder_1 = require(\"./workspaceFolder\");\nconst foldingRange_1 = require(\"./foldingRange\");\nconst declaration_1 = require(\"./declaration\");\nconst selectionRange_1 = require(\"./selectionRange\");\nconst progress_1 = require(\"./progress\");\nconst callHierarchy_1 = require(\"./callHierarchy\");\nconst semanticTokens_1 = require(\"./semanticTokens\");\nconst fileOperations_1 = require(\"./fileOperations\");\nconst linkedEditingRange_1 = require(\"./linkedEditingRange\");\nconst typeHierarchy_1 = require(\"./typeHierarchy\");\nconst inlineValue_1 = require(\"./inlineValue\");\nconst inlayHint_1 = require(\"./inlayHint\");\nconst inlineCompletion_1 = require(\"./inlineCompletion\");\n/**\n * Controls when the output channel is revealed.\n */\nvar RevealOutputChannelOn;\n(function (RevealOutputChannelOn) {\n RevealOutputChannelOn[RevealOutputChannelOn[\"Debug\"] = 0] = \"Debug\";\n RevealOutputChannelOn[RevealOutputChannelOn[\"Info\"] = 1] = \"Info\";\n RevealOutputChannelOn[RevealOutputChannelOn[\"Warn\"] = 2] = \"Warn\";\n RevealOutputChannelOn[RevealOutputChannelOn[\"Error\"] = 3] = \"Error\";\n RevealOutputChannelOn[RevealOutputChannelOn[\"Never\"] = 4] = \"Never\";\n})(RevealOutputChannelOn || (exports.RevealOutputChannelOn = RevealOutputChannelOn = {}));\n/**\n * An action to be performed when the connection is producing errors.\n */\nvar ErrorAction;\n(function (ErrorAction) {\n /**\n * Continue running the server.\n */\n ErrorAction[ErrorAction[\"Continue\"] = 1] = \"Continue\";\n /**\n * Shutdown the server.\n */\n ErrorAction[ErrorAction[\"Shutdown\"] = 2] = \"Shutdown\";\n})(ErrorAction || (exports.ErrorAction = ErrorAction = {}));\n/**\n * An action to be performed when the connection to a server got closed.\n */\nvar CloseAction;\n(function (CloseAction) {\n /**\n * Don't restart the server. The connection stays closed.\n */\n CloseAction[CloseAction[\"DoNotRestart\"] = 1] = \"DoNotRestart\";\n /**\n * Restart the server.\n */\n CloseAction[CloseAction[\"Restart\"] = 2] = \"Restart\";\n})(CloseAction || (exports.CloseAction = CloseAction = {}));\n/**\n * Signals in which state the language client is in.\n */\nvar State;\n(function (State) {\n /**\n * The client is stopped or got never started.\n */\n State[State[\"Stopped\"] = 1] = \"Stopped\";\n /**\n * The client is starting but not ready yet.\n */\n State[State[\"Starting\"] = 3] = \"Starting\";\n /**\n * The client is running and ready.\n */\n State[State[\"Running\"] = 2] = \"Running\";\n})(State || (exports.State = State = {}));\nvar SuspendMode;\n(function (SuspendMode) {\n /**\n * Don't allow suspend mode.\n */\n SuspendMode[\"off\"] = \"off\";\n /**\n * Support suspend mode even if not all\n * registered providers have a corresponding\n * activation listener.\n */\n SuspendMode[\"on\"] = \"on\";\n})(SuspendMode || (exports.SuspendMode = SuspendMode = {}));\nvar ResolvedClientOptions;\n(function (ResolvedClientOptions) {\n function sanitizeIsTrusted(isTrusted) {\n if (isTrusted === undefined || isTrusted === null) {\n return false;\n }\n if ((typeof isTrusted === 'boolean') || (typeof isTrusted === 'object' && isTrusted !== null && Is.stringArray(isTrusted.enabledCommands))) {\n return isTrusted;\n }\n return false;\n }\n ResolvedClientOptions.sanitizeIsTrusted = sanitizeIsTrusted;\n})(ResolvedClientOptions || (ResolvedClientOptions = {}));\nclass DefaultErrorHandler {\n constructor(client, maxRestartCount) {\n this.client = client;\n this.maxRestartCount = maxRestartCount;\n this.restarts = [];\n }\n error(_error, _message, count) {\n if (count && count <= 3) {\n return { action: ErrorAction.Continue };\n }\n return { action: ErrorAction.Shutdown };\n }\n closed() {\n this.restarts.push(Date.now());\n if (this.restarts.length <= this.maxRestartCount) {\n return { action: CloseAction.Restart };\n }\n else {\n let diff = this.restarts[this.restarts.length - 1] - this.restarts[0];\n if (diff <= 3 * 60 * 1000) {\n return { action: CloseAction.DoNotRestart, message: `The ${this.client.name} server crashed ${this.maxRestartCount + 1} times in the last 3 minutes. The server will not be restarted. See the output for more information.` };\n }\n else {\n this.restarts.shift();\n return { action: CloseAction.Restart };\n }\n }\n }\n}\nvar ClientState;\n(function (ClientState) {\n ClientState[\"Initial\"] = \"initial\";\n ClientState[\"Starting\"] = \"starting\";\n ClientState[\"StartFailed\"] = \"startFailed\";\n ClientState[\"Running\"] = \"running\";\n ClientState[\"Stopping\"] = \"stopping\";\n ClientState[\"Stopped\"] = \"stopped\";\n})(ClientState || (ClientState = {}));\nvar MessageTransports;\n(function (MessageTransports) {\n function is(value) {\n let candidate = value;\n return candidate && vscode_languageserver_protocol_1.MessageReader.is(value.reader) && vscode_languageserver_protocol_1.MessageWriter.is(value.writer);\n }\n MessageTransports.is = is;\n})(MessageTransports || (exports.MessageTransports = MessageTransports = {}));\nclass BaseLanguageClient {\n constructor(id, name, clientOptions) {\n this._traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text;\n this._diagnosticQueue = new Map();\n this._diagnosticQueueState = { state: 'idle' };\n this._features = [];\n this._dynamicFeatures = new Map();\n this.workspaceEditLock = new async_1.Semaphore(1);\n this._id = id;\n this._name = name;\n clientOptions = clientOptions || {};\n const markdown = { isTrusted: false, supportHtml: false };\n if (clientOptions.markdown !== undefined) {\n markdown.isTrusted = ResolvedClientOptions.sanitizeIsTrusted(clientOptions.markdown.isTrusted);\n markdown.supportHtml = clientOptions.markdown.supportHtml === true;\n }\n // const defaultInterval = (clientOptions as TestOptions).$testMode ? 50 : 60000;\n this._clientOptions = {\n documentSelector: clientOptions.documentSelector ?? [],\n synchronize: clientOptions.synchronize ?? {},\n diagnosticCollectionName: clientOptions.diagnosticCollectionName,\n outputChannelName: clientOptions.outputChannelName ?? this._name,\n revealOutputChannelOn: clientOptions.revealOutputChannelOn ?? RevealOutputChannelOn.Error,\n stdioEncoding: clientOptions.stdioEncoding ?? 'utf8',\n initializationOptions: clientOptions.initializationOptions,\n initializationFailedHandler: clientOptions.initializationFailedHandler,\n progressOnInitialization: !!clientOptions.progressOnInitialization,\n errorHandler: clientOptions.errorHandler ?? this.createDefaultErrorHandler(clientOptions.connectionOptions?.maxRestartCount),\n middleware: clientOptions.middleware ?? {},\n uriConverters: clientOptions.uriConverters,\n workspaceFolder: clientOptions.workspaceFolder,\n connectionOptions: clientOptions.connectionOptions,\n markdown,\n // suspend: {\n // \tmode: clientOptions.suspend?.mode ?? SuspendMode.off,\n // \tcallback: clientOptions.suspend?.callback ?? (() => Promise.resolve(true)),\n // \tinterval: clientOptions.suspend?.interval ? Math.max(clientOptions.suspend.interval, defaultInterval) : defaultInterval\n // },\n diagnosticPullOptions: clientOptions.diagnosticPullOptions ?? { onChange: true, onSave: false },\n notebookDocumentOptions: clientOptions.notebookDocumentOptions ?? {}\n };\n this._clientOptions.synchronize = this._clientOptions.synchronize || {};\n this._state = ClientState.Initial;\n this._ignoredRegistrations = new Set();\n this._listeners = [];\n this._notificationHandlers = new Map();\n this._pendingNotificationHandlers = new Map();\n this._notificationDisposables = new Map();\n this._requestHandlers = new Map();\n this._pendingRequestHandlers = new Map();\n this._requestDisposables = new Map();\n this._progressHandlers = new Map();\n this._pendingProgressHandlers = new Map();\n this._progressDisposables = new Map();\n this._connection = undefined;\n // this._idleStart = undefined;\n this._initializeResult = undefined;\n if (clientOptions.outputChannel) {\n this._outputChannel = clientOptions.outputChannel;\n this._disposeOutputChannel = false;\n }\n else {\n this._outputChannel = undefined;\n this._disposeOutputChannel = true;\n }\n this._traceOutputChannel = clientOptions.traceOutputChannel;\n this._diagnostics = undefined;\n this._pendingOpenNotifications = new Set();\n this._pendingChangeSemaphore = new async_1.Semaphore(1);\n this._pendingChangeDelayer = new async_1.Delayer(250);\n this._fileEvents = [];\n this._fileEventDelayer = new async_1.Delayer(250);\n this._onStop = undefined;\n this._telemetryEmitter = new vscode_languageserver_protocol_1.Emitter();\n this._stateChangeEmitter = new vscode_languageserver_protocol_1.Emitter();\n this._trace = vscode_languageserver_protocol_1.Trace.Off;\n this._tracer = {\n log: (messageOrDataObject, data) => {\n if (Is.string(messageOrDataObject)) {\n this.logTrace(messageOrDataObject, data);\n }\n else {\n this.logObjectTrace(messageOrDataObject);\n }\n },\n };\n this._c2p = c2p.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.code2Protocol : undefined);\n this._p2c = p2c.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.protocol2Code : undefined, this._clientOptions.markdown.isTrusted, this._clientOptions.markdown.supportHtml);\n this._syncedDocuments = new Map();\n this.registerBuiltinFeatures();\n }\n get name() {\n return this._name;\n }\n get middleware() {\n return this._clientOptions.middleware ?? Object.create(null);\n }\n get clientOptions() {\n return this._clientOptions;\n }\n get protocol2CodeConverter() {\n return this._p2c;\n }\n get code2ProtocolConverter() {\n return this._c2p;\n }\n get onTelemetry() {\n return this._telemetryEmitter.event;\n }\n get onDidChangeState() {\n return this._stateChangeEmitter.event;\n }\n get outputChannel() {\n if (!this._outputChannel) {\n this._outputChannel = vscode_1.window.createOutputChannel(this._clientOptions.outputChannelName ? this._clientOptions.outputChannelName : this._name);\n }\n return this._outputChannel;\n }\n get traceOutputChannel() {\n if (this._traceOutputChannel) {\n return this._traceOutputChannel;\n }\n return this.outputChannel;\n }\n get diagnostics() {\n return this._diagnostics;\n }\n get state() {\n return this.getPublicState();\n }\n get $state() {\n return this._state;\n }\n set $state(value) {\n let oldState = this.getPublicState();\n this._state = value;\n let newState = this.getPublicState();\n if (newState !== oldState) {\n this._stateChangeEmitter.fire({ oldState, newState });\n }\n }\n getPublicState() {\n switch (this.$state) {\n case ClientState.Starting:\n return State.Starting;\n case ClientState.Running:\n return State.Running;\n default:\n return State.Stopped;\n }\n }\n get initializeResult() {\n return this._initializeResult;\n }\n async sendRequest(type, ...params) {\n if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) {\n return Promise.reject(new vscode_languageserver_protocol_1.ResponseError(vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive, `Client is not running`));\n }\n // Ensure we have a connection before we force the document sync.\n const connection = await this.$start();\n // If any document is synced in full mode make sure we flush any pending\n // full document syncs.\n if (this._didChangeTextDocumentFeature.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) {\n await this.sendPendingFullTextDocumentChanges(connection);\n }\n const _sendRequest = this._clientOptions.middleware?.sendRequest;\n if (_sendRequest !== undefined) {\n let param = undefined;\n let token = undefined;\n // Separate cancellation tokens from other parameters for a better client interface\n if (params.length === 1) {\n // CancellationToken is an interface, so we need to check if the first param complies to it\n if (vscode_languageserver_protocol_1.CancellationToken.is(params[0])) {\n token = params[0];\n }\n else {\n param = params[0];\n }\n }\n else if (params.length === 2) {\n param = params[0];\n token = params[1];\n }\n // Return the general middleware invocation defining `next` as a utility function that reorganizes parameters to\n // pass them to the original sendRequest function.\n return _sendRequest(type, param, token, (type, param, token) => {\n const params = [];\n // Add the parameters if there are any\n if (param !== undefined) {\n params.push(param);\n }\n // Add the cancellation token if there is one\n if (token !== undefined) {\n params.push(token);\n }\n return connection.sendRequest(type, ...params);\n });\n }\n else {\n return connection.sendRequest(type, ...params);\n }\n }\n onRequest(type, handler) {\n const method = typeof type === 'string' ? type : type.method;\n this._requestHandlers.set(method, handler);\n const connection = this.activeConnection();\n let disposable;\n if (connection !== undefined) {\n this._requestDisposables.set(method, connection.onRequest(type, handler));\n disposable = {\n dispose: () => {\n const disposable = this._requestDisposables.get(method);\n if (disposable !== undefined) {\n disposable.dispose();\n this._requestDisposables.delete(method);\n }\n }\n };\n }\n else {\n this._pendingRequestHandlers.set(method, handler);\n disposable = {\n dispose: () => {\n this._pendingRequestHandlers.delete(method);\n const disposable = this._requestDisposables.get(method);\n if (disposable !== undefined) {\n disposable.dispose();\n this._requestDisposables.delete(method);\n }\n }\n };\n }\n return {\n dispose: () => {\n this._requestHandlers.delete(method);\n disposable.dispose();\n }\n };\n }\n async sendNotification(type, params) {\n if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) {\n return Promise.reject(new vscode_languageserver_protocol_1.ResponseError(vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive, `Client is not running`));\n }\n const needsPendingFullTextDocumentSync = this._didChangeTextDocumentFeature.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full;\n let openNotification;\n if (needsPendingFullTextDocumentSync && typeof type !== 'string' && type.method === vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.method) {\n openNotification = params?.textDocument.uri;\n this._pendingOpenNotifications.add(openNotification);\n }\n // Ensure we have a connection before we force the document sync.\n const connection = await this.$start();\n // If any document is synced in full mode make sure we flush any pending\n // full document syncs.\n if (needsPendingFullTextDocumentSync) {\n await this.sendPendingFullTextDocumentChanges(connection);\n }\n // We need to remove the pending open notification before we actually\n // send the notification over the connection. Otherwise there could be\n // a request coming in that although the open notification got already put\n // onto the wire will ignore pending document changes.\n //\n // Since the code path of connection.sendNotification is actually sync\n // until the message is handed of to the writer and the writer as a semaphore\n // lock with a capacity of 1 no additional async scheduling can happen until\n // the message is actually handed of.\n if (openNotification !== undefined) {\n this._pendingOpenNotifications.delete(openNotification);\n }\n const _sendNotification = this._clientOptions.middleware?.sendNotification;\n return _sendNotification\n ? _sendNotification(type, connection.sendNotification.bind(connection), params)\n : connection.sendNotification(type, params);\n }\n onNotification(type, handler) {\n const method = typeof type === 'string' ? type : type.method;\n this._notificationHandlers.set(method, handler);\n const connection = this.activeConnection();\n let disposable;\n if (connection !== undefined) {\n this._notificationDisposables.set(method, connection.onNotification(type, handler));\n disposable = {\n dispose: () => {\n const disposable = this._notificationDisposables.get(method);\n if (disposable !== undefined) {\n disposable.dispose();\n this._notificationDisposables.delete(method);\n }\n }\n };\n }\n else {\n this._pendingNotificationHandlers.set(method, handler);\n disposable = {\n dispose: () => {\n this._pendingNotificationHandlers.delete(method);\n const disposable = this._notificationDisposables.get(method);\n if (disposable !== undefined) {\n disposable.dispose();\n this._notificationDisposables.delete(method);\n }\n }\n };\n }\n return {\n dispose: () => {\n this._notificationHandlers.delete(method);\n disposable.dispose();\n }\n };\n }\n async sendProgress(type, token, value) {\n if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) {\n return Promise.reject(new vscode_languageserver_protocol_1.ResponseError(vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive, `Client is not running`));\n }\n try {\n // Ensure we have a connection before we force the document sync.\n const connection = await this.$start();\n return connection.sendProgress(type, token, value);\n }\n catch (error) {\n this.error(`Sending progress for token ${token} failed.`, error);\n throw error;\n }\n }\n onProgress(type, token, handler) {\n this._progressHandlers.set(token, { type, handler });\n const connection = this.activeConnection();\n let disposable;\n const handleWorkDoneProgress = this._clientOptions.middleware?.handleWorkDoneProgress;\n const realHandler = vscode_languageserver_protocol_1.WorkDoneProgress.is(type) && handleWorkDoneProgress !== undefined\n ? (params) => {\n handleWorkDoneProgress(token, params, () => handler(params));\n }\n : handler;\n if (connection !== undefined) {\n this._progressDisposables.set(token, connection.onProgress(type, token, realHandler));\n disposable = {\n dispose: () => {\n const disposable = this._progressDisposables.get(token);\n if (disposable !== undefined) {\n disposable.dispose();\n this._progressDisposables.delete(token);\n }\n }\n };\n }\n else {\n this._pendingProgressHandlers.set(token, { type, handler });\n disposable = {\n dispose: () => {\n this._pendingProgressHandlers.delete(token);\n const disposable = this._progressDisposables.get(token);\n if (disposable !== undefined) {\n disposable.dispose();\n this._progressDisposables.delete(token);\n }\n }\n };\n }\n return {\n dispose: () => {\n this._progressHandlers.delete(token);\n disposable.dispose();\n }\n };\n }\n createDefaultErrorHandler(maxRestartCount) {\n if (maxRestartCount !== undefined && maxRestartCount < 0) {\n throw new Error(`Invalid maxRestartCount: ${maxRestartCount}`);\n }\n return new DefaultErrorHandler(this, maxRestartCount ?? 4);\n }\n async setTrace(value) {\n this._trace = value;\n const connection = this.activeConnection();\n if (connection !== undefined) {\n await connection.trace(this._trace, this._tracer, {\n sendNotification: false,\n traceFormat: this._traceFormat\n });\n }\n }\n data2String(data) {\n if (data instanceof vscode_languageserver_protocol_1.ResponseError) {\n const responseError = data;\n return ` Message: ${responseError.message}\\n Code: ${responseError.code} ${responseError.data ? '\\n' + responseError.data.toString() : ''}`;\n }\n if (data instanceof Error) {\n if (Is.string(data.stack)) {\n return data.stack;\n }\n return data.message;\n }\n if (Is.string(data)) {\n return data;\n }\n return data.toString();\n }\n debug(message, data, showNotification = true) {\n this.logOutputMessage(vscode_languageserver_protocol_1.MessageType.Debug, RevealOutputChannelOn.Debug, 'Debug', message, data, showNotification);\n }\n info(message, data, showNotification = true) {\n this.logOutputMessage(vscode_languageserver_protocol_1.MessageType.Info, RevealOutputChannelOn.Info, 'Info', message, data, showNotification);\n }\n warn(message, data, showNotification = true) {\n this.logOutputMessage(vscode_languageserver_protocol_1.MessageType.Warning, RevealOutputChannelOn.Warn, 'Warn', message, data, showNotification);\n }\n error(message, data, showNotification = true) {\n this.logOutputMessage(vscode_languageserver_protocol_1.MessageType.Error, RevealOutputChannelOn.Error, 'Error', message, data, showNotification);\n }\n logOutputMessage(type, reveal, name, message, data, showNotification) {\n this.outputChannel.appendLine(`[${name.padEnd(5)} - ${(new Date().toLocaleTimeString())}] ${message}`);\n if (data !== null && data !== undefined) {\n this.outputChannel.appendLine(this.data2String(data));\n }\n if (showNotification === 'force' || (showNotification && this._clientOptions.revealOutputChannelOn <= reveal)) {\n this.showNotificationMessage(type, message);\n }\n }\n showNotificationMessage(type, message) {\n message = message ?? 'A request has failed. See the output for more information.';\n const messageFunc = type === vscode_languageserver_protocol_1.MessageType.Error\n ? vscode_1.window.showErrorMessage\n : type === vscode_languageserver_protocol_1.MessageType.Warning\n ? vscode_1.window.showWarningMessage\n : vscode_1.window.showInformationMessage;\n void messageFunc(message, 'Go to output').then((selection) => {\n if (selection !== undefined) {\n this.outputChannel.show(true);\n }\n });\n }\n logTrace(message, data) {\n this.traceOutputChannel.appendLine(`[Trace - ${(new Date().toLocaleTimeString())}] ${message}`);\n if (data) {\n this.traceOutputChannel.appendLine(this.data2String(data));\n }\n }\n logObjectTrace(data) {\n if (data.isLSPMessage && data.type) {\n this.traceOutputChannel.append(`[LSP - ${(new Date().toLocaleTimeString())}] `);\n }\n else {\n this.traceOutputChannel.append(`[Trace - ${(new Date().toLocaleTimeString())}] `);\n }\n if (data) {\n this.traceOutputChannel.appendLine(`${JSON.stringify(data)}`);\n }\n }\n needsStart() {\n return this.$state === ClientState.Initial || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped;\n }\n needsStop() {\n return this.$state === ClientState.Starting || this.$state === ClientState.Running;\n }\n activeConnection() {\n return this.$state === ClientState.Running && this._connection !== undefined ? this._connection : undefined;\n }\n isRunning() {\n return this.$state === ClientState.Running;\n }\n async start() {\n if (this._disposed === 'disposing' || this._disposed === 'disposed') {\n throw new Error(`Client got disposed and can't be restarted.`);\n }\n if (this.$state === ClientState.Stopping) {\n throw new Error(`Client is currently stopping. Can only restart a full stopped client`);\n }\n // We are already running or are in the process of getting up\n // to speed.\n if (this._onStart !== undefined) {\n return this._onStart;\n }\n const [promise, resolve, reject] = this.createOnStartPromise();\n this._onStart = promise;\n // If we restart then the diagnostics collection is reused.\n if (this._diagnostics === undefined) {\n this._diagnostics = this._clientOptions.diagnosticCollectionName\n ? vscode_1.languages.createDiagnosticCollection(this._clientOptions.diagnosticCollectionName)\n : vscode_1.languages.createDiagnosticCollection();\n }\n // When we start make all buffer handlers pending so that they\n // get added.\n for (const [method, handler] of this._notificationHandlers) {\n if (!this._pendingNotificationHandlers.has(method)) {\n this._pendingNotificationHandlers.set(method, handler);\n }\n }\n for (const [method, handler] of this._requestHandlers) {\n if (!this._pendingRequestHandlers.has(method)) {\n this._pendingRequestHandlers.set(method, handler);\n }\n }\n for (const [token, data] of this._progressHandlers) {\n if (!this._pendingProgressHandlers.has(token)) {\n this._pendingProgressHandlers.set(token, data);\n }\n }\n this.$state = ClientState.Starting;\n try {\n const connection = await this.createConnection();\n connection.onNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, (message) => {\n switch (message.type) {\n case vscode_languageserver_protocol_1.MessageType.Error:\n this.error(message.message, undefined, false);\n break;\n case vscode_languageserver_protocol_1.MessageType.Warning:\n this.warn(message.message, undefined, false);\n break;\n case vscode_languageserver_protocol_1.MessageType.Info:\n this.info(message.message, undefined, false);\n break;\n case vscode_languageserver_protocol_1.MessageType.Debug:\n this.debug(message.message, undefined, false);\n break;\n default:\n this.outputChannel.appendLine(message.message);\n }\n });\n connection.onNotification(vscode_languageserver_protocol_1.ShowMessageNotification.type, (message) => {\n switch (message.type) {\n case vscode_languageserver_protocol_1.MessageType.Error:\n void vscode_1.window.showErrorMessage(message.message);\n break;\n case vscode_languageserver_protocol_1.MessageType.Warning:\n void vscode_1.window.showWarningMessage(message.message);\n break;\n case vscode_languageserver_protocol_1.MessageType.Info:\n void vscode_1.window.showInformationMessage(message.message);\n break;\n default:\n void vscode_1.window.showInformationMessage(message.message);\n }\n });\n connection.onRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, (params) => {\n let messageFunc;\n switch (params.type) {\n case vscode_languageserver_protocol_1.MessageType.Error:\n messageFunc = vscode_1.window.showErrorMessage;\n break;\n case vscode_languageserver_protocol_1.MessageType.Warning:\n messageFunc = vscode_1.window.showWarningMessage;\n break;\n case vscode_languageserver_protocol_1.MessageType.Info:\n messageFunc = vscode_1.window.showInformationMessage;\n break;\n default:\n messageFunc = vscode_1.window.showInformationMessage;\n }\n let actions = params.actions || [];\n return messageFunc(params.message, ...actions);\n });\n connection.onNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, (data) => {\n this._telemetryEmitter.fire(data);\n });\n connection.onRequest(vscode_languageserver_protocol_1.ShowDocumentRequest.type, async (params) => {\n const showDocument = async (params) => {\n const uri = this.protocol2CodeConverter.asUri(params.uri);\n try {\n if (params.external === true) {\n const success = await vscode_1.env.openExternal(uri);\n return { success };\n }\n else {\n const options = {};\n if (params.selection !== undefined) {\n options.selection = this.protocol2CodeConverter.asRange(params.selection);\n }\n if (params.takeFocus === undefined || params.takeFocus === false) {\n options.preserveFocus = true;\n }\n else if (params.takeFocus === true) {\n options.preserveFocus = false;\n }\n await vscode_1.window.showTextDocument(uri, options);\n return { success: true };\n }\n }\n catch (error) {\n return { success: false };\n }\n };\n const middleware = this._clientOptions.middleware.window?.showDocument;\n if (middleware !== undefined) {\n return middleware(params, showDocument);\n }\n else {\n return showDocument(params);\n }\n });\n connection.listen();\n await this.initialize(connection);\n resolve();\n }\n catch (error) {\n this.$state = ClientState.StartFailed;\n this.error(`${this._name} client: couldn't create connection to server.`, error, 'force');\n reject(error);\n }\n return this._onStart;\n }\n createOnStartPromise() {\n let resolve;\n let reject;\n const promise = new Promise((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n return [promise, resolve, reject];\n }\n async initialize(connection) {\n this.refreshTrace(connection, false);\n const initOption = this._clientOptions.initializationOptions;\n // If the client is locked to a workspace folder use it. In this case the workspace folder\n // feature is not registered and we need to initialize the value here.\n const [rootPath, workspaceFolders] = this._clientOptions.workspaceFolder !== undefined\n ? [this._clientOptions.workspaceFolder.uri.fsPath, [{ uri: this._c2p.asUri(this._clientOptions.workspaceFolder.uri), name: this._clientOptions.workspaceFolder.name }]]\n : [this._clientGetRootPath(), null];\n const initParams = {\n processId: null,\n clientInfo: {\n name: vscode_1.env.appName,\n version: vscode_1.version\n },\n locale: this.getLocale(),\n rootPath: rootPath ? rootPath : null,\n rootUri: rootPath ? this._c2p.asUri(vscode_1.Uri.file(rootPath)) : null,\n capabilities: this.computeClientCapabilities(),\n initializationOptions: Is.func(initOption) ? initOption() : initOption,\n trace: vscode_languageserver_protocol_1.Trace.toString(this._trace),\n workspaceFolders: workspaceFolders\n };\n this.fillInitializeParams(initParams);\n if (this._clientOptions.progressOnInitialization) {\n const token = UUID.generateUuid();\n const part = new progressPart_1.ProgressPart(connection, token);\n initParams.workDoneToken = token;\n try {\n const result = await this.doInitialize(connection, initParams);\n part.done();\n return result;\n }\n catch (error) {\n part.cancel();\n throw error;\n }\n }\n else {\n return this.doInitialize(connection, initParams);\n }\n }\n async doInitialize(connection, initParams) {\n try {\n const result = await connection.initialize(initParams);\n if (result.capabilities.positionEncoding !== undefined && result.capabilities.positionEncoding !== vscode_languageserver_protocol_1.PositionEncodingKind.UTF16) {\n throw new Error(`Unsupported position encoding (${result.capabilities.positionEncoding}) received from server ${this.name}`);\n }\n this._initializeResult = result;\n this.$state = ClientState.Running;\n let textDocumentSyncOptions = undefined;\n if (Is.number(result.capabilities.textDocumentSync)) {\n if (result.capabilities.textDocumentSync === vscode_languageserver_protocol_1.TextDocumentSyncKind.None) {\n textDocumentSyncOptions = {\n openClose: false,\n change: vscode_languageserver_protocol_1.TextDocumentSyncKind.None,\n save: undefined\n };\n }\n else {\n textDocumentSyncOptions = {\n openClose: true,\n change: result.capabilities.textDocumentSync,\n save: {\n includeText: false\n }\n };\n }\n }\n else if (result.capabilities.textDocumentSync !== undefined && result.capabilities.textDocumentSync !== null) {\n textDocumentSyncOptions = result.capabilities.textDocumentSync;\n }\n this._capabilities = Object.assign({}, result.capabilities, { resolvedTextDocumentSync: textDocumentSyncOptions });\n connection.onNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, params => this.handleDiagnostics(params));\n connection.onRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params => this.handleRegistrationRequest(params));\n // See https://github.com/Microsoft/vscode-languageserver-node/issues/199\n connection.onRequest('client/registerFeature', params => this.handleRegistrationRequest(params));\n connection.onRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params => this.handleUnregistrationRequest(params));\n // See https://github.com/Microsoft/vscode-languageserver-node/issues/199\n connection.onRequest('client/unregisterFeature', params => this.handleUnregistrationRequest(params));\n connection.onRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params => this.handleApplyWorkspaceEdit(params));\n // Add pending notification, request and progress handlers.\n for (const [method, handler] of this._pendingNotificationHandlers) {\n this._notificationDisposables.set(method, connection.onNotification(method, handler));\n }\n this._pendingNotificationHandlers.clear();\n for (const [method, handler] of this._pendingRequestHandlers) {\n this._requestDisposables.set(method, connection.onRequest(method, handler));\n }\n this._pendingRequestHandlers.clear();\n for (const [token, data] of this._pendingProgressHandlers) {\n this._progressDisposables.set(token, connection.onProgress(data.type, token, data.handler));\n }\n this._pendingProgressHandlers.clear();\n // if (this._clientOptions.suspend.mode !== SuspendMode.off) {\n // \tthis._idleInterval = RAL().timer.setInterval(() => this.checkSuspend(), this._clientOptions.suspend.interval);\n // }\n await connection.sendNotification(vscode_languageserver_protocol_1.InitializedNotification.type, {});\n this.hookFileEvents(connection);\n this.hookConfigurationChanged(connection);\n this.initializeFeatures(connection);\n return result;\n }\n catch (error) {\n if (this._clientOptions.initializationFailedHandler) {\n if (this._clientOptions.initializationFailedHandler(error)) {\n void this.initialize(connection);\n }\n else {\n void this.stop();\n }\n }\n else if (error instanceof vscode_languageserver_protocol_1.ResponseError && error.data && error.data.retry) {\n void vscode_1.window.showErrorMessage(error.message, { title: 'Retry', id: 'retry' }).then(item => {\n if (item && item.id === 'retry') {\n void this.initialize(connection);\n }\n else {\n void this.stop();\n }\n });\n }\n else {\n if (error && error.message) {\n void vscode_1.window.showErrorMessage(error.message);\n }\n this.error('Server initialization failed.', error);\n void this.stop();\n }\n throw error;\n }\n }\n _clientGetRootPath() {\n let folders = vscode_1.workspace.workspaceFolders;\n if (!folders || folders.length === 0) {\n return undefined;\n }\n let folder = folders[0];\n if (folder.uri.scheme === 'file') {\n return folder.uri.fsPath;\n }\n return undefined;\n }\n stop(timeout = 2000) {\n // Wait 2 seconds on stop\n return this.shutdown('stop', timeout);\n }\n dispose(timeout = 2000) {\n try {\n this._disposed = 'disposing';\n return this.stop(timeout);\n }\n finally {\n this._disposed = 'disposed';\n }\n }\n async shutdown(mode, timeout) {\n // If the client is stopped or in its initial state return.\n if (this.$state === ClientState.Stopped || this.$state === ClientState.Initial) {\n return;\n }\n // If we are stopping the client and have a stop promise return it.\n if (this.$state === ClientState.Stopping) {\n if (this._onStop !== undefined) {\n return this._onStop;\n }\n else {\n throw new Error(`Client is stopping but no stop promise available.`);\n }\n }\n const connection = this.activeConnection();\n // We can't stop a client that is not running (e.g. has no connection). Especially not\n // on that us starting since it can't be correctly synchronized.\n if (connection === undefined || this.$state !== ClientState.Running) {\n throw new Error(`Client is not running and can't be stopped. It's current state is: ${this.$state}`);\n }\n this._initializeResult = undefined;\n this.$state = ClientState.Stopping;\n this.cleanUp(mode);\n const tp = new Promise(c => { (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(c, timeout); });\n const shutdown = (async (connection) => {\n await connection.shutdown();\n await connection.exit();\n return connection;\n })(connection);\n return this._onStop = Promise.race([tp, shutdown]).then((connection) => {\n // The connection won the race with the timeout.\n if (connection !== undefined) {\n connection.end();\n connection.dispose();\n }\n else {\n this.error(`Stopping server timed out`, undefined, false);\n throw new Error(`Stopping the server timed out`);\n }\n }, (error) => {\n this.error(`Stopping server failed`, error, false);\n throw error;\n }).finally(() => {\n this.$state = ClientState.Stopped;\n mode === 'stop' && this.cleanUpChannel();\n this._onStart = undefined;\n this._onStop = undefined;\n this._connection = undefined;\n this._ignoredRegistrations.clear();\n });\n }\n cleanUp(mode) {\n // purge outstanding file events.\n this._fileEvents = [];\n this._fileEventDelayer.cancel();\n const disposables = this._listeners.splice(0, this._listeners.length);\n for (const disposable of disposables) {\n disposable.dispose();\n }\n if (this._syncedDocuments) {\n this._syncedDocuments.clear();\n }\n // Clear features in reverse order;\n for (const feature of Array.from(this._features.entries()).map(entry => entry[1]).reverse()) {\n feature.clear();\n }\n if (mode === 'stop' && this._diagnostics !== undefined) {\n this._diagnostics.dispose();\n this._diagnostics = undefined;\n }\n if (this._idleInterval !== undefined) {\n this._idleInterval.dispose();\n this._idleInterval = undefined;\n }\n // this._idleStart = undefined;\n }\n cleanUpChannel() {\n if (this._outputChannel !== undefined && this._disposeOutputChannel) {\n this._outputChannel.dispose();\n this._outputChannel = undefined;\n }\n }\n notifyFileEvent(event) {\n const client = this;\n async function didChangeWatchedFile(event) {\n client._fileEvents.push(event);\n return client._fileEventDelayer.trigger(async () => {\n await client.sendNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, { changes: client._fileEvents });\n client._fileEvents = [];\n });\n }\n const workSpaceMiddleware = this.clientOptions.middleware?.workspace;\n (workSpaceMiddleware?.didChangeWatchedFile ? workSpaceMiddleware.didChangeWatchedFile(event, didChangeWatchedFile) : didChangeWatchedFile(event)).catch((error) => {\n client.error(`Notify file events failed.`, error);\n });\n }\n async sendPendingFullTextDocumentChanges(connection) {\n return this._pendingChangeSemaphore.lock(async () => {\n try {\n const changes = this._didChangeTextDocumentFeature.getPendingDocumentChanges(this._pendingOpenNotifications);\n if (changes.length === 0) {\n return;\n }\n for (const document of changes) {\n const params = this.code2ProtocolConverter.asChangeTextDocumentParams(document);\n // We await the send and not the delivery since it is more or less the same for\n // notifications.\n await connection.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params);\n this._didChangeTextDocumentFeature.notificationSent(document, vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params);\n }\n }\n catch (error) {\n this.error(`Sending pending changes failed`, error, false);\n throw error;\n }\n });\n }\n triggerPendingChangeDelivery() {\n this._pendingChangeDelayer.trigger(async () => {\n const connection = this.activeConnection();\n if (connection === undefined) {\n this.triggerPendingChangeDelivery();\n return;\n }\n await this.sendPendingFullTextDocumentChanges(connection);\n }).catch((error) => this.error(`Delivering pending changes failed`, error, false));\n }\n handleDiagnostics(params) {\n if (!this._diagnostics) {\n return;\n }\n const key = params.uri;\n if (this._diagnosticQueueState.state === 'busy' && this._diagnosticQueueState.document === key) {\n // Cancel the active run;\n this._diagnosticQueueState.tokenSource.cancel();\n }\n this._diagnosticQueue.set(params.uri, params.diagnostics);\n this.triggerDiagnosticQueue();\n }\n triggerDiagnosticQueue() {\n (0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => { this.workDiagnosticQueue(); });\n }\n workDiagnosticQueue() {\n if (this._diagnosticQueueState.state === 'busy') {\n return;\n }\n const next = this._diagnosticQueue.entries().next();\n if (next.done === true) {\n // Nothing in the queue\n return;\n }\n const [document, diagnostics] = next.value;\n this._diagnosticQueue.delete(document);\n const tokenSource = new vscode_1.CancellationTokenSource();\n this._diagnosticQueueState = { state: 'busy', document: document, tokenSource };\n this._p2c.asDiagnostics(diagnostics, tokenSource.token).then((converted) => {\n if (!tokenSource.token.isCancellationRequested) {\n const uri = this._p2c.asUri(document);\n const middleware = this.clientOptions.middleware;\n if (middleware.handleDiagnostics) {\n middleware.handleDiagnostics(uri, converted, (uri, diagnostics) => this.setDiagnostics(uri, diagnostics));\n }\n else {\n this.setDiagnostics(uri, converted);\n }\n }\n }).finally(() => {\n this._diagnosticQueueState = { state: 'idle' };\n this.triggerDiagnosticQueue();\n });\n }\n setDiagnostics(uri, diagnostics) {\n if (!this._diagnostics) {\n return;\n }\n this._diagnostics.set(uri, diagnostics);\n }\n getLocale() {\n return vscode_1.env.language;\n }\n async $start() {\n if (this.$state === ClientState.StartFailed) {\n throw new Error(`Previous start failed. Can't restart server.`);\n }\n await this.start();\n const connection = this.activeConnection();\n if (connection === undefined) {\n throw new Error(`Starting server failed`);\n }\n return connection;\n }\n async createConnection() {\n let errorHandler = (error, message, count) => {\n this.handleConnectionError(error, message, count).catch((error) => this.error(`Handling connection error failed`, error));\n };\n let closeHandler = () => {\n this.handleConnectionClosed().catch((error) => this.error(`Handling connection close failed`, error));\n };\n const transports = await this.createMessageTransports(this._clientOptions.stdioEncoding || 'utf8');\n this._connection = createConnection(transports.reader, transports.writer, errorHandler, closeHandler, this._clientOptions.connectionOptions);\n return this._connection;\n }\n async handleConnectionClosed() {\n // Check whether this is a normal shutdown in progress or the client stopped normally.\n if (this.$state === ClientState.Stopped) {\n return;\n }\n try {\n if (this._connection !== undefined) {\n this._connection.dispose();\n }\n }\n catch (error) {\n // Disposing a connection could fail if error cases.\n }\n let handlerResult = { action: CloseAction.DoNotRestart };\n if (this.$state !== ClientState.Stopping) {\n try {\n handlerResult = await this._clientOptions.errorHandler.closed();\n }\n catch (error) {\n // Ignore errors coming from the error handler.\n }\n }\n this._connection = undefined;\n if (handlerResult.action === CloseAction.DoNotRestart) {\n this.error(handlerResult.message ?? 'Connection to server got closed. Server will not be restarted.', undefined, handlerResult.handled === true ? false : 'force');\n this.cleanUp('stop');\n if (this.$state === ClientState.Starting) {\n this.$state = ClientState.StartFailed;\n }\n else {\n this.$state = ClientState.Stopped;\n }\n this._onStop = Promise.resolve();\n this._onStart = undefined;\n }\n else if (handlerResult.action === CloseAction.Restart) {\n this.info(handlerResult.message ?? 'Connection to server got closed. Server will restart.', !handlerResult.handled);\n this.cleanUp('restart');\n this.$state = ClientState.Initial;\n this._onStop = Promise.resolve();\n this._onStart = undefined;\n this.start().catch((error) => this.error(`Restarting server failed`, error, 'force'));\n }\n }\n async handleConnectionError(error, message, count) {\n const handlerResult = await this._clientOptions.errorHandler.error(error, message, count);\n if (handlerResult.action === ErrorAction.Shutdown) {\n this.error(handlerResult.message ?? `Client ${this._name}: connection to server is erroring.\\n${error.message}\\nShutting down server.`, undefined, handlerResult.handled === true ? false : 'force');\n this.stop().catch((error) => {\n this.error(`Stopping server failed`, error, false);\n });\n }\n else {\n this.error(handlerResult.message ??\n `Client ${this._name}: connection to server is erroring.\\n${error.message}`, undefined, handlerResult.handled === true ? false : 'force');\n }\n }\n hookConfigurationChanged(connection) {\n this._listeners.push(vscode_1.workspace.onDidChangeConfiguration(() => {\n this.refreshTrace(connection, true);\n }));\n }\n refreshTrace(connection, sendNotification = false) {\n const config = vscode_1.workspace.getConfiguration(this._id);\n let trace = vscode_languageserver_protocol_1.Trace.Off;\n let traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text;\n if (config) {\n const traceConfig = config.get('trace.server', 'off');\n if (typeof traceConfig === 'string') {\n trace = vscode_languageserver_protocol_1.Trace.fromString(traceConfig);\n }\n else {\n trace = vscode_languageserver_protocol_1.Trace.fromString(config.get('trace.server.verbosity', 'off'));\n traceFormat = vscode_languageserver_protocol_1.TraceFormat.fromString(config.get('trace.server.format', 'text'));\n }\n }\n this._trace = trace;\n this._traceFormat = traceFormat;\n connection.trace(this._trace, this._tracer, {\n sendNotification,\n traceFormat: this._traceFormat\n }).catch((error) => { this.error(`Updating trace failed with error`, error, false); });\n }\n hookFileEvents(_connection) {\n let fileEvents = this._clientOptions.synchronize.fileEvents;\n if (!fileEvents) {\n return;\n }\n let watchers;\n if (Is.array(fileEvents)) {\n watchers = fileEvents;\n }\n else {\n watchers = [fileEvents];\n }\n if (!watchers) {\n return;\n }\n this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type.method).registerRaw(UUID.generateUuid(), watchers);\n }\n registerFeatures(features) {\n for (let feature of features) {\n this.registerFeature(feature);\n }\n }\n registerFeature(feature) {\n this._features.push(feature);\n if (features_1.DynamicFeature.is(feature)) {\n const registrationType = feature.registrationType;\n this._dynamicFeatures.set(registrationType.method, feature);\n }\n }\n getFeature(request) {\n return this._dynamicFeatures.get(request);\n }\n hasDedicatedTextSynchronizationFeature(textDocument) {\n const feature = this.getFeature(vscode_languageserver_protocol_1.NotebookDocumentSyncRegistrationType.method);\n if (feature === undefined || !(feature instanceof notebook_1.NotebookDocumentSyncFeature)) {\n return false;\n }\n return feature.handles(textDocument);\n }\n registerBuiltinFeatures() {\n const pendingFullTextDocumentChanges = new Map();\n this.registerFeature(new configuration_1.ConfigurationFeature(this));\n this.registerFeature(new textSynchronization_1.DidOpenTextDocumentFeature(this, this._syncedDocuments));\n this._didChangeTextDocumentFeature = new textSynchronization_1.DidChangeTextDocumentFeature(this, pendingFullTextDocumentChanges);\n this._didChangeTextDocumentFeature.onPendingChangeAdded(() => {\n this.triggerPendingChangeDelivery();\n });\n this.registerFeature(this._didChangeTextDocumentFeature);\n this.registerFeature(new textSynchronization_1.WillSaveFeature(this));\n this.registerFeature(new textSynchronization_1.WillSaveWaitUntilFeature(this));\n this.registerFeature(new textSynchronization_1.DidSaveTextDocumentFeature(this));\n this.registerFeature(new textSynchronization_1.DidCloseTextDocumentFeature(this, this._syncedDocuments, pendingFullTextDocumentChanges));\n this.registerFeature(new fileSystemWatcher_1.FileSystemWatcherFeature(this, (event) => this.notifyFileEvent(event)));\n this.registerFeature(new completion_1.CompletionItemFeature(this));\n this.registerFeature(new hover_1.HoverFeature(this));\n this.registerFeature(new signatureHelp_1.SignatureHelpFeature(this));\n this.registerFeature(new definition_1.DefinitionFeature(this));\n this.registerFeature(new reference_1.ReferencesFeature(this));\n this.registerFeature(new documentHighlight_1.DocumentHighlightFeature(this));\n this.registerFeature(new documentSymbol_1.DocumentSymbolFeature(this));\n this.registerFeature(new workspaceSymbol_1.WorkspaceSymbolFeature(this));\n this.registerFeature(new codeAction_1.CodeActionFeature(this));\n this.registerFeature(new codeLens_1.CodeLensFeature(this));\n this.registerFeature(new formatting_1.DocumentFormattingFeature(this));\n this.registerFeature(new formatting_1.DocumentRangeFormattingFeature(this));\n this.registerFeature(new formatting_1.DocumentOnTypeFormattingFeature(this));\n this.registerFeature(new rename_1.RenameFeature(this));\n this.registerFeature(new documentLink_1.DocumentLinkFeature(this));\n this.registerFeature(new executeCommand_1.ExecuteCommandFeature(this));\n this.registerFeature(new configuration_1.SyncConfigurationFeature(this));\n this.registerFeature(new typeDefinition_1.TypeDefinitionFeature(this));\n this.registerFeature(new implementation_1.ImplementationFeature(this));\n this.registerFeature(new colorProvider_1.ColorProviderFeature(this));\n // We only register the workspace folder feature if the client is not locked\n // to a specific workspace folder.\n if (this.clientOptions.workspaceFolder === undefined) {\n this.registerFeature(new workspaceFolder_1.WorkspaceFoldersFeature(this));\n }\n this.registerFeature(new foldingRange_1.FoldingRangeFeature(this));\n this.registerFeature(new declaration_1.DeclarationFeature(this));\n this.registerFeature(new selectionRange_1.SelectionRangeFeature(this));\n this.registerFeature(new progress_1.ProgressFeature(this));\n this.registerFeature(new callHierarchy_1.CallHierarchyFeature(this));\n this.registerFeature(new semanticTokens_1.SemanticTokensFeature(this));\n this.registerFeature(new linkedEditingRange_1.LinkedEditingFeature(this));\n this.registerFeature(new fileOperations_1.DidCreateFilesFeature(this));\n this.registerFeature(new fileOperations_1.DidRenameFilesFeature(this));\n this.registerFeature(new fileOperations_1.DidDeleteFilesFeature(this));\n this.registerFeature(new fileOperations_1.WillCreateFilesFeature(this));\n this.registerFeature(new fileOperations_1.WillRenameFilesFeature(this));\n this.registerFeature(new fileOperations_1.WillDeleteFilesFeature(this));\n this.registerFeature(new typeHierarchy_1.TypeHierarchyFeature(this));\n this.registerFeature(new inlineValue_1.InlineValueFeature(this));\n this.registerFeature(new inlayHint_1.InlayHintsFeature(this));\n this.registerFeature(new diagnostic_1.DiagnosticFeature(this));\n this.registerFeature(new notebook_1.NotebookDocumentSyncFeature(this));\n }\n registerProposedFeatures() {\n this.registerFeatures(ProposedFeatures.createAll(this));\n }\n fillInitializeParams(params) {\n for (let feature of this._features) {\n if (Is.func(feature.fillInitializeParams)) {\n feature.fillInitializeParams(params);\n }\n }\n }\n computeClientCapabilities() {\n const result = {};\n (0, features_1.ensure)(result, 'workspace').applyEdit = true;\n const workspaceEdit = (0, features_1.ensure)((0, features_1.ensure)(result, 'workspace'), 'workspaceEdit');\n workspaceEdit.documentChanges = true;\n workspaceEdit.resourceOperations = [vscode_languageserver_protocol_1.ResourceOperationKind.Create, vscode_languageserver_protocol_1.ResourceOperationKind.Rename, vscode_languageserver_protocol_1.ResourceOperationKind.Delete];\n workspaceEdit.failureHandling = vscode_languageserver_protocol_1.FailureHandlingKind.TextOnlyTransactional;\n workspaceEdit.normalizesLineEndings = true;\n workspaceEdit.changeAnnotationSupport = {\n groupsOnLabel: true\n };\n const diagnostics = (0, features_1.ensure)((0, features_1.ensure)(result, 'textDocument'), 'publishDiagnostics');\n diagnostics.relatedInformation = true;\n diagnostics.versionSupport = false;\n diagnostics.tagSupport = { valueSet: [vscode_languageserver_protocol_1.DiagnosticTag.Unnecessary, vscode_languageserver_protocol_1.DiagnosticTag.Deprecated] };\n diagnostics.codeDescriptionSupport = true;\n diagnostics.dataSupport = true;\n const windowCapabilities = (0, features_1.ensure)(result, 'window');\n const showMessage = (0, features_1.ensure)(windowCapabilities, 'showMessage');\n showMessage.messageActionItem = { additionalPropertiesSupport: true };\n const showDocument = (0, features_1.ensure)(windowCapabilities, 'showDocument');\n showDocument.support = true;\n const generalCapabilities = (0, features_1.ensure)(result, 'general');\n generalCapabilities.staleRequestSupport = {\n cancel: true,\n retryOnContentModified: Array.from(BaseLanguageClient.RequestsToCancelOnContentModified)\n };\n generalCapabilities.regularExpressions = { engine: 'ECMAScript', version: 'ES2020' };\n generalCapabilities.markdown = {\n parser: 'marked',\n version: '1.1.0',\n };\n generalCapabilities.positionEncodings = ['utf-16'];\n if (this._clientOptions.markdown.supportHtml) {\n generalCapabilities.markdown.allowedTags = ['ul', 'li', 'p', 'code', 'blockquote', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'em', 'pre', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'div', 'del', 'a', 'strong', 'br', 'img', 'span'];\n }\n for (let feature of this._features) {\n feature.fillClientCapabilities(result);\n }\n return result;\n }\n initializeFeatures(_connection) {\n const documentSelector = this._clientOptions.documentSelector;\n for (const feature of this._features) {\n if (Is.func(feature.preInitialize)) {\n feature.preInitialize(this._capabilities, documentSelector);\n }\n }\n for (const feature of this._features) {\n feature.initialize(this._capabilities, documentSelector);\n }\n }\n async handleRegistrationRequest(params) {\n const middleware = this.clientOptions.middleware?.handleRegisterCapability;\n if (middleware) {\n return middleware(params, nextParams => this.doRegisterCapability(nextParams));\n }\n else {\n return this.doRegisterCapability(params);\n }\n }\n async doRegisterCapability(params) {\n // We will not receive a registration call before a client is running\n // from a server. However if we stop or shutdown we might which might\n // try to restart the server. So ignore registrations if we are not running\n if (!this.isRunning()) {\n for (const registration of params.registrations) {\n this._ignoredRegistrations.add(registration.id);\n }\n return;\n }\n for (const registration of params.registrations) {\n const feature = this._dynamicFeatures.get(registration.method);\n if (feature === undefined) {\n return Promise.reject(new Error(`No feature implementation for ${registration.method} found. Registration failed.`));\n }\n const options = registration.registerOptions ?? {};\n options.documentSelector = options.documentSelector ?? this._clientOptions.documentSelector;\n const data = {\n id: registration.id,\n registerOptions: options\n };\n try {\n feature.register(data);\n }\n catch (err) {\n return Promise.reject(err);\n }\n }\n }\n async handleUnregistrationRequest(params) {\n const middleware = this.clientOptions.middleware?.handleUnregisterCapability;\n if (middleware) {\n return middleware(params, nextParams => this.doUnregisterCapability(nextParams));\n }\n else {\n return this.doUnregisterCapability(params);\n }\n }\n async doUnregisterCapability(params) {\n for (const unregistration of params.unregisterations) {\n if (this._ignoredRegistrations.has(unregistration.id)) {\n continue;\n }\n const feature = this._dynamicFeatures.get(unregistration.method);\n if (!feature) {\n return Promise.reject(new Error(`No feature implementation for ${unregistration.method} found. Unregistration failed.`));\n }\n feature.unregister(unregistration.id);\n }\n }\n async handleApplyWorkspaceEdit(params) {\n const workspaceEdit = params.edit;\n // Make sure we convert workspace edits one after the other. Otherwise\n // we might execute a workspace edit received first after we received another\n // one since the conversion might race.\n const converted = await this.workspaceEditLock.lock(() => {\n return this._p2c.asWorkspaceEdit(workspaceEdit);\n });\n // This is some sort of workaround since the version check should be done by VS Code in the Workspace.applyEdit.\n // However doing it here adds some safety since the server can lag more behind then an extension.\n const openTextDocuments = new Map();\n vscode_1.workspace.textDocuments.forEach((document) => openTextDocuments.set(document.uri.toString(), document));\n let versionMismatch = false;\n if (workspaceEdit.documentChanges) {\n for (const change of workspaceEdit.documentChanges) {\n if (vscode_languageserver_protocol_1.TextDocumentEdit.is(change) && change.textDocument.version && change.textDocument.version >= 0) {\n const changeUri = this._p2c.asUri(change.textDocument.uri).toString();\n const textDocument = openTextDocuments.get(changeUri);\n if (textDocument && textDocument.version !== change.textDocument.version) {\n versionMismatch = true;\n break;\n }\n }\n }\n }\n if (versionMismatch) {\n return Promise.resolve({ applied: false });\n }\n return Is.asPromise(vscode_1.workspace.applyEdit(converted).then((value) => { return { applied: value }; }));\n }\n handleFailedRequest(type, token, error, defaultValue, showNotification = true) {\n // If we get a request cancel or a content modified don't log anything.\n if (error instanceof vscode_languageserver_protocol_1.ResponseError) {\n // The connection got disposed while we were waiting for a response.\n // Simply return the default value. Is the best we can do.\n if (error.code === vscode_languageserver_protocol_1.ErrorCodes.PendingResponseRejected || error.code === vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive) {\n return defaultValue;\n }\n if (error.code === vscode_languageserver_protocol_1.LSPErrorCodes.RequestCancelled || error.code === vscode_languageserver_protocol_1.LSPErrorCodes.ServerCancelled) {\n if (token !== undefined && token.isCancellationRequested) {\n return defaultValue;\n }\n else {\n if (error.data !== undefined) {\n throw new features_1.LSPCancellationError(error.data);\n }\n else {\n throw new vscode_1.CancellationError();\n }\n }\n }\n else if (error.code === vscode_languageserver_protocol_1.LSPErrorCodes.ContentModified) {\n if (BaseLanguageClient.RequestsToCancelOnContentModified.has(type.method) || BaseLanguageClient.CancellableResolveCalls.has(type.method)) {\n throw new vscode_1.CancellationError();\n }\n else {\n return defaultValue;\n }\n }\n }\n this.error(`Request ${type.method} failed.`, error, showNotification);\n throw error;\n }\n}\nexports.BaseLanguageClient = BaseLanguageClient;\nBaseLanguageClient.RequestsToCancelOnContentModified = new Set([\n vscode_languageserver_protocol_1.SemanticTokensRequest.method,\n vscode_languageserver_protocol_1.SemanticTokensRangeRequest.method,\n vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.method\n]);\nBaseLanguageClient.CancellableResolveCalls = new Set([\n vscode_languageserver_protocol_1.CompletionResolveRequest.method,\n vscode_languageserver_protocol_1.CodeLensResolveRequest.method,\n vscode_languageserver_protocol_1.CodeActionResolveRequest.method,\n vscode_languageserver_protocol_1.InlayHintResolveRequest.method,\n vscode_languageserver_protocol_1.DocumentLinkResolveRequest.method,\n vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.method\n]);\nclass ConsoleLogger {\n error(message) {\n (0, vscode_languageserver_protocol_1.RAL)().console.error(message);\n }\n warn(message) {\n (0, vscode_languageserver_protocol_1.RAL)().console.warn(message);\n }\n info(message) {\n (0, vscode_languageserver_protocol_1.RAL)().console.info(message);\n }\n log(message) {\n (0, vscode_languageserver_protocol_1.RAL)().console.log(message);\n }\n}\nfunction createConnection(input, output, errorHandler, closeHandler, options) {\n const logger = new ConsoleLogger();\n const connection = (0, vscode_languageserver_protocol_1.createProtocolConnection)(input, output, logger, options);\n connection.onError((data) => { errorHandler(data[0], data[1], data[2]); });\n connection.onClose(closeHandler);\n const result = {\n listen: () => connection.listen(),\n sendRequest: connection.sendRequest,\n onRequest: connection.onRequest,\n hasPendingResponse: connection.hasPendingResponse,\n sendNotification: connection.sendNotification,\n onNotification: connection.onNotification,\n onProgress: connection.onProgress,\n sendProgress: connection.sendProgress,\n trace: (value, tracer, sendNotificationOrTraceOptions) => {\n const defaultTraceOptions = {\n sendNotification: false,\n traceFormat: vscode_languageserver_protocol_1.TraceFormat.Text\n };\n if (sendNotificationOrTraceOptions === undefined) {\n return connection.trace(value, tracer, defaultTraceOptions);\n }\n else if (Is.boolean(sendNotificationOrTraceOptions)) {\n return connection.trace(value, tracer, sendNotificationOrTraceOptions);\n }\n else {\n return connection.trace(value, tracer, sendNotificationOrTraceOptions);\n }\n },\n initialize: (params) => {\n // This needs to return and MUST not be await to avoid any async\n // scheduling. Otherwise messages might overtake each other.\n return connection.sendRequest(vscode_languageserver_protocol_1.InitializeRequest.type, params);\n },\n shutdown: () => {\n // This needs to return and MUST not be await to avoid any async\n // scheduling. Otherwise messages might overtake each other.\n return connection.sendRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, undefined);\n },\n exit: () => {\n // This needs to return and MUST not be await to avoid any async\n // scheduling. Otherwise messages might overtake each other.\n return connection.sendNotification(vscode_languageserver_protocol_1.ExitNotification.type);\n },\n end: () => connection.end(),\n dispose: () => connection.dispose()\n };\n return result;\n}\n// Exporting proposed protocol.\nvar ProposedFeatures;\n(function (ProposedFeatures) {\n function createAll(_client) {\n let result = [\n new inlineCompletion_1.InlineCompletionItemFeature(_client)\n ];\n return result;\n }\n ProposedFeatures.createAll = createAll;\n})(ProposedFeatures || (exports.ProposedFeatures = ProposedFeatures = {}));\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.terminate = void 0;\nconst cp = require(\"child_process\");\nconst path_1 = require(\"path\");\nconst isWindows = (process.platform === 'win32');\nconst isMacintosh = (process.platform === 'darwin');\nconst isLinux = (process.platform === 'linux');\nfunction terminate(process, cwd) {\n if (isWindows) {\n try {\n // This we run in Atom execFileSync is available.\n // Ignore stderr since this is otherwise piped to parent.stderr\n // which might be already closed.\n let options = {\n stdio: ['pipe', 'pipe', 'ignore']\n };\n if (cwd) {\n options.cwd = cwd;\n }\n cp.execFileSync('taskkill', ['/T', '/F', '/PID', process.pid.toString()], options);\n return true;\n }\n catch (err) {\n return false;\n }\n }\n else if (isLinux || isMacintosh) {\n try {\n var cmd = (0, path_1.join)(__dirname, 'terminateProcess.sh');\n var result = cp.spawnSync(cmd, [process.pid.toString()]);\n return result.error ? false : true;\n }\n catch (err) {\n return false;\n }\n }\n else {\n process.kill('SIGKILL');\n return true;\n }\n}\nexports.terminate = terminate;\n", "/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ----------------------------------------------------------------------------------------- */\n'use strict';\n\nmodule.exports = require('./lib/node/main');", "'use strict'\n\nconst debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n", "'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n", "'use strict'\n\nconst {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numeric identifiers include numeric identifiers but can be longer.\n// Therefore non-numeric identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifier, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n", "'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n", "'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a === b ? 0 : a < b ? -1 : 1\n }\n\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n", "'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\n\nconst isPrereleaseIdentifier = (prerelease, identifier) => {\n const identifiers = identifier.split('.')\n if (identifiers.length > prerelease.length) {\n return false\n }\n\n for (let i = 0; i < identifiers.length; i++) {\n if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {\n return false\n }\n }\n\n return true\n}\n\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n if (this.major < other.major) {\n return -1\n }\n if (this.major > other.major) {\n return 1\n }\n if (this.minor < other.minor) {\n return -1\n }\n if (this.minor > other.minor) {\n return 1\n }\n if (this.patch < other.patch) {\n return -1\n }\n if (this.patch > other.patch) {\n return 1\n }\n return 0\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (isPrereleaseIdentifier(this.prerelease, identifier)) {\n const prereleaseBase = this.prerelease[identifier.split('.').length]\n if (isNaN(prereleaseBase)) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n", "'use strict'\n\nclass LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n", "'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // strip build metadata so it can't bleed into the version\n range = range.replace(BUILDSTRIPRE, '')\n\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n src,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\n// unbounded global build-metadata stripper used by parseRange\nconst BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n comp = comp.replace(re[t.BUILD], '')\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DiagnosticPullMode = exports.vsdiag = void 0;\n__exportStar(require(\"vscode-languageserver-protocol\"), exports);\n__exportStar(require(\"./features\"), exports);\nvar diagnostic_1 = require(\"./diagnostic\");\nObject.defineProperty(exports, \"vsdiag\", { enumerable: true, get: function () { return diagnostic_1.vsdiag; } });\nObject.defineProperty(exports, \"DiagnosticPullMode\", { enumerable: true, get: function () { return diagnostic_1.DiagnosticPullMode; } });\n__exportStar(require(\"./client\"), exports);\n", "\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SettingMonitor = exports.LanguageClient = exports.TransportKind = void 0;\nconst cp = require(\"child_process\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\nconst vscode_1 = require(\"vscode\");\nconst Is = require(\"../common/utils/is\");\nconst client_1 = require(\"../common/client\");\nconst processes_1 = require(\"./processes\");\nconst node_1 = require(\"vscode-languageserver-protocol/node\");\n// Import SemVer functions individually to avoid circular dependencies in SemVer\nconst semverParse = require(\"semver/functions/parse\");\nconst semverSatisfies = require(\"semver/functions/satisfies\");\n__exportStar(require(\"vscode-languageserver-protocol/node\"), exports);\n__exportStar(require(\"../common/api\"), exports);\nconst REQUIRED_VSCODE_VERSION = '^1.82.0'; // do not change format, updated by `updateVSCode` script\nvar TransportKind;\n(function (TransportKind) {\n TransportKind[TransportKind[\"stdio\"] = 0] = \"stdio\";\n TransportKind[TransportKind[\"ipc\"] = 1] = \"ipc\";\n TransportKind[TransportKind[\"pipe\"] = 2] = \"pipe\";\n TransportKind[TransportKind[\"socket\"] = 3] = \"socket\";\n})(TransportKind || (exports.TransportKind = TransportKind = {}));\nvar Transport;\n(function (Transport) {\n function isSocket(value) {\n const candidate = value;\n return candidate && candidate.kind === TransportKind.socket && Is.number(candidate.port);\n }\n Transport.isSocket = isSocket;\n})(Transport || (Transport = {}));\nvar Executable;\n(function (Executable) {\n function is(value) {\n return Is.string(value.command);\n }\n Executable.is = is;\n})(Executable || (Executable = {}));\nvar NodeModule;\n(function (NodeModule) {\n function is(value) {\n return Is.string(value.module);\n }\n NodeModule.is = is;\n})(NodeModule || (NodeModule = {}));\nvar StreamInfo;\n(function (StreamInfo) {\n function is(value) {\n let candidate = value;\n return candidate && candidate.writer !== undefined && candidate.reader !== undefined;\n }\n StreamInfo.is = is;\n})(StreamInfo || (StreamInfo = {}));\nvar ChildProcessInfo;\n(function (ChildProcessInfo) {\n function is(value) {\n let candidate = value;\n return candidate && candidate.process !== undefined && typeof candidate.detached === 'boolean';\n }\n ChildProcessInfo.is = is;\n})(ChildProcessInfo || (ChildProcessInfo = {}));\nclass LanguageClient extends client_1.BaseLanguageClient {\n constructor(arg1, arg2, arg3, arg4, arg5) {\n let id;\n let name;\n let serverOptions;\n let clientOptions;\n let forceDebug;\n if (Is.string(arg2)) {\n id = arg1;\n name = arg2;\n serverOptions = arg3;\n clientOptions = arg4;\n forceDebug = !!arg5;\n }\n else {\n id = arg1.toLowerCase();\n name = arg1;\n serverOptions = arg2;\n clientOptions = arg3;\n forceDebug = arg4;\n }\n if (forceDebug === undefined) {\n forceDebug = false;\n }\n super(id, name, clientOptions);\n this._serverOptions = serverOptions;\n this._forceDebug = forceDebug;\n this._isInDebugMode = forceDebug;\n try {\n this.checkVersion();\n }\n catch (error) {\n if (Is.string(error.message)) {\n this.outputChannel.appendLine(error.message);\n }\n throw error;\n }\n }\n checkVersion() {\n const codeVersion = semverParse(vscode_1.version);\n if (!codeVersion) {\n throw new Error(`No valid VS Code version detected. Version string is: ${vscode_1.version}`);\n }\n // Remove the insider pre-release since we stay API compatible.\n if (codeVersion.prerelease && codeVersion.prerelease.length > 0) {\n codeVersion.prerelease = [];\n }\n if (!semverSatisfies(codeVersion, REQUIRED_VSCODE_VERSION)) {\n throw new Error(`The language client requires VS Code version ${REQUIRED_VSCODE_VERSION} but received version ${vscode_1.version}`);\n }\n }\n get isInDebugMode() {\n return this._isInDebugMode;\n }\n async restart() {\n await this.stop();\n // We are in debug mode. Wait a little before we restart\n // so that the debug port can be freed. We can safely ignore\n // the disposable returned from start since it will call\n // stop on the same client instance.\n if (this.isInDebugMode) {\n await new Promise((resolve) => setTimeout(resolve, 1000));\n await this.start();\n }\n else {\n await this.start();\n }\n }\n stop(timeout = 2000) {\n return super.stop(timeout).finally(() => {\n if (this._serverProcess) {\n const toCheck = this._serverProcess;\n this._serverProcess = undefined;\n if (this._isDetached === undefined || !this._isDetached) {\n this.checkProcessDied(toCheck);\n }\n this._isDetached = undefined;\n }\n });\n }\n checkProcessDied(childProcess) {\n if (!childProcess || childProcess.pid === undefined) {\n return;\n }\n setTimeout(() => {\n // Test if the process is still alive. Throws an exception if not\n try {\n if (childProcess.pid !== undefined) {\n process.kill(childProcess.pid, 0);\n (0, processes_1.terminate)(childProcess);\n }\n }\n catch (error) {\n // All is fine.\n }\n }, 2000);\n }\n handleConnectionClosed() {\n this._serverProcess = undefined;\n return super.handleConnectionClosed();\n }\n fillInitializeParams(params) {\n super.fillInitializeParams(params);\n if (params.processId === null) {\n params.processId = process.pid;\n }\n }\n createMessageTransports(encoding) {\n function getEnvironment(env, fork) {\n if (!env && !fork) {\n return undefined;\n }\n const result = Object.create(null);\n Object.keys(process.env).forEach(key => result[key] = process.env[key]);\n if (fork) {\n result['ELECTRON_RUN_AS_NODE'] = '1';\n result['ELECTRON_NO_ASAR'] = '1';\n }\n if (env) {\n Object.keys(env).forEach(key => result[key] = env[key]);\n }\n return result;\n }\n const debugStartWith = ['--debug=', '--debug-brk=', '--inspect=', '--inspect-brk='];\n const debugEquals = ['--debug', '--debug-brk', '--inspect', '--inspect-brk'];\n function startedInDebugMode() {\n let args = process.execArgv;\n if (args) {\n return args.some((arg) => {\n return debugStartWith.some(value => arg.startsWith(value)) ||\n debugEquals.some(value => arg === value);\n });\n }\n return false;\n }\n function assertStdio(process) {\n if (process.stdin === null || process.stdout === null || process.stderr === null) {\n throw new Error('Process created without stdio streams');\n }\n }\n const server = this._serverOptions;\n // We got a function.\n if (Is.func(server)) {\n return server().then((result) => {\n if (client_1.MessageTransports.is(result)) {\n this._isDetached = !!result.detached;\n return result;\n }\n else if (StreamInfo.is(result)) {\n this._isDetached = !!result.detached;\n return { reader: new node_1.StreamMessageReader(result.reader), writer: new node_1.StreamMessageWriter(result.writer) };\n }\n else {\n let cp;\n if (ChildProcessInfo.is(result)) {\n cp = result.process;\n this._isDetached = result.detached;\n }\n else {\n cp = result;\n this._isDetached = false;\n }\n cp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n return { reader: new node_1.StreamMessageReader(cp.stdout), writer: new node_1.StreamMessageWriter(cp.stdin) };\n }\n });\n }\n let json;\n let runDebug = server;\n if (runDebug.run || runDebug.debug) {\n if (this._forceDebug || startedInDebugMode()) {\n json = runDebug.debug;\n this._isInDebugMode = true;\n }\n else {\n json = runDebug.run;\n this._isInDebugMode = false;\n }\n }\n else {\n json = server;\n }\n return this._getServerWorkingDir(json.options).then(serverWorkingDir => {\n if (NodeModule.is(json) && json.module) {\n let node = json;\n let transport = node.transport || TransportKind.stdio;\n if (node.runtime) {\n const args = [];\n const options = node.options ?? Object.create(null);\n if (options.execArgv) {\n options.execArgv.forEach(element => args.push(element));\n }\n args.push(node.module);\n if (node.args) {\n node.args.forEach(element => args.push(element));\n }\n const execOptions = Object.create(null);\n execOptions.cwd = serverWorkingDir;\n execOptions.env = getEnvironment(options.env, false);\n const runtime = this._getRuntimePath(node.runtime, serverWorkingDir);\n let pipeName = undefined;\n if (transport === TransportKind.ipc) {\n // exec options not correctly typed in lib\n execOptions.stdio = [null, null, null, 'ipc'];\n args.push('--node-ipc');\n }\n else if (transport === TransportKind.stdio) {\n args.push('--stdio');\n }\n else if (transport === TransportKind.pipe) {\n pipeName = (0, node_1.generateRandomPipeName)();\n args.push(`--pipe=${pipeName}`);\n }\n else if (Transport.isSocket(transport)) {\n args.push(`--socket=${transport.port}`);\n }\n args.push(`--clientProcessId=${process.pid.toString()}`);\n if (transport === TransportKind.ipc || transport === TransportKind.stdio) {\n const serverProcess = cp.spawn(runtime, args, execOptions);\n if (!serverProcess || !serverProcess.pid) {\n return handleChildProcessStartError(serverProcess, `Launching server using runtime ${runtime} failed.`);\n }\n this._serverProcess = serverProcess;\n serverProcess.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n if (transport === TransportKind.ipc) {\n serverProcess.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n return Promise.resolve({ reader: new node_1.IPCMessageReader(serverProcess), writer: new node_1.IPCMessageWriter(serverProcess) });\n }\n else {\n return Promise.resolve({ reader: new node_1.StreamMessageReader(serverProcess.stdout), writer: new node_1.StreamMessageWriter(serverProcess.stdin) });\n }\n }\n else if (transport === TransportKind.pipe) {\n return (0, node_1.createClientPipeTransport)(pipeName).then((transport) => {\n const process = cp.spawn(runtime, args, execOptions);\n if (!process || !process.pid) {\n return handleChildProcessStartError(process, `Launching server using runtime ${runtime} failed.`);\n }\n this._serverProcess = process;\n process.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n process.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n return transport.onConnected().then((protocol) => {\n return { reader: protocol[0], writer: protocol[1] };\n });\n });\n }\n else if (Transport.isSocket(transport)) {\n return (0, node_1.createClientSocketTransport)(transport.port).then((transport) => {\n const process = cp.spawn(runtime, args, execOptions);\n if (!process || !process.pid) {\n return handleChildProcessStartError(process, `Launching server using runtime ${runtime} failed.`);\n }\n this._serverProcess = process;\n process.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n process.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n return transport.onConnected().then((protocol) => {\n return { reader: protocol[0], writer: protocol[1] };\n });\n });\n }\n }\n else {\n let pipeName = undefined;\n return new Promise((resolve, reject) => {\n const args = (node.args && node.args.slice()) ?? [];\n if (transport === TransportKind.ipc) {\n args.push('--node-ipc');\n }\n else if (transport === TransportKind.stdio) {\n args.push('--stdio');\n }\n else if (transport === TransportKind.pipe) {\n pipeName = (0, node_1.generateRandomPipeName)();\n args.push(`--pipe=${pipeName}`);\n }\n else if (Transport.isSocket(transport)) {\n args.push(`--socket=${transport.port}`);\n }\n args.push(`--clientProcessId=${process.pid.toString()}`);\n const options = node.options ?? Object.create(null);\n options.env = getEnvironment(options.env, true);\n options.execArgv = options.execArgv || [];\n options.cwd = serverWorkingDir;\n options.silent = true;\n if (transport === TransportKind.ipc || transport === TransportKind.stdio) {\n const sp = cp.fork(node.module, args || [], options);\n assertStdio(sp);\n this._serverProcess = sp;\n sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n if (transport === TransportKind.ipc) {\n sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n resolve({ reader: new node_1.IPCMessageReader(this._serverProcess), writer: new node_1.IPCMessageWriter(this._serverProcess) });\n }\n else {\n resolve({ reader: new node_1.StreamMessageReader(sp.stdout), writer: new node_1.StreamMessageWriter(sp.stdin) });\n }\n }\n else if (transport === TransportKind.pipe) {\n (0, node_1.createClientPipeTransport)(pipeName).then((transport) => {\n const sp = cp.fork(node.module, args || [], options);\n assertStdio(sp);\n this._serverProcess = sp;\n sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n transport.onConnected().then((protocol) => {\n resolve({ reader: protocol[0], writer: protocol[1] });\n }, reject);\n }, reject);\n }\n else if (Transport.isSocket(transport)) {\n (0, node_1.createClientSocketTransport)(transport.port).then((transport) => {\n const sp = cp.fork(node.module, args || [], options);\n assertStdio(sp);\n this._serverProcess = sp;\n sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n transport.onConnected().then((protocol) => {\n resolve({ reader: protocol[0], writer: protocol[1] });\n }, reject);\n }, reject);\n }\n });\n }\n }\n else if (Executable.is(json) && json.command) {\n const command = json;\n const args = json.args !== undefined ? json.args.slice(0) : [];\n let pipeName = undefined;\n const transport = json.transport;\n if (transport === TransportKind.stdio) {\n args.push('--stdio');\n }\n else if (transport === TransportKind.pipe) {\n pipeName = (0, node_1.generateRandomPipeName)();\n args.push(`--pipe=${pipeName}`);\n }\n else if (Transport.isSocket(transport)) {\n args.push(`--socket=${transport.port}`);\n }\n else if (transport === TransportKind.ipc) {\n throw new Error(`Transport kind ipc is not support for command executable`);\n }\n const options = Object.assign({}, command.options);\n options.cwd = options.cwd || serverWorkingDir;\n if (transport === undefined || transport === TransportKind.stdio) {\n const serverProcess = cp.spawn(command.command, args, options);\n if (!serverProcess || !serverProcess.pid) {\n return handleChildProcessStartError(serverProcess, `Launching server using command ${command.command} failed.`);\n }\n serverProcess.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n this._serverProcess = serverProcess;\n this._isDetached = !!options.detached;\n return Promise.resolve({ reader: new node_1.StreamMessageReader(serverProcess.stdout), writer: new node_1.StreamMessageWriter(serverProcess.stdin) });\n }\n else if (transport === TransportKind.pipe) {\n return (0, node_1.createClientPipeTransport)(pipeName).then((transport) => {\n const serverProcess = cp.spawn(command.command, args, options);\n if (!serverProcess || !serverProcess.pid) {\n return handleChildProcessStartError(serverProcess, `Launching server using command ${command.command} failed.`);\n }\n this._serverProcess = serverProcess;\n this._isDetached = !!options.detached;\n serverProcess.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n serverProcess.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n return transport.onConnected().then((protocol) => {\n return { reader: protocol[0], writer: protocol[1] };\n });\n });\n }\n else if (Transport.isSocket(transport)) {\n return (0, node_1.createClientSocketTransport)(transport.port).then((transport) => {\n const serverProcess = cp.spawn(command.command, args, options);\n if (!serverProcess || !serverProcess.pid) {\n return handleChildProcessStartError(serverProcess, `Launching server using command ${command.command} failed.`);\n }\n this._serverProcess = serverProcess;\n this._isDetached = !!options.detached;\n serverProcess.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n serverProcess.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding)));\n return transport.onConnected().then((protocol) => {\n return { reader: protocol[0], writer: protocol[1] };\n });\n });\n }\n }\n return Promise.reject(new Error(`Unsupported server configuration ` + JSON.stringify(server, null, 4)));\n }).finally(() => {\n if (this._serverProcess !== undefined) {\n this._serverProcess.on('exit', (code, signal) => {\n if (code !== null) {\n this.error(`Server process exited with code ${code}.`, undefined, false);\n }\n if (signal !== null) {\n this.error(`Server process exited with signal ${signal}.`, undefined, false);\n }\n });\n }\n });\n }\n _getRuntimePath(runtime, serverWorkingDirectory) {\n if (path.isAbsolute(runtime)) {\n return runtime;\n }\n const mainRootPath = this._mainGetRootPath();\n if (mainRootPath !== undefined) {\n const result = path.join(mainRootPath, runtime);\n if (fs.existsSync(result)) {\n return result;\n }\n }\n if (serverWorkingDirectory !== undefined) {\n const result = path.join(serverWorkingDirectory, runtime);\n if (fs.existsSync(result)) {\n return result;\n }\n }\n return runtime;\n }\n _mainGetRootPath() {\n let folders = vscode_1.workspace.workspaceFolders;\n if (!folders || folders.length === 0) {\n return undefined;\n }\n let folder = folders[0];\n if (folder.uri.scheme === 'file') {\n return folder.uri.fsPath;\n }\n return undefined;\n }\n _getServerWorkingDir(options) {\n let cwd = options && options.cwd;\n if (!cwd) {\n cwd = this.clientOptions.workspaceFolder\n ? this.clientOptions.workspaceFolder.uri.fsPath\n : this._mainGetRootPath();\n }\n if (cwd) {\n // make sure the folder exists otherwise creating the process will fail\n return new Promise(s => {\n fs.lstat(cwd, (err, stats) => {\n s(!err && stats.isDirectory() ? cwd : undefined);\n });\n });\n }\n return Promise.resolve(undefined);\n }\n}\nexports.LanguageClient = LanguageClient;\nclass SettingMonitor {\n constructor(_client, _setting) {\n this._client = _client;\n this._setting = _setting;\n this._listeners = [];\n }\n start() {\n vscode_1.workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this, this._listeners);\n this.onDidChangeConfiguration();\n return new vscode_1.Disposable(() => {\n if (this._client.needsStop()) {\n void this._client.stop();\n }\n });\n }\n onDidChangeConfiguration() {\n let index = this._setting.indexOf('.');\n let primary = index >= 0 ? this._setting.substr(0, index) : this._setting;\n let rest = index >= 0 ? this._setting.substr(index + 1) : undefined;\n let enabled = rest ? vscode_1.workspace.getConfiguration(primary).get(rest, false) : vscode_1.workspace.getConfiguration(primary);\n if (enabled && this._client.needsStart()) {\n this._client.start().catch((error) => this._client.error('Start failed after configuration change', error, 'force'));\n }\n else if (!enabled && this._client.needsStop()) {\n void this._client.stop().catch((error) => this._client.error('Stop failed after configuration change', error, 'force'));\n }\n }\n}\nexports.SettingMonitor = SettingMonitor;\nfunction handleChildProcessStartError(process, message) {\n if (process === null) {\n return Promise.reject(message);\n }\n return new Promise((_, reject) => {\n process.on('error', (err) => {\n reject(`${message} ${err}`);\n });\n // the error event should always be run immediately,\n // but race on it just in case\n setImmediate(() => reject(message));\n });\n}\n", "/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ----------------------------------------------------------------------------------------- */\n'use strict';\n\nmodule.exports = require('./lib/node/main');", "import * as vscode from 'vscode';\nimport * as path from 'path';\nimport { detectPlatform } from './toolchain/platform';\nimport { detectInfs, inferenceHome } from './toolchain/detection';\nimport { exec } from './utils/exec';\nimport { compareSemver } from './utils/semver';\nimport { registerInstallCommand } from './commands/install';\nimport { registerInstallComponentCommand } from './commands/installComponent';\nimport { registerDoctorCommand } from './commands/doctor';\nimport { registerSelectVersionCommand } from './commands/selectVersion';\nimport { registerUpdateCommand, checkForUpdates } from './commands/update';\nimport { createStatusBar, updateStatusBar } from './ui/statusBar';\nimport { InferenceConfigProvider, ConfigItem } from './ui/configTree';\nimport { runDoctor } from './toolchain/doctor';\nimport {\n handleLspConfigChange,\n initializeLspClient,\n restartLspClient,\n startLspClient,\n stopLspClient,\n} from './lsp/client';\n\n/** Minimum infs CLI version the extension can work with. */\nconst MIN_INFS_VERSION = '0.0.1-beta.1';\n\nconst outputChannel = vscode.window.createOutputChannel('Inference', { log: true });\n\nexport function activate(context: vscode.ExtensionContext) {\n context.subscriptions.push(outputChannel);\n\n const statusBarItem = createStatusBar();\n context.subscriptions.push(statusBarItem);\n\n context.subscriptions.push(\n vscode.commands.registerCommand('inference.showOutput', () => {\n outputChannel.show();\n }),\n );\n\n context.subscriptions.push(registerInstallCommand(outputChannel, statusBarItem));\n context.subscriptions.push(\n registerDoctorCommand(outputChannel, statusBarItem),\n );\n context.subscriptions.push(registerInstallComponentCommand(outputChannel));\n\n context.subscriptions.push(registerUpdateCommand(outputChannel));\n context.subscriptions.push(registerSelectVersionCommand(outputChannel));\n\n const configProvider = new InferenceConfigProvider();\n const configView = vscode.window.createTreeView('inference.configView', {\n treeDataProvider: configProvider,\n });\n context.subscriptions.push(configView);\n context.subscriptions.push(configProvider);\n\n context.subscriptions.push(\n vscode.commands.registerCommand('inference.refreshConfigView', () => {\n configProvider.refresh();\n }),\n );\n\n context.subscriptions.push(\n vscode.commands.registerCommand('inference.applyTerminalPath', () => {\n applyTerminalPath(context);\n }),\n );\n\n context.subscriptions.push(\n vscode.commands.registerCommand(\n 'inference.copyConfigValue',\n (item: ConfigItem) => {\n if (item.copyValue) {\n vscode.env.clipboard.writeText(item.copyValue);\n vscode.window.showInformationMessage(\n `Copied: ${item.copyValue}`,\n );\n }\n },\n ),\n );\n\n context.subscriptions.push(\n vscode.commands.registerCommand(\n 'inference.revealConfigPath',\n (item: ConfigItem) => {\n if (item.copyValue) {\n vscode.commands.executeCommand(\n 'revealFileInOS',\n vscode.Uri.file(item.copyValue),\n );\n }\n },\n ),\n );\n\n context.subscriptions.push(\n vscode.workspace.onDidChangeConfiguration((e) => {\n if (e.affectsConfiguration('inference')) {\n configProvider.refresh();\n }\n handleLspConfigChange(e).catch((err) =>\n outputChannel.error(`Language server reconfigure failed: ${err}`),\n );\n }),\n );\n\n context.subscriptions.push(\n vscode.commands.registerCommand('inference.restartLsp', () => {\n restartLspClient().catch((err) =>\n outputChannel.error(`Language server restart failed: ${err}`),\n );\n }),\n );\n\n context.subscriptions.push(\n vscode.commands.registerCommand('inference.resetPathAcceptance', () => {\n const home = inferenceHome();\n const stateKey = `${PATH_FALLBACK_KEY}:${home}`;\n context.globalState.update(stateKey, undefined);\n vscode.window.showInformationMessage(\n 'Inference: PATH fallback preference has been reset.',\n );\n }),\n );\n\n applyTerminalPath(context);\n\n initializeLspClient(context, outputChannel);\n startLspClient().catch((err) =>\n outputChannel.error(`Language server start failed: ${err}`),\n );\n\n checkToolchain(context, statusBarItem, configProvider).catch((err) =>\n outputChannel.error(`Toolchain check failed: ${err}`),\n );\n}\n\nexport function deactivate(): Thenable {\n return stopLspClient();\n}\n\n/**\n * Prepend `INFERENCE_HOME/bin` to PATH for all integrated terminals.\n *\n * Uses VS Code's `EnvironmentVariableCollection` so that:\n * - New terminals automatically have the toolchain on PATH.\n * - Existing terminals show a relaunch indicator when the collection changes.\n *\n * Exported so that install/update commands can re-apply the mutation to\n * trigger the relaunch indicator on already-open terminals.\n */\nexport function applyTerminalPath(context: vscode.ExtensionContext): void {\n const binDir = path.join(inferenceHome(), 'bin');\n const sep = process.platform === 'win32' ? ';' : ':';\n const env = context.environmentVariableCollection;\n env.prepend('PATH', binDir + sep);\n env.description = 'Adds the Inference toolchain to PATH';\n}\n\n/** globalState key prefix for remembering PATH fallback acceptance. */\nconst PATH_FALLBACK_KEY = 'inference.acceptedPathFallback';\n\nasync function checkToolchain(\n context: vscode.ExtensionContext,\n statusBarItem: vscode.StatusBarItem,\n configProvider: InferenceConfigProvider,\n): Promise {\n const platform = detectPlatform();\n const home = inferenceHome();\n const homeIsDefault = !process.env['INFERENCE_HOME'];\n const distServer = process.env['INFS_DIST_SERVER'];\n\n outputChannel.info('Inference Activation');\n\n if (!platform) {\n outputChannel.warn(\n `Platform: ${process.platform}-${process.arch} (unsupported)`,\n );\n outputChannel.info(\n `INFERENCE_HOME: ${home} ${homeIsDefault ? '(default)' : '(env)'}`,\n );\n outputChannel.info(\n `INFS_DIST_SERVER: ${distServer ?? '(not set, using production)'}`,\n );\n updateStatusBar(statusBarItem, null);\n vscode.commands.executeCommand('setContext', 'inference.toolchainInstalled', false);\n vscode.window\n .showWarningMessage(\n `Inference: unsupported platform (${process.platform}-${process.arch}).`,\n 'Download Page',\n )\n .then((action) => {\n if (action === 'Download Page') {\n vscode.env.openExternal(\n vscode.Uri.parse(\n 'https://github.com/Inferara/inference/releases',\n ),\n );\n }\n });\n return;\n }\n\n outputChannel.info(`Platform: ${platform.id}`);\n outputChannel.info(\n `INFERENCE_HOME: ${home} ${homeIsDefault ? '(default)' : '(env)'}`,\n );\n outputChannel.info(\n `INFS_DIST_SERVER: ${distServer ?? '(not set, using production)'}`,\n );\n\n const detection = detectInfs();\n if (!detection) {\n outputChannel.error('infs binary: not found');\n outputChannel.error('Toolchain status: errors');\n updateStatusBar(statusBarItem, null);\n vscode.commands.executeCommand('setContext', 'inference.toolchainInstalled', false);\n notifyMissing();\n return;\n }\n outputChannel.info(\n `infs binary: ${detection.path} (${detection.source})`,\n );\n\n if (!homeIsDefault && detection.source === 'path') {\n const stateKey = `${PATH_FALLBACK_KEY}:${home}`;\n const accepted = context.globalState.get(stateKey);\n\n if (accepted === '*') {\n outputChannel.info(\n `Note: Using PATH binary (notification permanently suppressed for this INFERENCE_HOME).`,\n );\n } else if (accepted === detection.path) {\n outputChannel.info(\n `Note: Using PATH binary (previously accepted for this INFERENCE_HOME).`,\n );\n } else {\n outputChannel.warn(\n `INFERENCE_HOME is set to ${home} but infs was not found there. Using binary from PATH instead.`,\n );\n vscode.window.showWarningMessage(\n `Inference: infs binary not found in INFERENCE_HOME (${home}). Found via PATH instead.`,\n 'Install',\n 'Dismiss',\n ).then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand('inference.installToolchain');\n } else {\n context.globalState.update(stateKey, '*');\n }\n });\n }\n }\n\n const versionOk = await checkInfsVersion(detection.path);\n if (!versionOk) {\n outputChannel.error('Toolchain status: errors');\n updateStatusBar(statusBarItem, null);\n vscode.commands.executeCommand('setContext', 'inference.toolchainInstalled', false);\n return;\n }\n\n vscode.commands.executeCommand('setContext', 'inference.toolchainInstalled', true);\n\n const doctorResult = await runDoctor(detection.path);\n updateStatusBar(statusBarItem, doctorResult);\n configProvider.refresh(detection, doctorResult);\n\n const status = doctorResult?.hasErrors\n ? 'errors'\n : doctorResult?.hasWarnings\n ? 'warnings'\n : 'healthy';\n if (doctorResult?.hasErrors) {\n outputChannel.error(`Toolchain status: ${status}`);\n } else if (doctorResult?.hasWarnings) {\n outputChannel.warn(`Toolchain status: ${status}`);\n } else {\n outputChannel.info(`Toolchain status: ${status}`);\n }\n\n checkForUpdates(detection.path, outputChannel).catch((err) =>\n outputChannel.error(`Update check failed: ${err}`),\n );\n}\n\n/**\n * Run `infs version` and check the output against MIN_INFS_VERSION.\n * Returns true if version is acceptable.\n */\nasync function checkInfsVersion(infsPath: string): Promise {\n try {\n const result = await exec(infsPath, ['version']);\n if (result.exitCode !== 0) {\n outputChannel.error(\n `infs version failed (exit ${result.exitCode}): ${result.stderr}`,\n );\n return false;\n }\n // Output format: \"infs 0.1.0\"\n const match = result.stdout.match(/^infs\\s+(\\S+)/);\n if (!match) {\n outputChannel.error(\n `Could not parse infs version from: ${result.stdout.trim()}`,\n );\n return false;\n }\n const version = match[1];\n outputChannel.info(`infs version: ${version}`);\n\n if (compareSemver(version, MIN_INFS_VERSION) < 0) {\n outputChannel.warn(\n `infs version ${version} is below minimum ${MIN_INFS_VERSION}.`,\n );\n vscode.window\n .showWarningMessage(\n `Inference: infs version ${version} is outdated (minimum: ${MIN_INFS_VERSION}). Please update.`,\n 'Update',\n )\n .then((action) => {\n if (action === 'Update') {\n vscode.commands.executeCommand('inference.updateToolchain');\n }\n });\n return false;\n }\n return true;\n } catch (err) {\n outputChannel.error(`Failed to run infs version: ${err}`);\n return false;\n }\n}\n\nfunction notifyMissing(): void {\n vscode.window\n .showInformationMessage(\n 'Inference toolchain not found. Would you like to install it?',\n 'Install',\n 'Download Manually',\n 'Configure Path',\n )\n .then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand('inference.installToolchain');\n } else if (action === 'Download Manually') {\n vscode.env.openExternal(\n vscode.Uri.parse(\n 'https://github.com/Inferara/inference/releases',\n ),\n );\n } else if (action === 'Configure Path') {\n vscode.commands.executeCommand(\n 'workbench.action.openSettings',\n 'inference.path',\n );\n }\n });\n}\n", "import * as os from 'os';\n\nexport type PlatformId = 'linux-x64' | 'macos-arm64' | 'windows-x64';\n\nexport interface PlatformInfo {\n id: PlatformId;\n archiveExtension: string;\n binaryName: string;\n}\n\nexport const SUPPORTED_PLATFORMS: Record = {\n 'linux-x64': 'linux-x64',\n 'darwin-arm64': 'macos-arm64',\n 'win32-x64': 'windows-x64',\n};\n\n/**\n * Detect the platform and return its info, or null if unsupported.\n * When osPlatform/osArch are omitted, uses the current runtime values.\n */\nexport function detectPlatform(\n osPlatform?: string,\n osArch?: string,\n): PlatformInfo | null {\n const key = `${osPlatform ?? os.platform()}-${osArch ?? os.arch()}`;\n const id = SUPPORTED_PLATFORMS[key];\n if (!id) {\n return null;\n }\n return {\n id,\n archiveExtension: id === 'windows-x64' ? '.zip' : '.tar.gz',\n binaryName: id === 'windows-x64' ? 'infs.exe' : 'infs',\n };\n}\n", "import * as fs from 'fs';\nimport * as path from 'path';\nimport { getSettings } from '../config/settings';\nimport { detectPlatform } from './platform';\nimport { inferenceHome } from './home';\n\nexport { inferenceHome };\n\n/** Check whether a file exists and is executable (or just exists on Windows). */\nexport function isExecutable(filePath: string): boolean {\n try {\n const mode = process.platform === 'win32'\n ? fs.constants.F_OK\n : fs.constants.X_OK;\n fs.accessSync(filePath, mode);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Search PATH for the given binary name.\n * Returns the first match or null.\n */\nexport function findInPath(binaryName: string): string | null {\n const envPath = process.env['PATH'] || '';\n const sep = process.platform === 'win32' ? ';' : ':';\n const dirs = envPath.split(sep).filter(Boolean);\n for (const dir of dirs) {\n const candidate = path.join(dir, binaryName);\n if (isExecutable(candidate)) {\n return candidate;\n }\n }\n return null;\n}\n\n/** Source where the infs binary was found. */\nexport type InfsSource = 'settings' | 'managed' | 'path';\n\n/** Result of infs binary detection. */\nexport interface InfsDetection {\n path: string;\n source: InfsSource;\n}\n\n/**\n * Detect infs binary location.\n *\n * Search order:\n * 1. Custom path from settings (inference.path)\n * 2. Managed location (INFERENCE_HOME/bin/infs)\n * 3. System PATH\n *\n * Returns the resolved absolute path and source, or null if not found.\n */\nexport function detectInfs(): InfsDetection | null {\n const platform = detectPlatform();\n const binaryName = platform?.binaryName ?? 'infs';\n\n const settings = getSettings();\n if (settings.path) {\n if (isExecutable(settings.path)) {\n return { path: settings.path, source: 'settings' };\n }\n return null;\n }\n\n const managedPath = path.join(inferenceHome(), 'bin', binaryName);\n if (isExecutable(managedPath)) {\n return { path: managedPath, source: 'managed' };\n }\n\n const pathResult = findInPath(binaryName);\n if (pathResult) {\n return { path: pathResult, source: 'path' };\n }\n\n return null;\n}\n", "import * as vscode from 'vscode';\n\nexport interface InferenceSettings {\n /** Custom path to infs binary. Empty string means auto-detect. */\n path: string;\n /** Prompt to install toolchain if not found. */\n autoInstall: boolean;\n /** Check for toolchain updates on activation. */\n checkForUpdates: boolean;\n /** Start the language server automatically. */\n lspEnabled: boolean;\n /** Custom path to inference-lsp binary. Empty string means auto-detect. */\n lspPath: string;\n}\n\n/** Read current inference.* configuration values. */\nexport function getSettings(): InferenceSettings {\n const config = vscode.workspace.getConfiguration('inference');\n return {\n path: config.get('path', ''),\n autoInstall: config.get('autoInstall', true),\n checkForUpdates: config.get('checkForUpdates', true),\n lspEnabled: config.get('lsp.enabled', true),\n lspPath: config.get('lsp.path', ''),\n };\n}\n", "/**\n * Compare two semver strings. Returns negative if a < b, 0 if equal, positive if a > b.\n * Handles numeric major.minor.patch and pre-release tags per the SemVer 2.0.0 spec.\n *\n * Pre-release versions have lower precedence than the associated normal version:\n * 1.0.0-alpha < 1.0.0\n *\n * Pre-release identifiers are compared left-to-right:\n * - Numeric identifiers are compared as integers.\n * - Alphanumeric identifiers are compared lexically (ASCII order).\n * - Numeric identifiers always have lower precedence than alphanumeric.\n * - A shorter set of identifiers has lower precedence if all preceding are equal.\n */\nexport function compareSemver(a: string, b: string): number {\n const clean = (v: string) => v.replace(/^v/i, '');\n const [coreA, preA] = clean(a).split('-', 2);\n const [coreB, preB] = clean(b).split('-', 2);\n\n const pa = coreA.split('.').map(Number);\n const pb = coreB.split('.').map(Number);\n for (let i = 0; i < 3; i++) {\n const diff = (pa[i] || 0) - (pb[i] || 0);\n if (diff !== 0) {\n return diff;\n }\n }\n\n if (!preA && !preB) {\n return 0;\n }\n if (preA && !preB) {\n return -1;\n }\n if (!preA && preB) {\n return 1;\n }\n\n const partsA = preA!.split('.');\n const partsB = preB!.split('.');\n const len = Math.max(partsA.length, partsB.length);\n for (let i = 0; i < len; i++) {\n if (i >= partsA.length) {\n return -1;\n }\n if (i >= partsB.length) {\n return 1;\n }\n const numA = Number(partsA[i]);\n const numB = Number(partsB[i]);\n const aIsNum = !Number.isNaN(numA);\n const bIsNum = !Number.isNaN(numB);\n if (aIsNum && bIsNum) {\n if (numA !== numB) {\n return numA - numB;\n }\n } else if (aIsNum) {\n return -1;\n } else if (bIsNum) {\n return 1;\n } else {\n if (partsA[i] < partsB[i]) {\n return -1;\n }\n if (partsA[i] > partsB[i]) {\n return 1;\n }\n }\n }\n return 0;\n}\n", "import * as vscode from 'vscode';\nimport { detectPlatform, PlatformInfo } from '../toolchain/platform';\nimport {\n installToolchain,\n InstallProgress,\n InstallProgressCallback,\n InstallResult,\n} from '../toolchain/installation';\nimport { runDoctor } from '../toolchain/doctor';\nimport { updateStatusBar } from '../ui/statusBar';\nimport { ensureLspStarted } from '../lsp/client';\n\n/** Guard against concurrent install attempts. */\nlet installing = false;\n\n/**\n * Register the inference.installToolchain command.\n * Returns the Disposable to add to context.subscriptions.\n */\nexport function registerInstallCommand(\n outputChannel: vscode.OutputChannel,\n statusBarItem: vscode.StatusBarItem,\n): vscode.Disposable {\n return vscode.commands.registerCommand(\n 'inference.installToolchain',\n async () => {\n if (installing) {\n vscode.window.showInformationMessage(\n 'Inference toolchain installation is already in progress.',\n );\n return;\n }\n\n const platform = detectPlatform();\n if (!platform) {\n vscode.window.showErrorMessage(\n `Inference: unsupported platform (${process.platform}-${process.arch}).`,\n );\n return;\n }\n\n installing = true;\n try {\n const result = await installWithProgress(\n platform,\n outputChannel,\n );\n outputChannel.appendLine(\n `Toolchain v${result.version} installed at ${result.infsPath}`,\n );\n vscode.commands.executeCommand(\n 'setContext', 'inference.toolchainInstalled', true,\n );\n\n const doctorResult = await runDoctor(result.infsPath);\n updateStatusBar(statusBarItem, doctorResult);\n vscode.commands.executeCommand('inference.refreshConfigView');\n vscode.commands.executeCommand('inference.applyTerminalPath');\n void ensureLspStarted();\n\n notifyInstallSuccess(result.version, result.doctorWarnings);\n } catch (err) {\n const message =\n err instanceof Error ? err.message : String(err);\n outputChannel.appendLine(`Installation failed: ${message}`);\n notifyInstallError(message);\n } finally {\n installing = false;\n }\n },\n );\n}\n\n/** Run the installation with a VS Code progress notification. */\nfunction installWithProgress(\n platform: PlatformInfo,\n outputChannel: vscode.OutputChannel,\n): Thenable {\n return vscode.window.withProgress(\n {\n location: vscode.ProgressLocation.Notification,\n title: 'Inference Toolchain',\n cancellable: false,\n },\n async (progress) => {\n const onProgress: InstallProgressCallback = (\n p: InstallProgress,\n ) => {\n outputChannel.appendLine(p.message);\n if (p.stage === 'downloading' && p.bytesTotal) {\n const pct = Math.round(\n ((p.bytesReceived ?? 0) / p.bytesTotal) * 100,\n );\n progress.report({ message: `${p.message} (${pct}%)` });\n } else {\n progress.report({ message: p.message });\n }\n };\n return installToolchain(platform, onProgress);\n },\n );\n}\n\n/** Show a notification that the toolchain was installed successfully. */\nfunction notifyInstallSuccess(\n version: string,\n doctorWarnings: boolean,\n): void {\n if (doctorWarnings) {\n vscode.window\n .showWarningMessage(\n `Inference toolchain v${version} installed, but doctor reported issues. See output for details.`,\n 'Show Output',\n )\n .then((action) => {\n if (action === 'Show Output') {\n vscode.commands.executeCommand('inference.showOutput');\n }\n });\n } else {\n vscode.window.showInformationMessage(\n `Inference toolchain v${version} installed successfully.`,\n );\n }\n}\n\n/** Show an error notification for installation failure. */\nfunction notifyInstallError(errorMessage: string): void {\n vscode.window\n .showErrorMessage(\n `Inference toolchain installation failed: ${errorMessage}`,\n 'Retry',\n 'Download Manually',\n 'Settings',\n )\n .then((action) => {\n if (action === 'Retry') {\n vscode.commands.executeCommand('inference.installToolchain');\n } else if (action === 'Download Manually') {\n vscode.env.openExternal(\n vscode.Uri.parse(\n 'https://github.com/Inferara/inference/releases',\n ),\n );\n } else if (action === 'Settings') {\n vscode.commands.executeCommand(\n 'workbench.action.openSettings',\n 'inference.path',\n );\n }\n });\n}\n", "import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { PlatformInfo } from './platform';\nimport { inferenceHome } from './home';\nimport { fetchJson, downloadFile, sha256File } from '../utils/download';\nimport { extractArchive } from '../utils/extract';\nimport { exec } from '../utils/exec';\nimport {\n ReleaseEntry,\n findLatestRelease,\n} from './manifest';\n\nexport type { FileEntry, ReleaseEntry } from './manifest';\nexport { findLatestRelease } from './manifest';\n\n/** Progress updates emitted during installation. */\nexport interface InstallProgress {\n stage:\n | 'fetching-manifest'\n | 'downloading'\n | 'extracting'\n | 'installing'\n | 'verifying';\n message: string;\n bytesReceived?: number;\n bytesTotal?: number;\n}\n\nexport type InstallProgressCallback = (progress: InstallProgress) => void;\n\n/** Result of a successful installation. */\nexport interface InstallResult {\n infsPath: string;\n version: string;\n doctorWarnings: boolean;\n}\n\nconst DEFAULT_DIST_SERVER = 'https://inference-lang.org';\nconst RELEASES_PATH = '/releases.json';\n\nfunction manifestUrl(): string {\n const server = process.env['INFS_DIST_SERVER']?.trim();\n const base = server && server.length > 0\n ? server.replace(/\\/+$/, '')\n : DEFAULT_DIST_SERVER;\n return `${base}${RELEASES_PATH}`;\n}\n\n/**\n * Run the full installation flow.\n * Fetches manifest, downloads infs, extracts, runs `infs install`, verifies with `infs doctor`.\n * Throws on failure with a descriptive error message.\n */\nexport async function installToolchain(\n platform: PlatformInfo,\n onProgress?: InstallProgressCallback,\n): Promise {\n onProgress?.({\n stage: 'fetching-manifest',\n message: 'Fetching release manifest...',\n });\n\n const manifest = await fetchJson(manifestUrl());\n\n if (!Array.isArray(manifest)) {\n throw new Error('Invalid release manifest: expected an array.');\n }\n for (const entry of manifest) {\n if (\n typeof entry?.version !== 'string' ||\n typeof entry?.stable !== 'boolean' ||\n !Array.isArray(entry?.files)\n ) {\n throw new Error(\n `Invalid release manifest entry: ${JSON.stringify(entry)?.slice(0, 200)}`,\n );\n }\n }\n\n const match = findLatestRelease(manifest, platform);\n if (!match) {\n throw new Error(\n `No compatible infs release found for ${platform.id}.`,\n );\n }\n\n const { release, fileUrl, sha256 } = match;\n const version = release.version;\n\n onProgress?.({\n stage: 'downloading',\n message: `Downloading infs v${version}...`,\n });\n\n const destDir = path.join(inferenceHome(), 'bin');\n fs.mkdirSync(destDir, { recursive: true });\n\n const archiveName = `infs-${platform.id}${platform.archiveExtension}`;\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'infs-'));\n const archivePath = path.join(tmpDir, archiveName);\n\n try {\n await downloadFile(fileUrl, {\n destPath: archivePath,\n onProgress: (received, total) => {\n onProgress?.({\n stage: 'downloading',\n message: `Downloading infs v${version}...`,\n bytesReceived: received,\n bytesTotal: total,\n });\n },\n });\n\n const actualHash = await sha256File(archivePath);\n if (actualHash !== sha256) {\n throw new Error(\n `SHA-256 verification failed for infs v${version}. Expected ${sha256}, got ${actualHash}.`,\n );\n }\n\n onProgress?.({\n stage: 'extracting',\n message: 'Extracting archive...',\n });\n\n await extractArchive({ archivePath, destDir });\n } finally {\n try {\n fs.rmSync(tmpDir, { recursive: true, force: true });\n } catch {\n // best-effort cleanup\n }\n }\n\n const infsPath = path.join(destDir, platform.binaryName);\n if (!fs.existsSync(infsPath)) {\n throw new Error(\n `infs binary not found at ${infsPath} after extraction.`,\n );\n }\n\n onProgress?.({\n stage: 'installing',\n message: 'Running infs install...',\n });\n\n const binDir = path.join(inferenceHome(), 'bin');\n const sep = process.platform === 'win32' ? ';' : ':';\n const augmentedPath = `${binDir}${sep}${process.env['PATH'] ?? ''}`;\n\n const installResult = await exec(infsPath, ['install'], {\n timeoutMs: 120_000,\n env: { PATH: augmentedPath },\n });\n if (installResult.exitCode !== 0) {\n throw new Error(\n `infs install failed (exit ${installResult.exitCode}): ${installResult.stderr || installResult.stdout}`,\n );\n }\n\n onProgress?.({\n stage: 'verifying',\n message: 'Verifying installation...',\n });\n\n let doctorWarnings = false;\n try {\n const doctorResult = await exec(infsPath, ['doctor'], {\n timeoutMs: 30_000,\n env: { PATH: augmentedPath },\n });\n if (doctorResult.exitCode !== 0) {\n doctorWarnings = true;\n } else {\n const { parseDoctorOutput } = await import('./doctor');\n const parsed = parseDoctorOutput(doctorResult.stdout);\n if (parsed.hasErrors || parsed.hasWarnings) {\n doctorWarnings = true;\n }\n }\n } catch {\n doctorWarnings = true;\n }\n\n return { infsPath, version, doctorWarnings };\n}\n", "import * as https from 'https';\nimport * as http from 'http';\nimport * as fs from 'fs';\nimport * as crypto from 'crypto';\n\n/** Callback invoked during download with bytes received and total (if known). */\nexport type ProgressCallback = (\n received: number,\n total: number | undefined,\n) => void;\n\nexport interface DownloadOptions {\n /** Absolute path where the downloaded file will be saved. */\n destPath: string;\n /** Optional progress callback. */\n onProgress?: ProgressCallback;\n /** Connection timeout in milliseconds (default: 15000). */\n timeoutMs?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 15_000;\nconst MAX_REDIRECTS = 5;\n\nconst SOCKET_TIMEOUT_MS = 15_000;\nconst MAX_JSON_RESPONSE_BYTES = 10 * 1024 * 1024;\n\n/**\n * Perform an HTTPS GET request following redirects.\n * Rejects HTTPS-to-HTTP downgrades.\n */\nfunction followRedirects(\n url: string,\n remaining: number,\n): Promise {\n return new Promise((resolve, reject) => {\n const parsed = new URL(url);\n const requester = parsed.protocol === 'https:' ? https : http;\n\n const req = requester.get(url, (res) => {\n const status = res.statusCode ?? 0;\n\n if (status >= 300 && status < 400 && res.headers.location) {\n if (remaining <= 0) {\n res.resume();\n reject(new Error(`Too many redirects fetching ${url}`));\n return;\n }\n const target = new URL(res.headers.location, url).href;\n const targetProtocol = new URL(target).protocol;\n if (parsed.protocol === 'https:' && targetProtocol === 'http:') {\n res.resume();\n reject(\n new Error(\n `Refusing HTTPS-to-HTTP redirect: ${url} -> ${target}`,\n ),\n );\n return;\n }\n res.resume();\n followRedirects(target, remaining - 1).then(resolve, reject);\n return;\n }\n\n if (status < 200 || status >= 300) {\n res.resume();\n reject(new Error(`HTTP ${status} fetching ${url}`));\n return;\n }\n\n resolve(res);\n });\n\n req.setTimeout(SOCKET_TIMEOUT_MS, () => {\n req.destroy(new Error(`Connection timed out for ${url}`));\n });\n\n req.on('error', (err) =>\n reject(new Error(`Network error fetching ${url}: ${err.message}`)),\n );\n });\n}\n\n/**\n * Fetch a JSON document from a URL via HTTPS GET.\n * Follows up to 5 redirects. Rejects HTTPS-to-HTTP downgrades.\n */\nexport function fetchJson(url: string): Promise {\n return new Promise((resolve, reject) => {\n followRedirects(url, MAX_REDIRECTS).then(\n (res) => {\n const chunks: Buffer[] = [];\n let totalBytes = 0;\n res.on('data', (chunk: Buffer) => {\n totalBytes += chunk.length;\n if (totalBytes > MAX_JSON_RESPONSE_BYTES) {\n res.destroy();\n reject(new Error(`Response too large (>${MAX_JSON_RESPONSE_BYTES} bytes) from ${url}`));\n return;\n }\n chunks.push(chunk);\n });\n res.on('end', () => {\n try {\n const text = Buffer.concat(chunks).toString('utf-8');\n resolve(JSON.parse(text) as T);\n } catch (err) {\n reject(\n new Error(\n `Failed to parse JSON from ${url}: ${err instanceof Error ? err.message : err}`,\n ),\n );\n }\n });\n res.on('error', (err) =>\n reject(\n new Error(\n `Error reading response from ${url}: ${err.message}`,\n ),\n ),\n );\n },\n (err) => reject(err),\n );\n });\n}\n\n/**\n * Download a file from a URL to destPath using streaming.\n * Uses a temp file (.partial suffix) and renames on completion.\n * Follows redirects (GitHub releases redirect to CDN).\n */\nexport function downloadFile(\n url: string,\n options: DownloadOptions,\n): Promise {\n const timeout = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const partialPath = options.destPath + '.partial';\n\n return new Promise((resolve, reject) => {\n let settled = false;\n const settle = (fn: (...args: T) => void, ...args: T) => {\n if (!settled) {\n settled = true;\n fn(...args);\n }\n };\n\n followRedirects(url, MAX_REDIRECTS).then(\n (res) => {\n const totalStr = res.headers['content-length'];\n const total = totalStr ? parseInt(totalStr, 10) : undefined;\n let received = 0;\n\n const ws = fs.createWriteStream(partialPath);\n\n res.on('data', (chunk: Buffer) => {\n received += chunk.length;\n options.onProgress?.(received, total);\n });\n\n res.pipe(ws);\n\n const cleanup = () => {\n try {\n fs.unlinkSync(partialPath);\n } catch {\n // ignore\n }\n };\n\n // No-data timeout: if no bytes arrive for `timeout` ms, abort\n let dataTimer: ReturnType | undefined;\n const clearDataTimer = () => {\n if (dataTimer) {\n clearTimeout(dataTimer);\n dataTimer = undefined;\n }\n };\n const resetTimer = () => {\n clearDataTimer();\n dataTimer = setTimeout(() => {\n res.destroy();\n ws.destroy();\n cleanup();\n settle(reject, new Error(`Download timed out for ${url}`));\n }, timeout);\n };\n resetTimer();\n res.on('data', resetTimer);\n res.on('end', clearDataTimer);\n\n ws.on('finish', () => {\n clearDataTimer();\n try {\n fs.renameSync(partialPath, options.destPath);\n settle(resolve);\n } catch (err) {\n cleanup();\n settle(\n reject,\n new Error(\n `Failed to save download to ${options.destPath}: ${err instanceof Error ? err.message : err}`,\n ),\n );\n }\n });\n\n ws.on('error', (err) => {\n clearDataTimer();\n res.destroy();\n cleanup();\n settle(\n reject,\n new Error(\n `Failed to write download: ${err.message}`,\n ),\n );\n });\n\n res.on('error', (err) => {\n clearDataTimer();\n ws.destroy();\n cleanup();\n settle(\n reject,\n new Error(\n `Download stream error from ${url}: ${err.message}`,\n ),\n );\n });\n },\n (err) => settle(reject, err),\n );\n });\n}\n\n/**\n * Compute SHA-256 hash of a file.\n * Returns lowercase hex string.\n */\nexport function sha256File(filePath: string): Promise {\n return new Promise((resolve, reject) => {\n const hash = crypto.createHash('sha256');\n const stream = fs.createReadStream(filePath);\n stream.on('data', (chunk) => hash.update(chunk));\n stream.on('end', () => resolve(hash.digest('hex')));\n stream.on('error', (err) =>\n reject(\n new Error(\n `Failed to compute SHA-256 for ${filePath}: ${err.message}`,\n ),\n ),\n );\n });\n}\n", "import * as fs from 'fs';\nimport * as path from 'path';\nimport { exec } from './exec';\n\nexport interface ExtractOptions {\n /** Path to the archive file. */\n archivePath: string;\n /** Directory to extract into (created if it doesn't exist). */\n destDir: string;\n}\n\n/**\n * Extract an archive to the destination directory.\n * Detects format from file extension (.tar.gz or .zip).\n * On Unix, sets executable permission on extracted binaries.\n */\nexport async function extractArchive(options: ExtractOptions): Promise {\n fs.mkdirSync(options.destDir, { recursive: true });\n\n if (\n options.archivePath.endsWith('.tar.gz') ||\n options.archivePath.endsWith('.tgz')\n ) {\n await extractTarGz(options.archivePath, options.destDir);\n } else if (options.archivePath.endsWith('.zip')) {\n await extractZip(options.archivePath, options.destDir);\n } else {\n throw new Error(\n `Unsupported archive format: ${path.basename(options.archivePath)}`,\n );\n }\n\n if (process.platform !== 'win32') {\n setExecutablePermissions(options.destDir);\n }\n}\n\nasync function extractTarGz(\n archivePath: string,\n destDir: string,\n): Promise {\n const result = await exec('tar', ['-xzf', archivePath, '-C', destDir]);\n if (result.exitCode !== 0) {\n throw new Error(\n `tar extraction failed (exit ${result.exitCode}): ${result.stderr}`,\n );\n }\n}\n\n/** Escape a string for use inside a PowerShell single-quoted literal. */\nfunction escapePowerShellSingleQuote(value: string): string {\n return value.replace(/'/g, \"''\");\n}\n\nasync function extractZip(\n archivePath: string,\n destDir: string,\n): Promise {\n const safePath = escapePowerShellSingleQuote(archivePath);\n const safeDest = escapePowerShellSingleQuote(destDir);\n const result = await exec('powershell', [\n '-NoProfile',\n '-Command',\n `Expand-Archive -LiteralPath '${safePath}' -DestinationPath '${safeDest}' -Force`,\n ]);\n if (result.exitCode !== 0) {\n throw new Error(\n `zip extraction failed (exit ${result.exitCode}): ${result.stderr}`,\n );\n }\n}\n\n/** Set executable permissions on files in the directory (non-recursive, top level only). */\nfunction setExecutablePermissions(dir: string): void {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (entry.isFile()) {\n try {\n fs.chmodSync(path.join(dir, entry.name), 0o755);\n } catch {\n // best-effort per file\n }\n }\n }\n}\n", "import { compareSemver } from '../utils/semver';\n\n/** A platform-specific file entry from the manifest. */\nexport interface FileEntry {\n url: string;\n sha256: string;\n}\n\n/** A single release entry from the manifest. */\nexport interface ReleaseEntry {\n version: string;\n stable: boolean;\n files: FileEntry[];\n}\n\n/** Minimal platform info needed for manifest matching. */\nexport interface ManifestPlatform {\n id: string;\n}\n\n/**\n * Extract tool name from a manifest file URL.\n * URL format: `https://.../tool-os-arch.ext` (e.g., `infs-linux-x64.tar.gz`).\n */\nexport function toolFromUrl(url: string): string {\n const filename = url.split('/').pop() ?? '';\n return filename.split('-')[0] ?? '';\n}\n\n/**\n * Extract OS name from a manifest file URL.\n * URL format: `https://.../tool-os-arch.ext` (e.g., `infs-linux-x64.tar.gz`).\n */\nexport function osFromUrl(url: string): string {\n const filename = url.split('/').pop() ?? '';\n const parts = filename.split('-');\n return parts.length > 1 ? parts[1] : '';\n}\n\n/** Map platform ID to the OS string used in manifest URLs. */\nexport function platformOs(platform: ManifestPlatform): string {\n if (platform.id === 'linux-x64') {\n return 'linux';\n }\n if (platform.id === 'macos-arm64') {\n return 'macos';\n }\n if (platform.id === 'windows-x64') {\n return 'windows';\n }\n return '';\n}\n\n/**\n * Find the latest release from the manifest for the given platform.\n * Matches the `infs` tool artifact for the platform's OS.\n * Returns the release entry, file URL, and sha256, or null if not found.\n */\nexport function findLatestRelease(\n manifest: ReleaseEntry[],\n platform: ManifestPlatform,\n): { release: ReleaseEntry; fileUrl: string; sha256: string } | null {\n if (manifest.length === 0) {\n return null;\n }\n\n const sorted = [...manifest].sort((a, b) =>\n compareSemver(b.version, a.version),\n );\n\n const os = platformOs(platform);\n\n for (const release of sorted) {\n const file = release.files.find(\n (f) => toolFromUrl(f.url) === 'infs' && osFromUrl(f.url) === os,\n );\n if (file) {\n return { release, fileUrl: file.url, sha256: file.sha256 };\n }\n }\n\n return null;\n}\n", "import * as vscode from 'vscode';\nimport { DoctorResult } from '../toolchain/doctor';\nimport { determineStatusBarState, StatusBarIcon } from './statusBarState';\n\nconst ICON_MAP: Record = {\n loading: '$(loading~spin)',\n dash: '$(dash)',\n check: '$(check)',\n warning: '$(warning)',\n error: '$(error)',\n};\n\nconst BACKGROUND_MAP: Record = {\n none: undefined,\n warning: new vscode.ThemeColor('statusBarItem.warningBackground'),\n error: new vscode.ThemeColor('statusBarItem.errorBackground'),\n};\n\n/**\n * Create the Inference status bar item.\n * Positioned on the left side with low priority.\n * Clicking triggers the inference.runDoctor command.\n */\nexport function createStatusBar(): vscode.StatusBarItem {\n const item = vscode.window.createStatusBarItem(\n vscode.StatusBarAlignment.Left,\n 0,\n );\n item.command = 'inference.runDoctor';\n item.text = '$(loading~spin) Inference';\n item.tooltip = 'Inference: Checking toolchain...';\n item.show();\n return item;\n}\n\n/**\n * Update the status bar to reflect doctor results.\n *\n * - null: toolchain not found (grey dash icon)\n * - hasErrors: red error icon\n * - hasWarnings: yellow warning icon\n * - all OK: green check icon\n */\nexport function updateStatusBar(\n item: vscode.StatusBarItem,\n result: DoctorResult | null,\n): void {\n const state = determineStatusBarState(result);\n item.text = `${ICON_MAP[state.icon]} ${state.label}`;\n item.tooltip = state.tooltip;\n item.backgroundColor = BACKGROUND_MAP[state.background];\n}\n", "import { DoctorResult } from '../toolchain/doctor';\n\nexport type StatusBarIcon = 'loading' | 'dash' | 'check' | 'warning' | 'error';\nexport type StatusBarBackground = 'none' | 'warning' | 'error';\n\nexport interface StatusBarState {\n icon: StatusBarIcon;\n label: string;\n tooltip: string;\n background: StatusBarBackground;\n}\n\n/**\n * Determine the status bar display state from a doctor result.\n *\n * - null: toolchain not found (dash icon)\n * - hasErrors: red error icon\n * - hasWarnings: yellow warning icon\n * - all OK: green check icon\n */\nexport function determineStatusBarState(result: DoctorResult | null): StatusBarState {\n if (result === null) {\n return {\n icon: 'dash',\n label: 'Inference',\n tooltip: 'Inference: Toolchain not found. Click to run doctor.',\n background: 'none',\n };\n }\n\n if (result.hasErrors) {\n return {\n icon: 'error',\n label: 'Inference',\n tooltip: `Inference: ${result.summary || 'Toolchain errors detected'}`,\n background: 'error',\n };\n }\n\n if (result.hasWarnings) {\n return {\n icon: 'warning',\n label: 'Inference',\n tooltip: `Inference: ${result.summary || 'Toolchain warnings detected'}`,\n background: 'warning',\n };\n }\n\n return {\n icon: 'check',\n label: 'Inference',\n tooltip: 'Inference: Toolchain healthy',\n background: 'none',\n };\n}\n", "import * as vscode from 'vscode';\nimport {\n LanguageClient,\n LanguageClientOptions,\n ServerOptions,\n TransportKind,\n} from 'vscode-languageclient/node';\nimport { getSettings } from '../config/settings';\nimport { isExecutable } from '../toolchain/detection';\nimport { inferenceHome } from '../toolchain/home';\nimport { lspActionForConfigChange, resolveLspBinary } from './resolve';\n\n/**\n * Lifecycle management for the `inference-lsp` language server client.\n *\n * A single LanguageClient instance is managed at module level. All lifecycle\n * operations (start/stop/restart) are serialized through an internal promise\n * queue so overlapping triggers (activation, configuration changes, the\n * restart command, post-install retries) cannot race each other.\n *\n * When the server binary cannot be found the client stays stopped QUIETLY:\n * a line is written to the main Inference output channel, but no user-facing\n * notification is shown (the toolchain check already owns that conversation).\n */\n\nlet mainChannel: vscode.LogOutputChannel | undefined;\nlet serverChannel: vscode.OutputChannel | undefined;\nlet client: LanguageClient | undefined;\nlet queue: Promise = Promise.resolve();\n\n/** Serialize a lifecycle operation behind all previously queued ones. */\nfunction enqueue(operation: () => Promise): Promise {\n const next = queue.then(operation);\n queue = next.catch(() => undefined);\n return next;\n}\n\n/**\n * Initialize the language client module. Must be called once during\n * activation, before any other function in this module.\n */\nexport function initializeLspClient(\n context: vscode.ExtensionContext,\n outputChannel: vscode.LogOutputChannel,\n): void {\n mainChannel = outputChannel;\n serverChannel = vscode.window.createOutputChannel(\n 'Inference Language Server',\n { log: true },\n );\n context.subscriptions.push(serverChannel);\n context.subscriptions.push(\n new vscode.Disposable(() => {\n void stopLspClient();\n }),\n );\n}\n\n/** Whether a language client is currently active. */\nexport function isLspRunning(): boolean {\n return client !== undefined;\n}\n\n/**\n * Start the language client if it is enabled and not already running.\n * Quiet when the binary is missing: logs to the output channel only.\n */\nexport function startLspClient(): Promise {\n return enqueue(() => doStart());\n}\n\n/** Stop the language client if it is running. */\nexport function stopLspClient(): Promise {\n return enqueue(() => doStop());\n}\n\n/** Restart the language client, re-resolving the server binary. */\nexport function restartLspClient(): Promise {\n return enqueue(async () => {\n await doStop();\n await doStart();\n });\n}\n\n/**\n * Start the language client if it is not running yet. Called after a\n * successful toolchain install/update so the server comes up without a\n * window reload. Never rejects; failures are logged.\n */\nexport function ensureLspStarted(): Promise {\n return enqueue(async () => {\n if (client) {\n return;\n }\n await doStart();\n }).catch((err) => {\n mainChannel?.error(`Language server start failed: ${err}`);\n });\n}\n\n/**\n * React to a configuration change event: restart on any `inference.lsp.*`\n * change while enabled, stop when disabled.\n */\nexport function handleLspConfigChange(\n event: vscode.ConfigurationChangeEvent,\n): Promise {\n const action = lspActionForConfigChange({\n affectsLsp: event.affectsConfiguration('inference.lsp'),\n enabled: getSettings().lspEnabled,\n running: isLspRunning(),\n });\n switch (action) {\n case 'restart':\n return restartLspClient();\n case 'stop':\n return stopLspClient();\n case 'none':\n return Promise.resolve();\n }\n}\n\nasync function doStart(): Promise {\n if (client) {\n return;\n }\n\n const settings = getSettings();\n if (!settings.lspEnabled) {\n mainChannel?.info(\n 'Language server disabled (inference.lsp.enabled is false).',\n );\n return;\n }\n\n const resolution = resolveLspBinary({\n configuredPath: settings.lspPath,\n inferenceHome: inferenceHome(),\n isWindows: process.platform === 'win32',\n envPath: process.env['PATH'] || '',\n isExecutable,\n });\n\n if (!resolution) {\n if (settings.lspPath) {\n mainChannel?.warn(\n `Language server not started: inference.lsp.path is set to ${settings.lspPath} but it is not executable.`,\n );\n } else {\n mainChannel?.info(\n `Language server not started: inference-lsp not found (searched ${inferenceHome()}/bin and PATH). Install or update the toolchain to enable it.`,\n );\n }\n return;\n }\n\n const serverOptions: ServerOptions = {\n command: resolution.path,\n transport: TransportKind.stdio,\n };\n const clientOptions: LanguageClientOptions = {\n documentSelector: [{ scheme: 'file', language: 'inference' }],\n outputChannel: serverChannel,\n };\n const candidate = new LanguageClient(\n 'inference-lsp',\n 'Inference Language Server',\n serverOptions,\n clientOptions,\n );\n\n try {\n await candidate.start();\n } catch (err) {\n mainChannel?.error(\n `Language server failed to start (${resolution.path}): ${err}`,\n );\n await candidate.dispose().catch(() => undefined);\n return;\n }\n\n client = candidate;\n mainChannel?.info(\n `Language server started: ${resolution.path} (${resolution.source})`,\n );\n}\n\nasync function doStop(): Promise {\n if (!client) {\n return;\n }\n const stopping = client;\n client = undefined;\n try {\n await stopping.stop();\n mainChannel?.info('Language server stopped.');\n } catch (err) {\n mainChannel?.warn(`Language server stop failed: ${err}`);\n } finally {\n await stopping.dispose().catch(() => undefined);\n }\n}\n", "import * as path from 'path';\n\n/**\n * Pure helpers for locating the `inference-lsp` language server binary and\n * deciding lifecycle actions. This module MUST NOT import `vscode` (directly\n * or transitively) so it stays importable from plain `node:test` files; all\n * environment access is injected through {@link ResolveLspBinaryOptions}.\n *\n * The resolution semantics deliberately mirror `detectInfs()` in\n * `src/toolchain/detection.ts`:\n * 1. Explicit configured path (`inference.lsp.path`) \u2014 if set but not\n * executable, resolution FAILS without falling back.\n * 2. Managed location (`INFERENCE_HOME/bin/`).\n * 3. System PATH.\n * Resolution is attempted even on platforms without prebuilt toolchain\n * support, matching detectInfs() which still probes a bare binary name there.\n */\n\n/** Source where the inference-lsp binary was found. */\nexport type LspBinarySource = 'settings' | 'managed' | 'path';\n\n/** Result of inference-lsp binary resolution. */\nexport interface LspBinaryResolution {\n path: string;\n source: LspBinarySource;\n}\n\n/** Inputs for {@link resolveLspBinary}; all environment access is explicit. */\nexport interface ResolveLspBinaryOptions {\n /** Value of the `inference.lsp.path` setting; empty means auto-detect. */\n configuredPath: string;\n /** Resolved INFERENCE_HOME directory. */\n inferenceHome: string;\n /** Whether resolving for Windows (`.exe` suffix, `;` PATH separator). */\n isWindows: boolean;\n /** Value of the PATH environment variable. */\n envPath: string;\n /** Probe that reports whether a candidate file is executable. */\n isExecutable: (filePath: string) => boolean;\n}\n\n/** Platform-specific file name of the language server binary. */\nexport function lspBinaryName(isWindows: boolean): string {\n return isWindows ? 'inference-lsp.exe' : 'inference-lsp';\n}\n\n/**\n * Resolve the inference-lsp binary location.\n *\n * Search order (same as `detectInfs()`):\n * 1. Configured path \u2014 used verbatim; when set but not executable the\n * result is `null` with NO fallback to other locations.\n * 2. Managed location: `/bin/`.\n * 3. First match on PATH.\n */\nexport function resolveLspBinary(\n options: ResolveLspBinaryOptions,\n): LspBinaryResolution | null {\n if (options.configuredPath) {\n if (options.isExecutable(options.configuredPath)) {\n return { path: options.configuredPath, source: 'settings' };\n }\n return null;\n }\n\n const binaryName = lspBinaryName(options.isWindows);\n\n const managedPath = path.join(options.inferenceHome, 'bin', binaryName);\n if (options.isExecutable(managedPath)) {\n return { path: managedPath, source: 'managed' };\n }\n\n const sep = options.isWindows ? ';' : ':';\n const dirs = options.envPath.split(sep).filter(Boolean);\n for (const dir of dirs) {\n const candidate = path.join(dir, binaryName);\n if (options.isExecutable(candidate)) {\n return { path: candidate, source: 'path' };\n }\n }\n\n return null;\n}\n\n/** Lifecycle action to take in response to a configuration change. */\nexport type LspConfigChangeAction = 'restart' | 'stop' | 'none';\n\n/**\n * Decide how the language client should react to a configuration change.\n *\n * - Changes outside `inference.lsp.*` are ignored.\n * - Disabling stops a running client (no-op when already stopped).\n * - Any `inference.lsp.*` change while enabled triggers a restart so the\n * client re-resolves the binary; restart also covers the not-yet-running\n * case (stop is a no-op, then a fresh start is attempted).\n */\nexport function lspActionForConfigChange(change: {\n affectsLsp: boolean;\n enabled: boolean;\n running: boolean;\n}): LspConfigChangeAction {\n if (!change.affectsLsp) {\n return 'none';\n }\n if (!change.enabled) {\n return change.running ? 'stop' : 'none';\n }\n return 'restart';\n}\n", "import * as vscode from 'vscode';\nimport { detectInfs } from '../toolchain/detection';\nimport { exec, ExecResult } from '../utils/exec';\nimport {\n ComponentName,\n KNOWN_COMPONENTS,\n componentAddArgs,\n} from '../toolchain/components';\n\n/** Guard against concurrent component install attempts. */\nlet installing = false;\n\n/**\n * Timeout for a component install. Managed downloads can be ~100 MB, far\n * beyond the default exec timeout, so allow up to ten minutes.\n */\nconst INSTALL_TIMEOUT_MS = 600_000;\n\n/**\n * Register the inference.installComponent command.\n * Returns the Disposable to add to context.subscriptions.\n */\nexport function registerInstallComponentCommand(\n outputChannel: vscode.OutputChannel,\n): vscode.Disposable {\n return vscode.commands.registerCommand(\n 'inference.installComponent',\n async (component: string = 'wasm-opt') => {\n if (installing) {\n vscode.window.showInformationMessage(\n 'Inference component installation is already in progress.',\n );\n return;\n }\n\n if (!isKnownComponent(component)) {\n vscode.window.showErrorMessage(\n `Inference: unknown component '${component}'.`,\n );\n return;\n }\n\n const detection = detectInfs();\n if (!detection) {\n vscode.window\n .showWarningMessage(\n 'Inference toolchain not found. Install it first.',\n 'Install',\n )\n .then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand(\n 'inference.installToolchain',\n );\n }\n });\n return;\n }\n\n installing = true;\n try {\n const result = await installWithProgress(\n detection.path,\n component,\n outputChannel,\n );\n if (result.stdout) {\n outputChannel.appendLine(result.stdout);\n }\n if (result.stderr) {\n outputChannel.appendLine(result.stderr);\n }\n\n if (result.exitCode === 0) {\n vscode.window.showInformationMessage(\n `Inference: component '${component}' installed.`,\n );\n vscode.commands.executeCommand('inference.runDoctor');\n } else {\n notifyInstallError(component);\n }\n } catch (err) {\n const message =\n err instanceof Error ? err.message : String(err);\n outputChannel.appendLine(\n `Component installation failed: ${message}`,\n );\n notifyInstallError(component);\n } finally {\n installing = false;\n }\n },\n );\n}\n\n/** Type guard: whether a string is a known component name. */\nfunction isKnownComponent(name: string): name is ComponentName {\n return (KNOWN_COMPONENTS as readonly string[]).includes(name);\n}\n\n/** Run `infs component add ` with a VS Code progress notification. */\nfunction installWithProgress(\n infsPath: string,\n component: ComponentName,\n outputChannel: vscode.OutputChannel,\n): Thenable {\n return vscode.window.withProgress(\n {\n location: vscode.ProgressLocation.Notification,\n title: 'Inference Component',\n cancellable: false,\n },\n async (progress) => {\n progress.report({ message: `Installing ${component}...` });\n outputChannel.appendLine(`Installing component '${component}'...`);\n return exec(infsPath, componentAddArgs(component), {\n timeoutMs: INSTALL_TIMEOUT_MS,\n });\n },\n );\n}\n\n/** Show an error notification for component installation failure. */\nfunction notifyInstallError(component: ComponentName): void {\n vscode.window\n .showErrorMessage(\n `Inference: failed to install component '${component}'. See output for details.`,\n 'Show Output',\n 'Retry',\n )\n .then((action) => {\n if (action === 'Show Output') {\n vscode.commands.executeCommand('inference.showOutput');\n } else if (action === 'Retry') {\n vscode.commands.executeCommand(\n 'inference.installComponent',\n component,\n );\n }\n });\n}\n", "import { DoctorResult } from './doctor';\n\n/**\n * Toolchain components the CLI can provision via `infs component add`.\n *\n * Mirrors the `KNOWN_COMPONENTS` list in the `infs component` command\n * (`apps/infs/src/commands/component.rs`); keep the two in sync.\n */\nexport const KNOWN_COMPONENTS = ['wasm-opt'] as const;\n\n/** A component name understood by `infs component`. */\nexport type ComponentName = (typeof KNOWN_COMPONENTS)[number];\n\n/** Build the argv for `infs component add `. */\nexport function componentAddArgs(component: ComponentName): string[] {\n return ['component', 'add', component];\n}\n\n/**\n * Whether a doctor result indicates the wasm-opt component needs attention,\n * i.e. any check named `wasm-opt` reported a warning or failure.\n */\nexport function wasmOptNeedsAttention(result: DoctorResult): boolean {\n return result.checks.some(\n (check) =>\n check.name === 'wasm-opt' &&\n (check.status === 'warn' || check.status === 'fail'),\n );\n}\n", "import * as vscode from 'vscode';\nimport { detectInfs } from '../toolchain/detection';\nimport { runDoctor, DoctorResult } from '../toolchain/doctor';\nimport { formatDoctorChecks } from '../toolchain/doctorFormat';\nimport { wasmOptNeedsAttention } from '../toolchain/components';\nimport { updateStatusBar } from '../ui/statusBar';\n\n/** Guard against concurrent doctor runs. */\nlet running = false;\n\n/**\n * Register the inference.runDoctor command.\n *\n * When invoked: detect infs \u2192 run doctor \u2192 display results in output\n * channel \u2192 update status bar \u2192 show notification summary.\n */\nexport function registerDoctorCommand(\n outputChannel: vscode.OutputChannel,\n statusBarItem: vscode.StatusBarItem,\n): vscode.Disposable {\n return vscode.commands.registerCommand(\n 'inference.runDoctor',\n async () => {\n if (running) {\n return;\n }\n\n const detection = detectInfs();\n if (!detection) {\n outputChannel.appendLine('Doctor: infs binary not found.');\n updateStatusBar(statusBarItem, null);\n vscode.window\n .showWarningMessage(\n 'Inference toolchain not found. Install it first.',\n 'Install',\n )\n .then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand(\n 'inference.installToolchain',\n );\n }\n });\n return;\n }\n\n running = true;\n try {\n outputChannel.appendLine(\n `Running infs doctor (${detection.path})...`,\n );\n const result = await runDoctor(detection.path);\n\n if (!result) {\n outputChannel.appendLine(\n 'Doctor: failed to execute infs doctor.',\n );\n updateStatusBar(statusBarItem, null);\n vscode.window.showErrorMessage(\n 'Inference: Failed to run doctor. See output for details.',\n );\n return;\n }\n\n for (const line of formatDoctorChecks(result)) {\n outputChannel.appendLine(line);\n }\n updateStatusBar(statusBarItem, result);\n vscode.commands.executeCommand('inference.refreshConfigView');\n\n if (result.hasErrors) {\n const actions = ['Show Output'];\n if (wasmOptNeedsAttention(result)) {\n actions.push('Install wasm-opt');\n }\n vscode.window\n .showErrorMessage(\n `Inference doctor: ${result.summary}`,\n ...actions,\n )\n .then((action) => {\n if (action === 'Show Output') {\n outputChannel.show();\n } else if (action === 'Install wasm-opt') {\n vscode.commands.executeCommand(\n 'inference.installComponent',\n 'wasm-opt',\n );\n }\n });\n } else if (result.hasWarnings) {\n const actions = ['Show Output'];\n if (wasmOptNeedsAttention(result)) {\n actions.push('Install wasm-opt');\n }\n vscode.window\n .showWarningMessage(\n `Inference doctor: ${result.summary}`,\n ...actions,\n )\n .then((action) => {\n if (action === 'Show Output') {\n outputChannel.show();\n } else if (action === 'Install wasm-opt') {\n vscode.commands.executeCommand(\n 'inference.installComponent',\n 'wasm-opt',\n );\n }\n });\n } else {\n vscode.window.showInformationMessage(\n 'Inference: Toolchain is healthy.',\n );\n }\n } finally {\n running = false;\n }\n },\n );\n}\n\n", "import { DoctorResult } from './doctor';\n\nconst STATUS_TAGS: Record = {\n ok: '[OK] ',\n warn: '[WARN]',\n fail: '[FAIL]',\n};\n\n/**\n * Format doctor check results into display lines.\n *\n * Each check is formatted as: ` [TAG] name: message`\n * If a summary is present, it is appended after a blank line.\n * Separator lines wrap the output.\n */\nexport function formatDoctorChecks(result: DoctorResult): string[] {\n const lines: string[] = [];\n lines.push('--- Doctor Report ---');\n for (const check of result.checks) {\n const tag = STATUS_TAGS[check.status] ?? `[${check.status.toUpperCase()}]`;\n lines.push(` ${tag} ${check.name}: ${check.message}`);\n }\n if (result.summary) {\n lines.push('');\n lines.push(result.summary);\n }\n lines.push('---------------------');\n return lines;\n}\n", "import * as vscode from 'vscode';\nimport { detectInfs } from '../toolchain/detection';\nimport { fetchVersions, getCurrentVersion } from '../toolchain/versions';\nimport { buildVersionPickItems } from '../toolchain/versionPicker';\nimport { performVersionChange } from './versionChange';\n\n/** Guard against concurrent select operations. */\nlet selecting = false;\n\n/**\n * Register the inference.selectVersion command.\n * Shows a QuickPick with available toolchain versions and switches to the selected one.\n */\nexport function registerSelectVersionCommand(\n outputChannel: vscode.OutputChannel,\n): vscode.Disposable {\n return vscode.commands.registerCommand(\n 'inference.selectVersion',\n async () => {\n if (selecting) {\n vscode.window.showInformationMessage(\n 'Version selection is already in progress.',\n );\n return;\n }\n\n const detection = detectInfs();\n if (!detection) {\n vscode.window\n .showWarningMessage(\n 'Inference toolchain not found. Install it first.',\n 'Install',\n )\n .then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand(\n 'inference.installToolchain',\n );\n }\n });\n return;\n }\n\n selecting = true;\n try {\n const versions = await fetchVersions(detection.path);\n if (!versions) {\n vscode.window.showErrorMessage(\n 'Inference: Failed to fetch available versions.',\n );\n return;\n }\n\n const currentVersion = await getCurrentVersion(detection.path);\n\n const items = buildVersionPickItems(versions, currentVersion);\n\n if (items.length === 0) {\n vscode.window.showInformationMessage(\n 'No toolchain versions available for this platform.',\n );\n return;\n }\n\n const picked = await vscode.window.showQuickPick(items, {\n placeHolder: 'Select toolchain version',\n matchOnDescription: true,\n });\n\n if (!picked) {\n return;\n }\n\n const selectedVersion = picked.label;\n if (selectedVersion === currentVersion) {\n vscode.window.showInformationMessage(\n `Already using toolchain v${selectedVersion}.`,\n );\n return;\n }\n\n await performVersionChange(detection.path, selectedVersion, outputChannel, 'Switching to');\n } finally {\n selecting = false;\n }\n },\n );\n}\n", "import { exec } from '../utils/exec';\n\n/** Version info returned by `infs versions --json`. */\nexport interface VersionInfo {\n version: string;\n stable: boolean;\n platforms: string[];\n available_for_current: boolean;\n}\n\n/**\n * Parse the JSON output of `infs versions --json`.\n * Returns an empty array if the output is invalid.\n */\nexport function parseVersionsOutput(stdout: string): VersionInfo[] {\n try {\n const parsed = JSON.parse(stdout);\n if (!Array.isArray(parsed)) {\n return [];\n }\n return parsed;\n } catch {\n return [];\n }\n}\n\n/**\n * Parse the version string from `infs version` output.\n * Expected format: \"infs X.Y.Z\"\n * Returns the version string or null on parse failure.\n */\nexport function parseCurrentVersion(stdout: string): string | null {\n const match = stdout.match(/^infs\\s+(\\S+)/);\n return match ? match[1] : null;\n}\n\n/**\n * Run `infs versions --json` and parse the output.\n * Returns null if the command fails.\n */\nexport async function fetchVersions(\n infsPath: string,\n): Promise {\n try {\n const result = await exec(infsPath, ['versions', '--json'], {\n timeoutMs: 30_000,\n });\n if (result.exitCode !== 0) {\n return null;\n }\n return parseVersionsOutput(result.stdout);\n } catch {\n return null;\n }\n}\n\n/**\n * Run `infs version` and parse the current version.\n * Returns null if the command fails or the output is unexpected.\n */\nexport async function getCurrentVersion(\n infsPath: string,\n): Promise {\n try {\n const result = await exec(infsPath, ['version'], {\n timeoutMs: 10_000,\n });\n if (result.exitCode !== 0) {\n return null;\n }\n return parseCurrentVersion(result.stdout);\n } catch {\n return null;\n }\n}\n\n/** Result of an install-and-set-default operation. */\nexport interface SwitchResult {\n success: boolean;\n installedButNotDefault: boolean;\n error?: string;\n}\n\n/**\n * Install a toolchain version and set it as default.\n *\n * Runs `infs install VERSION` followed by `infs default VERSION`.\n * Handles the partial-success case where install succeeds but setting default fails.\n */\nexport async function installAndSetDefault(\n infsPath: string,\n version: string,\n): Promise {\n const installResult = await exec(infsPath, ['install', version], {\n timeoutMs: 120_000,\n });\n if (installResult.exitCode !== 0) {\n const detail = installResult.stderr || installResult.stdout;\n return { success: false, installedButNotDefault: false, error: detail };\n }\n\n const defaultResult = await exec(infsPath, ['default', version], {\n timeoutMs: 30_000,\n });\n if (defaultResult.exitCode !== 0) {\n const detail = defaultResult.stderr || defaultResult.stdout;\n return { success: false, installedButNotDefault: true, error: detail };\n }\n\n return { success: true, installedButNotDefault: false };\n}\n", "import { VersionInfo } from './versions';\nimport { compareSemver } from '../utils/semver';\n\nexport interface PickItem {\n label: string;\n description?: string;\n}\n\n/**\n * Build QuickPick items from available versions.\n *\n * - Filters to `available_for_current` versions only\n * - Sorts descending by semver\n * - Tags the current version with \"(current)\" and stable versions with \"(stable)\"\n * - Moves the current version to the top of the list\n */\nexport function buildVersionPickItems(\n versions: VersionInfo[],\n currentVersion: string | null,\n): PickItem[] {\n const available = versions\n .filter((v) => v.available_for_current)\n .sort((a, b) => compareSemver(b.version, a.version));\n\n const items: PickItem[] = available.map((v) => {\n const tags: string[] = [];\n if (v.version === currentVersion) {\n tags.push('current');\n }\n if (v.stable) {\n tags.push('stable');\n }\n return {\n label: v.version,\n description: tags.length > 0 ? `(${tags.join(', ')})` : undefined,\n };\n });\n\n if (currentVersion) {\n const idx = items.findIndex((i) => i.label === currentVersion);\n if (idx > 0) {\n const [item] = items.splice(idx, 1);\n items.unshift(item);\n }\n }\n\n return items;\n}\n", "import * as vscode from 'vscode';\nimport { installAndSetDefault } from '../toolchain/versions';\nimport { ensureLspStarted } from '../lsp/client';\n\n/**\n * Perform a version change (install + set default) with progress UI.\n *\n * Shared by both the \"Select Version\" and \"Update Toolchain\" commands.\n */\nexport async function performVersionChange(\n infsPath: string,\n version: string,\n outputChannel: vscode.OutputChannel,\n actionVerb: string,\n): Promise {\n await vscode.window.withProgress(\n {\n location: vscode.ProgressLocation.Notification,\n title: 'Inference Toolchain',\n cancellable: false,\n },\n async (progress) => {\n progress.report({ message: `${actionVerb} v${version}...` });\n outputChannel.appendLine(`${actionVerb} toolchain v${version}...`);\n\n const result = await installAndSetDefault(infsPath, version);\n\n if (result.success) {\n outputChannel.appendLine(\n `${actionVerb} toolchain v${version} complete.`,\n );\n vscode.commands.executeCommand(\n 'setContext', 'inference.toolchainInstalled', true,\n );\n vscode.commands.executeCommand('inference.applyTerminalPath');\n vscode.commands.executeCommand('inference.runDoctor');\n void ensureLspStarted();\n vscode.window\n .showInformationMessage(\n `Inference toolchain ${actionVerb.toLowerCase()} to v${version}.`,\n 'Show Output',\n )\n .then((action) => {\n if (action === 'Show Output') {\n outputChannel.show();\n }\n });\n return;\n }\n\n outputChannel.appendLine(\n `${actionVerb} failed: ${result.error}`,\n );\n\n if (result.installedButNotDefault) {\n vscode.window\n .showWarningMessage(\n `Inference: v${version} was installed but could not be set as default. Run \\`infs default ${version}\\` manually.`,\n 'Show Output',\n )\n .then((action) => {\n if (action === 'Show Output') {\n outputChannel.show();\n }\n });\n } else {\n vscode.window.showErrorMessage(\n `Inference: Failed to install v${version}: ${result.error}`,\n );\n }\n },\n );\n}\n", "import * as vscode from 'vscode';\nimport { detectInfs } from '../toolchain/detection';\nimport { fetchVersions, getCurrentVersion } from '../toolchain/versions';\nimport { checkUpdateAvailable } from '../toolchain/updateCheck';\nimport { getSettings } from '../config/settings';\nimport { performVersionChange } from './versionChange';\n\n/** Guard against concurrent update operations. */\nlet updating = false;\n\n/**\n * Register the inference.updateToolchain command.\n * Checks for updates and prompts the user to install if available.\n */\nexport function registerUpdateCommand(\n outputChannel: vscode.OutputChannel,\n): vscode.Disposable {\n return vscode.commands.registerCommand(\n 'inference.updateToolchain',\n async () => {\n if (updating) {\n vscode.window.showInformationMessage(\n 'Update check is already in progress.',\n );\n return;\n }\n\n const detection = detectInfs();\n if (!detection) {\n vscode.window\n .showWarningMessage(\n 'Inference toolchain not found. Install it first.',\n 'Install',\n )\n .then((action) => {\n if (action === 'Install') {\n vscode.commands.executeCommand(\n 'inference.installToolchain',\n );\n }\n });\n return;\n }\n\n updating = true;\n try {\n await checkForUpdatesImpl(detection.path, outputChannel, true);\n } finally {\n updating = false;\n }\n },\n );\n}\n\n/**\n * Check for toolchain updates on activation.\n * Respects the `inference.checkForUpdates` setting.\n * This is a no-op if checks are disabled.\n */\nexport async function checkForUpdates(\n infsPath: string,\n outputChannel: vscode.OutputChannel,\n): Promise {\n if (updating) {\n return;\n }\n const settings = getSettings();\n if (!settings.checkForUpdates) {\n return;\n }\n updating = true;\n try {\n await checkForUpdatesImpl(infsPath, outputChannel, false);\n } finally {\n updating = false;\n }\n}\n\nasync function checkForUpdatesImpl(\n infsPath: string,\n outputChannel: vscode.OutputChannel,\n userInitiated: boolean,\n): Promise {\n const currentVersion = await getCurrentVersion(infsPath);\n if (!currentVersion) {\n outputChannel.appendLine('Update check: could not determine current version.');\n if (userInitiated) {\n vscode.window.showErrorMessage(\n 'Inference: Could not determine the current toolchain version.',\n );\n }\n return;\n }\n\n outputChannel.appendLine(`Update check: current version is ${currentVersion}.`);\n\n const versions = await fetchVersions(infsPath);\n if (!versions) {\n outputChannel.appendLine('Update check: failed to fetch available versions.');\n if (userInitiated) {\n vscode.window.showErrorMessage(\n 'Inference: Failed to check for updates.',\n );\n }\n return;\n }\n\n const result = checkUpdateAvailable(currentVersion, versions);\n\n switch (result.status) {\n case 'no-current-version':\n outputChannel.appendLine('Update check: could not determine current version.');\n if (userInitiated) {\n vscode.window.showErrorMessage(\n 'Inference: Could not determine the current toolchain version.',\n );\n }\n return;\n\n case 'no-versions':\n outputChannel.appendLine('Update check: no versions available for this platform.');\n if (userInitiated) {\n vscode.window.showInformationMessage(\n 'Inference: No toolchain versions available for this platform.',\n );\n }\n return;\n\n case 'up-to-date':\n outputChannel.appendLine(\n `Update check: toolchain is up to date (v${result.version}).`,\n );\n if (userInitiated) {\n vscode.window.showInformationMessage(\n `Inference toolchain is up to date (v${result.version}).`,\n );\n }\n return;\n\n case 'update-available': {\n outputChannel.appendLine(\n `Update check: v${result.latest} available (current: v${result.current}).`,\n );\n\n const action = await vscode.window.showInformationMessage(\n `Inference toolchain update available: v${result.latest} (current: v${result.current})`,\n 'Update',\n 'Release Notes',\n );\n\n if (action === 'Update') {\n await performVersionChange(infsPath, result.latest, outputChannel, 'Updating to');\n } else if (action === 'Release Notes') {\n vscode.env.openExternal(\n vscode.Uri.parse(\n `https://github.com/Inferara/inference/releases/tag/v${result.latest}`,\n ),\n );\n }\n return;\n }\n }\n}\n", "import { VersionInfo } from './versions';\nimport { compareSemver } from '../utils/semver';\n\nexport type UpdateCheckResult =\n | { status: 'up-to-date'; version: string }\n | { status: 'update-available'; current: string; latest: string }\n | { status: 'no-versions' }\n | { status: 'no-current-version' };\n\n/**\n * Determine whether an update is available based on current version and available versions.\n *\n * Filters to `available_for_current` versions and compares the highest against current.\n */\nexport function checkUpdateAvailable(\n currentVersion: string | null,\n versions: VersionInfo[] | null,\n): UpdateCheckResult {\n if (!currentVersion) {\n return { status: 'no-current-version' };\n }\n\n if (!versions) {\n return { status: 'no-versions' };\n }\n\n const candidates = versions.filter((v) => v.available_for_current);\n\n if (candidates.length === 0) {\n return { status: 'no-versions' };\n }\n\n const sorted = [...candidates].sort((a, b) =>\n compareSemver(b.version, a.version),\n );\n const latest = sorted[0];\n\n if (compareSemver(currentVersion, latest.version) >= 0) {\n return { status: 'up-to-date', version: currentVersion };\n }\n\n return {\n status: 'update-available',\n current: currentVersion,\n latest: latest.version,\n };\n}\n", "import * as vscode from 'vscode';\nimport { detectInfs, InfsDetection } from '../toolchain/detection';\nimport { inferenceHome } from '../toolchain/home';\nimport { detectPlatform } from '../toolchain/platform';\nimport { getSettings } from '../config/settings';\nimport { exec } from '../utils/exec';\nimport { DoctorResult } from '../toolchain/doctor';\n\ntype GroupId = 'toolchain' | 'settings';\n\nexport class ConfigItem extends vscode.TreeItem {\n constructor(\n label: string,\n public readonly kind: 'group' | 'property',\n collapsible: vscode.TreeItemCollapsibleState,\n public readonly groupId?: GroupId,\n public readonly settingKey?: string,\n public readonly copyValue?: string,\n ) {\n super(label, collapsible);\n\n if (kind === 'group') {\n this.iconPath = new vscode.ThemeIcon(\n groupId === 'toolchain' ? 'tools' : 'gear',\n );\n }\n\n if (settingKey) {\n this.command = {\n title: 'Open Setting',\n command: 'workbench.action.openSettings',\n arguments: [settingKey],\n };\n }\n\n if (copyValue) {\n this.contextValue = 'inference.configPath';\n }\n }\n}\n\nexport class InferenceConfigProvider\n implements vscode.TreeDataProvider\n{\n private _onDidChangeTreeData = new vscode.EventEmitter<\n ConfigItem | undefined | null\n >();\n readonly onDidChangeTreeData = this._onDidChangeTreeData.event;\n\n private detection: InfsDetection | null = null;\n private version: string | null = null;\n private doctorResult: DoctorResult | null = null;\n\n refresh(detection?: InfsDetection | null, doctorResult?: DoctorResult | null): void {\n if (detection !== undefined) {\n this.detection = detection;\n }\n if (doctorResult !== undefined) {\n this.doctorResult = doctorResult;\n }\n this._onDidChangeTreeData.fire(undefined);\n }\n\n getTreeItem(element: ConfigItem): vscode.TreeItem {\n return element;\n }\n\n async getChildren(element?: ConfigItem): Promise {\n if (!element) {\n return [\n new ConfigItem(\n 'Toolchain',\n 'group',\n vscode.TreeItemCollapsibleState.Expanded,\n 'toolchain',\n ),\n new ConfigItem(\n 'Settings',\n 'group',\n vscode.TreeItemCollapsibleState.Expanded,\n 'settings',\n ),\n ];\n }\n\n if (element.groupId === 'toolchain') {\n return this.getToolchainChildren();\n }\n\n if (element.groupId === 'settings') {\n return this.getSettingsChildren();\n }\n\n return [];\n }\n\n private async getToolchainChildren(): Promise {\n const detection = this.detection ?? detectInfs();\n const items: ConfigItem[] = [];\n\n if (!detection) {\n const item = new ConfigItem(\n 'infs: not found',\n 'property',\n vscode.TreeItemCollapsibleState.None,\n );\n item.iconPath = new vscode.ThemeIcon('error');\n item.command = {\n title: 'Install Toolchain',\n command: 'inference.installToolchain',\n arguments: [],\n };\n items.push(item);\n return items;\n }\n\n const infsItem = new ConfigItem(\n `infs: ${detection.path} (${detection.source})`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n undefined,\n undefined,\n detection.path,\n );\n infsItem.iconPath = new vscode.ThemeIcon('file-binary');\n items.push(infsItem);\n\n const version = await this.resolveVersion(detection.path);\n const versionItem = new ConfigItem(\n `Version: ${version ?? 'unknown'}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n );\n versionItem.iconPath = new vscode.ThemeIcon('tag');\n items.push(versionItem);\n\n const home = inferenceHome();\n const homeIsDefault = !process.env['INFERENCE_HOME'];\n const homeItem = new ConfigItem(\n `Home: ${home} (${homeIsDefault ? 'default' : 'env'})`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n undefined,\n undefined,\n home,\n );\n homeItem.iconPath = new vscode.ThemeIcon('home');\n items.push(homeItem);\n\n const platform = detectPlatform();\n const platformItem = new ConfigItem(\n `Platform: ${platform?.id ?? 'unknown'}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n );\n platformItem.iconPath = new vscode.ThemeIcon('device-desktop');\n items.push(platformItem);\n\n const status = this.doctorResult\n ? this.doctorResult.hasErrors\n ? 'errors'\n : this.doctorResult.hasWarnings\n ? 'warnings'\n : 'healthy'\n : 'unknown';\n const statusIcon = this.doctorResult\n ? this.doctorResult.hasErrors\n ? 'error'\n : this.doctorResult.hasWarnings\n ? 'warning'\n : 'pass'\n : 'question';\n const statusItem = new ConfigItem(\n `Status: ${status}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n );\n statusItem.iconPath = new vscode.ThemeIcon(statusIcon);\n statusItem.command = {\n title: 'Run Doctor',\n command: 'inference.runDoctor',\n arguments: [],\n };\n items.push(statusItem);\n\n return items;\n }\n\n private getSettingsChildren(): ConfigItem[] {\n const settings = getSettings();\n\n const pathItem = new ConfigItem(\n `Path: ${settings.path || '(auto-detect)'}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n undefined,\n 'inference.path',\n );\n pathItem.iconPath = new vscode.ThemeIcon('file-symlink-directory');\n\n const autoInstallItem = new ConfigItem(\n `Auto Install: ${settings.autoInstall ? 'enabled' : 'disabled'}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n undefined,\n 'inference.autoInstall',\n );\n autoInstallItem.iconPath = new vscode.ThemeIcon('cloud-download');\n\n const updateItem = new ConfigItem(\n `Check for Updates: ${settings.checkForUpdates ? 'enabled' : 'disabled'}`,\n 'property',\n vscode.TreeItemCollapsibleState.None,\n undefined,\n 'inference.checkForUpdates',\n );\n updateItem.iconPath = new vscode.ThemeIcon('sync');\n\n return [pathItem, autoInstallItem, updateItem];\n }\n\n private async resolveVersion(infsPath: string): Promise {\n if (this.version) {\n return this.version;\n }\n try {\n const result = await exec(infsPath, ['version']);\n if (result.exitCode !== 0) {\n return null;\n }\n const match = result.stdout.match(/^infs\\s+(\\S+)/);\n if (match) {\n this.version = match[1];\n return this.version;\n }\n return null;\n } catch {\n return null;\n }\n }\n\n dispose(): void {\n this._onDidChangeTreeData.dispose();\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIO,SAAS,gBAAwB;AACpC,SAAO,QAAQ,IAAI,gBAAgB,KAAU,UAAQ,YAAQ,GAAG,YAAY;AAChF;AANA,IAAAA,KACA;AADA;AAAA;AAAA;AAAA,IAAAA,MAAoB;AACpB,WAAsB;AAAA;AAAA;;;ACgBf,SAAS,KACZ,SACA,MACA,SACmB;AACnB,QAAM,UAAU,SAAS,aAAa;AACtC,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACpC,UAAM,QAAW,SAAM,SAAS,MAAM;AAAA,MAClC,KAAK,SAAS;AAAA,MACd,KAAK,SAAS,MAAM,EAAE,GAAG,QAAQ,KAAK,GAAG,QAAQ,IAAI,IAAI;AAAA,MACzD,OAAO,CAAC,UAAU,QAAQ,MAAM;AAAA,MAChC;AAAA,IACJ,CAAC;AAED,UAAM,eAAyB,CAAC;AAChC,UAAM,eAAyB,CAAC;AAEhC,UAAM,OAAO,GAAG,QAAQ,CAAC,UAAkB,aAAa,KAAK,KAAK,CAAC;AACnE,UAAM,OAAO,GAAG,QAAQ,CAAC,UAAkB,aAAa,KAAK,KAAK,CAAC;AAEnE,UAAM,GAAG,SAAS,CAAC,QAAQ,OAAO,GAAG,CAAC;AAEtC,UAAM,GAAG,SAAS,CAAC,SAAS;AACxB,cAAQ;AAAA,QACJ,UAAU,QAAQ;AAAA,QAClB,QAAQ,OAAO,OAAO,YAAY,EAAE,SAAS,OAAO;AAAA,QACpD,QAAQ,OAAO,OAAO,YAAY,EAAE,SAAS,OAAO;AAAA,MACxD,CAAC;AAAA,IACL,CAAC;AAAA,EACL,CAAC;AACL;AA/CA,QASM;AATN;AAAA;AAAA;AAAA,SAAoB;AASpB,IAAM,qBAAqB;AAAA;AA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AA,IACX;AACA,WAAO;AAAA,EACX,SAAS,KAAK;AACV,kBAAc,MAAM,+BAA+B,GAAG,EAAE;AACxD,WAAO;AAAA,EACX;AACJ;AAEA,SAAS,gBAAsB;AAC3B,EAAO,gBACF;AAAA,IACG;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ,EACC,KAAK,CAAC,WAAW;AACd,QAAI,WAAW,WAAW;AACtB,MAAO,kBAAS,eAAe,4BAA4B;AAAA,IAC/D,WAAW,WAAW,qBAAqB;AACvC,MAAO,aAAI;AAAA,QACA,aAAI;AAAA,UACP;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ,WAAW,WAAW,kBAAkB;AACpC,MAAO,kBAAS;AAAA,QACZ;AAAA,QACA;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ,CAAC;AACT;", + "names": ["os", "path", "exports", "error", "require_is", "exports", "exports", "ErrorCodes", "Message", "exports", "Touch", "exports", "Disposable", "exports", "RAL", "exports", "Event", "exports", "CancellationToken", "exports", "CancellationState", "exports", "exports", "MessageReader", "ResolvedMessageReaderOptions", "exports", "MessageWriter", "ResolvedMessageWriterOptions", "exports", "result", "exports", "CancelNotification", "ProgressToken", "ProgressNotification", "StarRequestHandler", "Trace", "TraceValues", "TraceFormat", "SetTraceNotification", "LogTraceNotification", "ConnectionErrors", "ConnectionStrategy", "IdCancellationReceiverStrategy", "RequestCancellationReceiverStrategy", "CancellationReceiverStrategy", "CancellationSenderStrategy", "CancellationStrategy", "MessageStrategy", "ConnectionOptions", "ConnectionState", "queue", "startTime", "exports", "exports", "RIL", "exports", "path", "os", "process", "exports", "module", "require_main", "exports", "module", "require", "DocumentUri", "URI", "integer", "uinteger", "Position", "Range", "Location", "LocationLink", "Color", "ColorInformation", "ColorPresentation", "FoldingRangeKind", "FoldingRange", "DiagnosticRelatedInformation", "DiagnosticSeverity", "DiagnosticTag", "CodeDescription", "Diagnostic", "Command", "TextEdit", "ChangeAnnotation", "ChangeAnnotationIdentifier", "AnnotatedTextEdit", "TextDocumentEdit", "CreateFile", "RenameFile", "DeleteFile", "WorkspaceEdit", "TextEditChangeImpl", "ChangeAnnotations", "WorkspaceChange", "TextDocumentIdentifier", "VersionedTextDocumentIdentifier", "OptionalVersionedTextDocumentIdentifier", "TextDocumentItem", "MarkupKind", "MarkupContent", "CompletionItemKind", "InsertTextFormat", "CompletionItemTag", "InsertReplaceEdit", "InsertTextMode", "CompletionItemLabelDetails", "CompletionItem", "CompletionList", "MarkedString", "Hover", "ParameterInformation", "SignatureInformation", "DocumentHighlightKind", "DocumentHighlight", "SymbolKind", "SymbolTag", "SymbolInformation", "WorkspaceSymbol", "DocumentSymbol", "CodeActionKind", "CodeActionTriggerKind", "CodeActionContext", "CodeAction", "CodeLens", "FormattingOptions", "DocumentLink", "SelectionRange", "SemanticTokenTypes", "SemanticTokenModifiers", "SemanticTokens", "InlineValueText", "InlineValueVariableLookup", "InlineValueEvaluatableExpression", "InlineValueContext", "InlayHintKind", "InlayHintLabelPart", "InlayHint", "StringValue", "InlineCompletionItem", "InlineCompletionList", "InlineCompletionTriggerKind", "SelectedCompletionInfo", "InlineCompletionContext", "WorkspaceFolder", "TextDocument", "FullTextDocument", "Is", "undefined", "require_messages", "exports", "MessageDirection", "require_is", "exports", "exports", "ImplementationRequest", "exports", "TypeDefinitionRequest", "exports", "WorkspaceFoldersRequest", "DidChangeWorkspaceFoldersNotification", "exports", "ConfigurationRequest", "exports", "DocumentColorRequest", "ColorPresentationRequest", "exports", "FoldingRangeRequest", "FoldingRangeRefreshRequest", "exports", "DeclarationRequest", "exports", "SelectionRangeRequest", "exports", "WorkDoneProgress", "WorkDoneProgressCreateRequest", "WorkDoneProgressCancelNotification", "exports", "CallHierarchyPrepareRequest", "CallHierarchyIncomingCallsRequest", "CallHierarchyOutgoingCallsRequest", "exports", "TokenFormat", "SemanticTokensRegistrationType", "SemanticTokensRequest", "SemanticTokensDeltaRequest", "SemanticTokensRangeRequest", "SemanticTokensRefreshRequest", "exports", "ShowDocumentRequest", "exports", "LinkedEditingRangeRequest", "exports", "FileOperationPatternKind", "WillCreateFilesRequest", "DidCreateFilesNotification", "WillRenameFilesRequest", "DidRenameFilesNotification", "DidDeleteFilesNotification", "WillDeleteFilesRequest", "exports", "UniquenessLevel", "MonikerKind", "MonikerRequest", "exports", "TypeHierarchyPrepareRequest", "TypeHierarchySupertypesRequest", "TypeHierarchySubtypesRequest", "exports", "InlineValueRequest", "InlineValueRefreshRequest", "exports", "InlayHintRequest", "InlayHintResolveRequest", "InlayHintRefreshRequest", "exports", "DiagnosticServerCancellationData", "DocumentDiagnosticReportKind", "DocumentDiagnosticRequest", "WorkspaceDiagnosticRequest", "DiagnosticRefreshRequest", "exports", "NotebookCellKind", "ExecutionSummary", "NotebookCell", "NotebookDocument", "NotebookDocumentSyncRegistrationType", "DidOpenNotebookDocumentNotification", "NotebookCellArrayChange", "DidChangeNotebookDocumentNotification", "DidSaveNotebookDocumentNotification", "DidCloseNotebookDocumentNotification", "exports", "InlineCompletionRequest", "exports", "TextDocumentFilter", "NotebookDocumentFilter", "NotebookCellTextDocumentFilter", "DocumentSelector", "RegistrationRequest", "UnregistrationRequest", "ResourceOperationKind", "FailureHandlingKind", "PositionEncodingKind", "StaticRegistrationOptions", "TextDocumentRegistrationOptions", "WorkDoneProgressOptions", "InitializeRequest", "InitializeErrorCodes", "InitializedNotification", "ShutdownRequest", "ExitNotification", "DidChangeConfigurationNotification", "MessageType", "ShowMessageNotification", "ShowMessageRequest", "LogMessageNotification", "TelemetryEventNotification", "TextDocumentSyncKind", "DidOpenTextDocumentNotification", "TextDocumentContentChangeEvent", "DidChangeTextDocumentNotification", "DidCloseTextDocumentNotification", "DidSaveTextDocumentNotification", "TextDocumentSaveReason", "WillSaveTextDocumentNotification", "WillSaveTextDocumentWaitUntilRequest", "DidChangeWatchedFilesNotification", "FileChangeType", "RelativePattern", "WatchKind", "PublishDiagnosticsNotification", "CompletionTriggerKind", "CompletionRequest", "CompletionResolveRequest", "HoverRequest", "SignatureHelpTriggerKind", "SignatureHelpRequest", "DefinitionRequest", "ReferencesRequest", "DocumentHighlightRequest", "DocumentSymbolRequest", "CodeActionRequest", "CodeActionResolveRequest", "WorkspaceSymbolRequest", "WorkspaceSymbolResolveRequest", "CodeLensRequest", "CodeLensResolveRequest", "CodeLensRefreshRequest", "DocumentLinkRequest", "DocumentLinkResolveRequest", "DocumentFormattingRequest", "DocumentRangeFormattingRequest", "DocumentRangesFormattingRequest", "DocumentOnTypeFormattingRequest", "PrepareSupportDefaultBehavior", "RenameRequest", "PrepareRenameRequest", "ExecuteCommandRequest", "ApplyWorkspaceEditRequest", "require_connection", "exports", "require_api", "exports", "LSPErrorCodes", "require_main", "exports", "exports", "exports", "exports", "exports", "exports", "vscode", "exports", "vscode", "DiagnosticCode", "exports", "exports", "exports", "exports", "exports", "InsertReplaceRange", "code", "exports", "CodeBlock", "cp", "exports", "exports", "exports", "StaticFeature", "DynamicFeature", "client", "data", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "path", "set", "exports", "vsdiag", "DocumentDiagnosticReportKind", "DiagnosticPullMode", "RequestStateKind", "PullState", "DocumentOrUri", "client", "document", "previousResultId", "token", "result", "resultIds", "exports", "vscode", "Converter", "c2p", "event", "$NotebookCell", "$NotebookDocumentFilter", "$NotebookDocumentSyncOptions", "SyncInfo", "client", "notebookDocument", "cells", "exports", "client", "params", "sections", "path", "exports", "client", "textDocument", "event", "exports", "client", "document", "position", "context", "token", "item", "exports", "client", "document", "position", "token", "exports", "client", "document", "position", "token", "exports", "client", "document", "position", "context", "token", "exports", "client", "document", "position", "token", "exports", "client", "document", "token", "exports", "client", "query", "token", "item", "exports", "client", "options", "document", "position", "token", "exports", "client", "document", "range", "context", "token", "item", "exports", "client", "document", "token", "codeLens", "exports", "FileFormattingOptions", "client", "options", "document", "token", "range", "ranges", "position", "ch", "exports", "client", "document", "position", "newName", "token", "exports", "client", "document", "token", "link", "exports", "client", "exports", "client", "exports", "client", "color", "context", "token", "document", "exports", "client", "document", "position", "token", "exports", "client", "document", "position", "token", "exports", "client", "event", "exports", "client", "document", "token", "exports", "client", "document", "position", "token", "exports", "client", "document", "positions", "token", "exports", "client", "exports", "client", "document", "position", "token", "item", "exports", "vscode", "client", "document", "token", "previousResultId", "range", "exports", "client", "path", "exports", "client", "document", "position", "token", "exports", "client", "document", "position", "token", "item", "exports", "client", "document", "viewPort", "context", "token", "exports", "client", "document", "viewPort", "token", "exports", "client", "document", "position", "context", "token", "exports", "RevealOutputChannelOn", "ErrorAction", "CloseAction", "State", "SuspendMode", "ResolvedClientOptions", "client", "ClientState", "MessageTransports", "type", "param", "token", "params", "disposable", "connection", "event", "uri", "diagnostics", "error", "ProposedFeatures", "exports", "cp", "process", "require_node", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "require_api", "exports", "require_main", "exports", "cp", "fs", "path", "TransportKind", "Transport", "Executable", "NodeModule", "StreamInfo", "ChildProcessInfo", "LanguageClient", "env", "process", "transport", "require_node", "exports", "module", "vscode", "path", "path", "platform", "vscode", "fs", "os", "path", "fs", "DEFAULT_TIMEOUT_MS", "fs", "path", "platform", "os", "platform", "parseDoctorOutput", "vscode", "vscode", "path", "outputChannel", "outputChannel", "platform", "vscode", "installing", "outputChannel", "installWithProgress", "notifyInstallError", "vscode", "outputChannel", "vscode", "vscode", "outputChannel", "outputChannel", "vscode", "outputChannel", "vscode", "platform", "env", "platform"] } diff --git a/editors/vscode/package.json b/editors/vscode/package.json index ecbec303..37539556 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -2,7 +2,7 @@ "name": "inference", "displayName": "Inference", "description": "Language support for Inference - a programming language for verified WebAssembly", - "version": "0.0.4", + "version": "0.0.5", "publisher": "inference-lang", "license": "GPL-3.0", "icon": "icons/inference.png", @@ -27,6 +27,7 @@ "main": "./dist/extension.js", "activationEvents": [ "workspaceContains:**/*.inf", + "onLanguage:inference", "onView:inference.configView" ], "contributes": { @@ -41,8 +42,8 @@ }, "views": { "inference": [ - { - "id": "inference.configView", + { + "id": "inference.configView", "name": "Configuration", "icon": "icons/file_icon.svg" } @@ -101,6 +102,10 @@ "command": "inference.runDoctor", "title": "Inference: Run Doctor" }, + { + "command": "inference.restartLsp", + "title": "Inference: Restart Language Server" + }, { "command": "inference.showOutput", "title": "Inference: Show Output" @@ -161,6 +166,17 @@ "type": "boolean", "default": true, "description": "Check for toolchain updates on activation." + }, + "inference.lsp.enabled": { + "type": "boolean", + "default": true, + "description": "Start the Inference language server (inference-lsp) automatically. Provides diagnostics, hover, go to definition, completions, and more." + }, + "inference.lsp.path": { + "type": "string", + "default": "", + "scope": "machine", + "description": "Path to the inference-lsp binary. Leave empty for auto-detection (INFERENCE_HOME/bin, then PATH). If set but not executable, the language server is not started." } } }, @@ -230,7 +246,7 @@ "build:prod": "node esbuild.mjs --production", "watch": "node esbuild.mjs --watch", "test": "node --import tsx --test src/test/**/*.test.ts", - "package": "vsce package", + "package": "vsce package --no-dependencies", "publish": "vsce publish", "test syntax": "tsx --test test/grammar.test.ts test/language-config.test.ts" }, @@ -243,5 +259,8 @@ "typescript": "^5.3.0", "vscode-oniguruma": "^2.0.1", "vscode-textmate": "^9.1.0" + }, + "dependencies": { + "vscode-languageclient": "^9.0.1" } } diff --git a/editors/vscode/src/commands/install.ts b/editors/vscode/src/commands/install.ts index 41efaec1..70fd1e45 100644 --- a/editors/vscode/src/commands/install.ts +++ b/editors/vscode/src/commands/install.ts @@ -8,6 +8,7 @@ import { } from '../toolchain/installation'; import { runDoctor } from '../toolchain/doctor'; import { updateStatusBar } from '../ui/statusBar'; +import { ensureLspStarted } from '../lsp/client'; /** Guard against concurrent install attempts. */ let installing = false; @@ -55,6 +56,7 @@ export function registerInstallCommand( updateStatusBar(statusBarItem, doctorResult); vscode.commands.executeCommand('inference.refreshConfigView'); vscode.commands.executeCommand('inference.applyTerminalPath'); + void ensureLspStarted(); notifyInstallSuccess(result.version, result.doctorWarnings); } catch (err) { @@ -73,7 +75,7 @@ export function registerInstallCommand( function installWithProgress( platform: PlatformInfo, outputChannel: vscode.OutputChannel, -): Promise { +): Thenable { return vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, diff --git a/editors/vscode/src/commands/installComponent.ts b/editors/vscode/src/commands/installComponent.ts index 8e0eb9a9..e3f6aa97 100644 --- a/editors/vscode/src/commands/installComponent.ts +++ b/editors/vscode/src/commands/installComponent.ts @@ -103,7 +103,7 @@ function installWithProgress( infsPath: string, component: ComponentName, outputChannel: vscode.OutputChannel, -): Promise { +): Thenable { return vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, diff --git a/editors/vscode/src/commands/versionChange.ts b/editors/vscode/src/commands/versionChange.ts index 1e5daac1..df01ee57 100644 --- a/editors/vscode/src/commands/versionChange.ts +++ b/editors/vscode/src/commands/versionChange.ts @@ -1,5 +1,6 @@ import * as vscode from 'vscode'; import { installAndSetDefault } from '../toolchain/versions'; +import { ensureLspStarted } from '../lsp/client'; /** * Perform a version change (install + set default) with progress UI. @@ -33,6 +34,7 @@ export async function performVersionChange( ); vscode.commands.executeCommand('inference.applyTerminalPath'); vscode.commands.executeCommand('inference.runDoctor'); + void ensureLspStarted(); vscode.window .showInformationMessage( `Inference toolchain ${actionVerb.toLowerCase()} to v${version}.`, diff --git a/editors/vscode/src/config/settings.ts b/editors/vscode/src/config/settings.ts index b868dbe7..de0e83bd 100644 --- a/editors/vscode/src/config/settings.ts +++ b/editors/vscode/src/config/settings.ts @@ -7,6 +7,10 @@ export interface InferenceSettings { autoInstall: boolean; /** Check for toolchain updates on activation. */ checkForUpdates: boolean; + /** Start the language server automatically. */ + lspEnabled: boolean; + /** Custom path to inference-lsp binary. Empty string means auto-detect. */ + lspPath: string; } /** Read current inference.* configuration values. */ @@ -16,5 +20,7 @@ export function getSettings(): InferenceSettings { path: config.get('path', ''), autoInstall: config.get('autoInstall', true), checkForUpdates: config.get('checkForUpdates', true), + lspEnabled: config.get('lsp.enabled', true), + lspPath: config.get('lsp.path', ''), }; } diff --git a/editors/vscode/src/extension.ts b/editors/vscode/src/extension.ts index c5626796..90427772 100644 --- a/editors/vscode/src/extension.ts +++ b/editors/vscode/src/extension.ts @@ -12,6 +12,13 @@ import { registerUpdateCommand, checkForUpdates } from './commands/update'; import { createStatusBar, updateStatusBar } from './ui/statusBar'; import { InferenceConfigProvider, ConfigItem } from './ui/configTree'; import { runDoctor } from './toolchain/doctor'; +import { + handleLspConfigChange, + initializeLspClient, + restartLspClient, + startLspClient, + stopLspClient, +} from './lsp/client'; /** Minimum infs CLI version the extension can work with. */ const MIN_INFS_VERSION = '0.0.1-beta.1'; @@ -91,6 +98,17 @@ export function activate(context: vscode.ExtensionContext) { if (e.affectsConfiguration('inference')) { configProvider.refresh(); } + handleLspConfigChange(e).catch((err) => + outputChannel.error(`Language server reconfigure failed: ${err}`), + ); + }), + ); + + context.subscriptions.push( + vscode.commands.registerCommand('inference.restartLsp', () => { + restartLspClient().catch((err) => + outputChannel.error(`Language server restart failed: ${err}`), + ); }), ); @@ -107,13 +125,18 @@ export function activate(context: vscode.ExtensionContext) { applyTerminalPath(context); + initializeLspClient(context, outputChannel); + startLspClient().catch((err) => + outputChannel.error(`Language server start failed: ${err}`), + ); + checkToolchain(context, statusBarItem, configProvider).catch((err) => outputChannel.error(`Toolchain check failed: ${err}`), ); } -export function deactivate() { - // Nothing to clean up +export function deactivate(): Thenable { + return stopLspClient(); } /** diff --git a/editors/vscode/src/lsp/client.ts b/editors/vscode/src/lsp/client.ts new file mode 100644 index 00000000..ea8dbe2a --- /dev/null +++ b/editors/vscode/src/lsp/client.ts @@ -0,0 +1,202 @@ +import * as vscode from 'vscode'; +import { + LanguageClient, + LanguageClientOptions, + ServerOptions, + TransportKind, +} from 'vscode-languageclient/node'; +import { getSettings } from '../config/settings'; +import { isExecutable } from '../toolchain/detection'; +import { inferenceHome } from '../toolchain/home'; +import { lspActionForConfigChange, resolveLspBinary } from './resolve'; + +/** + * Lifecycle management for the `inference-lsp` language server client. + * + * A single LanguageClient instance is managed at module level. All lifecycle + * operations (start/stop/restart) are serialized through an internal promise + * queue so overlapping triggers (activation, configuration changes, the + * restart command, post-install retries) cannot race each other. + * + * When the server binary cannot be found the client stays stopped QUIETLY: + * a line is written to the main Inference output channel, but no user-facing + * notification is shown (the toolchain check already owns that conversation). + */ + +let mainChannel: vscode.LogOutputChannel | undefined; +let serverChannel: vscode.OutputChannel | undefined; +let client: LanguageClient | undefined; +let queue: Promise = Promise.resolve(); + +/** Serialize a lifecycle operation behind all previously queued ones. */ +function enqueue(operation: () => Promise): Promise { + const next = queue.then(operation); + queue = next.catch(() => undefined); + return next; +} + +/** + * Initialize the language client module. Must be called once during + * activation, before any other function in this module. + */ +export function initializeLspClient( + context: vscode.ExtensionContext, + outputChannel: vscode.LogOutputChannel, +): void { + mainChannel = outputChannel; + serverChannel = vscode.window.createOutputChannel( + 'Inference Language Server', + { log: true }, + ); + context.subscriptions.push(serverChannel); + context.subscriptions.push( + new vscode.Disposable(() => { + void stopLspClient(); + }), + ); +} + +/** Whether a language client is currently active. */ +export function isLspRunning(): boolean { + return client !== undefined; +} + +/** + * Start the language client if it is enabled and not already running. + * Quiet when the binary is missing: logs to the output channel only. + */ +export function startLspClient(): Promise { + return enqueue(() => doStart()); +} + +/** Stop the language client if it is running. */ +export function stopLspClient(): Promise { + return enqueue(() => doStop()); +} + +/** Restart the language client, re-resolving the server binary. */ +export function restartLspClient(): Promise { + return enqueue(async () => { + await doStop(); + await doStart(); + }); +} + +/** + * Start the language client if it is not running yet. Called after a + * successful toolchain install/update so the server comes up without a + * window reload. Never rejects; failures are logged. + */ +export function ensureLspStarted(): Promise { + return enqueue(async () => { + if (client) { + return; + } + await doStart(); + }).catch((err) => { + mainChannel?.error(`Language server start failed: ${err}`); + }); +} + +/** + * React to a configuration change event: restart on any `inference.lsp.*` + * change while enabled, stop when disabled. + */ +export function handleLspConfigChange( + event: vscode.ConfigurationChangeEvent, +): Promise { + const action = lspActionForConfigChange({ + affectsLsp: event.affectsConfiguration('inference.lsp'), + enabled: getSettings().lspEnabled, + running: isLspRunning(), + }); + switch (action) { + case 'restart': + return restartLspClient(); + case 'stop': + return stopLspClient(); + case 'none': + return Promise.resolve(); + } +} + +async function doStart(): Promise { + if (client) { + return; + } + + const settings = getSettings(); + if (!settings.lspEnabled) { + mainChannel?.info( + 'Language server disabled (inference.lsp.enabled is false).', + ); + return; + } + + const resolution = resolveLspBinary({ + configuredPath: settings.lspPath, + inferenceHome: inferenceHome(), + isWindows: process.platform === 'win32', + envPath: process.env['PATH'] || '', + isExecutable, + }); + + if (!resolution) { + if (settings.lspPath) { + mainChannel?.warn( + `Language server not started: inference.lsp.path is set to ${settings.lspPath} but it is not executable.`, + ); + } else { + mainChannel?.info( + `Language server not started: inference-lsp not found (searched ${inferenceHome()}/bin and PATH). Install or update the toolchain to enable it.`, + ); + } + return; + } + + const serverOptions: ServerOptions = { + command: resolution.path, + transport: TransportKind.stdio, + }; + const clientOptions: LanguageClientOptions = { + documentSelector: [{ scheme: 'file', language: 'inference' }], + outputChannel: serverChannel, + }; + const candidate = new LanguageClient( + 'inference-lsp', + 'Inference Language Server', + serverOptions, + clientOptions, + ); + + try { + await candidate.start(); + } catch (err) { + mainChannel?.error( + `Language server failed to start (${resolution.path}): ${err}`, + ); + await candidate.dispose().catch(() => undefined); + return; + } + + client = candidate; + mainChannel?.info( + `Language server started: ${resolution.path} (${resolution.source})`, + ); +} + +async function doStop(): Promise { + if (!client) { + return; + } + const stopping = client; + client = undefined; + try { + await stopping.stop(); + mainChannel?.info('Language server stopped.'); + } catch (err) { + mainChannel?.warn(`Language server stop failed: ${err}`); + } finally { + await stopping.dispose().catch(() => undefined); + } +} diff --git a/editors/vscode/src/lsp/resolve.ts b/editors/vscode/src/lsp/resolve.ts new file mode 100644 index 00000000..6b9ddc55 --- /dev/null +++ b/editors/vscode/src/lsp/resolve.ts @@ -0,0 +1,109 @@ +import * as path from 'path'; + +/** + * Pure helpers for locating the `inference-lsp` language server binary and + * deciding lifecycle actions. This module MUST NOT import `vscode` (directly + * or transitively) so it stays importable from plain `node:test` files; all + * environment access is injected through {@link ResolveLspBinaryOptions}. + * + * The resolution semantics deliberately mirror `detectInfs()` in + * `src/toolchain/detection.ts`: + * 1. Explicit configured path (`inference.lsp.path`) — if set but not + * executable, resolution FAILS without falling back. + * 2. Managed location (`INFERENCE_HOME/bin/`). + * 3. System PATH. + * Resolution is attempted even on platforms without prebuilt toolchain + * support, matching detectInfs() which still probes a bare binary name there. + */ + +/** Source where the inference-lsp binary was found. */ +export type LspBinarySource = 'settings' | 'managed' | 'path'; + +/** Result of inference-lsp binary resolution. */ +export interface LspBinaryResolution { + path: string; + source: LspBinarySource; +} + +/** Inputs for {@link resolveLspBinary}; all environment access is explicit. */ +export interface ResolveLspBinaryOptions { + /** Value of the `inference.lsp.path` setting; empty means auto-detect. */ + configuredPath: string; + /** Resolved INFERENCE_HOME directory. */ + inferenceHome: string; + /** Whether resolving for Windows (`.exe` suffix, `;` PATH separator). */ + isWindows: boolean; + /** Value of the PATH environment variable. */ + envPath: string; + /** Probe that reports whether a candidate file is executable. */ + isExecutable: (filePath: string) => boolean; +} + +/** Platform-specific file name of the language server binary. */ +export function lspBinaryName(isWindows: boolean): string { + return isWindows ? 'inference-lsp.exe' : 'inference-lsp'; +} + +/** + * Resolve the inference-lsp binary location. + * + * Search order (same as `detectInfs()`): + * 1. Configured path — used verbatim; when set but not executable the + * result is `null` with NO fallback to other locations. + * 2. Managed location: `/bin/`. + * 3. First match on PATH. + */ +export function resolveLspBinary( + options: ResolveLspBinaryOptions, +): LspBinaryResolution | null { + if (options.configuredPath) { + if (options.isExecutable(options.configuredPath)) { + return { path: options.configuredPath, source: 'settings' }; + } + return null; + } + + const binaryName = lspBinaryName(options.isWindows); + + const managedPath = path.join(options.inferenceHome, 'bin', binaryName); + if (options.isExecutable(managedPath)) { + return { path: managedPath, source: 'managed' }; + } + + const sep = options.isWindows ? ';' : ':'; + const dirs = options.envPath.split(sep).filter(Boolean); + for (const dir of dirs) { + const candidate = path.join(dir, binaryName); + if (options.isExecutable(candidate)) { + return { path: candidate, source: 'path' }; + } + } + + return null; +} + +/** Lifecycle action to take in response to a configuration change. */ +export type LspConfigChangeAction = 'restart' | 'stop' | 'none'; + +/** + * Decide how the language client should react to a configuration change. + * + * - Changes outside `inference.lsp.*` are ignored. + * - Disabling stops a running client (no-op when already stopped). + * - Any `inference.lsp.*` change while enabled triggers a restart so the + * client re-resolves the binary; restart also covers the not-yet-running + * case (stop is a no-op, then a fresh start is attempted). + */ +export function lspActionForConfigChange(change: { + affectsLsp: boolean; + enabled: boolean; + running: boolean; +}): LspConfigChangeAction { + if (!change.affectsLsp) { + return 'none'; + } + if (!change.enabled) { + return change.running ? 'stop' : 'none'; + } + return 'restart'; +} diff --git a/editors/vscode/src/test/exec.test.ts b/editors/vscode/src/test/exec.test.ts index 01c4cce6..0744ca01 100644 --- a/editors/vscode/src/test/exec.test.ts +++ b/editors/vscode/src/test/exec.test.ts @@ -1,4 +1,5 @@ import * as assert from 'node:assert'; +import * as fs from 'node:fs'; import { describe, it } from 'node:test'; // exec.ts uses child_process.spawn; we test it by running real simple commands. @@ -51,9 +52,13 @@ describe('exec', () => { it('respects cwd option', async () => { const result = await exec('pwd', [], { cwd: '/tmp' }); assert.strictEqual(result.exitCode, 0); - assert.ok( - result.stdout.trim().startsWith('/tmp'), - `Expected /tmp, got ${result.stdout.trim()}`, + // pwd prints the physical path; on macOS /tmp is a symlink to + // /private/tmp, so compare against the resolved real path. + const expected = fs.realpathSync('/tmp'); + assert.strictEqual( + result.stdout.trim(), + expected, + `Expected ${expected}, got ${result.stdout.trim()}`, ); }); diff --git a/editors/vscode/src/test/lsp-resolve.test.ts b/editors/vscode/src/test/lsp-resolve.test.ts new file mode 100644 index 00000000..57e9571c --- /dev/null +++ b/editors/vscode/src/test/lsp-resolve.test.ts @@ -0,0 +1,485 @@ +import * as assert from 'node:assert'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { after, before, describe, it } from 'node:test'; +import { + lspActionForConfigChange, + lspBinaryName, + resolveLspBinary, + ResolveLspBinaryOptions, +} from '../lsp/resolve'; + +/** + * Tests for the pure inference-lsp binary resolution module. + * resolve.ts has no vscode dependency, so it is imported directly. + * + * Two styles are used: + * - Injected fake `isExecutable` callbacks for precedence / separator / + * platform-name matrices (fully deterministic, no filesystem). + * - Real temp directories with an fs-based probe mirroring + * `detection.isExecutable` semantics (F_OK on win32, X_OK elsewhere). + */ + +const isWin = process.platform === 'win32'; + +/** Same probe semantics as src/toolchain/detection.ts isExecutable. */ +function fsIsExecutable(filePath: string): boolean { + try { + const mode = isWin ? fs.constants.F_OK : fs.constants.X_OK; + fs.accessSync(filePath, mode); + return true; + } catch { + return false; + } +} + +/** Build options with sane defaults for the injected-callback tests. */ +function opts( + overrides: Partial, +): ResolveLspBinaryOptions { + return { + configuredPath: '', + inferenceHome: path.join(path.sep, 'home', 'u', '.inference'), + isWindows: false, + envPath: '', + isExecutable: () => false, + ...overrides, + }; +} + +describe('lspBinaryName', () => { + it('is inference-lsp on posix', () => { + assert.strictEqual(lspBinaryName(false), 'inference-lsp'); + }); + + it('is inference-lsp.exe on windows', () => { + assert.strictEqual(lspBinaryName(true), 'inference-lsp.exe'); + }); +}); + +describe('resolveLspBinary (injected callbacks)', () => { + const home = path.join(path.sep, 'home', 'u', '.inference'); + const managedPosix = path.join(home, 'bin', 'inference-lsp'); + const managedWindows = path.join(home, 'bin', 'inference-lsp.exe'); + + describe('settings path', () => { + it('returns the configured path when executable', () => { + const configured = path.join(path.sep, 'opt', 'inference-lsp'); + const result = resolveLspBinary( + opts({ + configuredPath: configured, + isExecutable: (p) => p === configured, + }), + ); + assert.deepStrictEqual(result, { + path: configured, + source: 'settings', + }); + }); + + it('returns null when set but not executable, WITHOUT fallback to managed or PATH', () => { + const dir = path.join(path.sep, 'usr', 'bin'); + const result = resolveLspBinary( + opts({ + configuredPath: path.join(path.sep, 'bad', 'inference-lsp'), + envPath: dir, + // Everything except the configured path is executable. + isExecutable: (p) => + p !== path.join(path.sep, 'bad', 'inference-lsp'), + }), + ); + assert.strictEqual(result, null); + }); + + it('is used verbatim: no .exe suffix appended on windows', () => { + const configured = 'C:\\tools\\my-lsp'; + const probed: string[] = []; + resolveLspBinary( + opts({ + configuredPath: configured, + isWindows: true, + isExecutable: (p) => { + probed.push(p); + return true; + }, + }), + ); + assert.deepStrictEqual(probed, [configured]); + }); + }); + + describe('managed location', () => { + it('finds INFERENCE_HOME/bin/inference-lsp on posix', () => { + const result = resolveLspBinary( + opts({ + inferenceHome: home, + isExecutable: (p) => p === managedPosix, + }), + ); + assert.deepStrictEqual(result, { + path: managedPosix, + source: 'managed', + }); + }); + + it('finds INFERENCE_HOME/bin/inference-lsp.exe on windows', () => { + const result = resolveLspBinary( + opts({ + inferenceHome: home, + isWindows: true, + isExecutable: (p) => p === managedWindows, + }), + ); + assert.deepStrictEqual(result, { + path: managedWindows, + source: 'managed', + }); + }); + }); + + describe('PATH lookup', () => { + it('finds the binary in a PATH directory', () => { + const dir = path.join(path.sep, 'usr', 'local', 'bin'); + const candidate = path.join(dir, 'inference-lsp'); + const result = resolveLspBinary( + opts({ + envPath: dir, + isExecutable: (p) => p === candidate, + }), + ); + assert.deepStrictEqual(result, { path: candidate, source: 'path' }); + }); + + it('returns the FIRST matching PATH directory', () => { + const first = path.join(path.sep, 'a'); + const second = path.join(path.sep, 'b'); + const candidates = [ + path.join(first, 'inference-lsp'), + path.join(second, 'inference-lsp'), + ]; + const result = resolveLspBinary( + opts({ + envPath: [first, second].join(':'), + // Both PATH directories contain an executable candidate. + isExecutable: (p) => candidates.includes(p), + }), + ); + assert.deepStrictEqual(result, { + path: candidates[0], + source: 'path', + }); + }); + + it('splits PATH on ":" on posix', () => { + const dir = path.join(path.sep, 'x'); + const candidate = path.join(dir, 'inference-lsp'); + const result = resolveLspBinary( + opts({ + envPath: `${path.join(path.sep, 'nope')}:${dir}`, + isExecutable: (p) => p === candidate, + }), + ); + assert.deepStrictEqual(result, { path: candidate, source: 'path' }); + }); + + it('splits PATH on ";" on windows', () => { + const dir = 'C:\\tools'; + const candidate = path.join(dir, 'inference-lsp.exe'); + const result = resolveLspBinary( + opts({ + isWindows: true, + envPath: `C:\\nope;${dir}`, + isExecutable: (p) => p === candidate, + }), + ); + assert.deepStrictEqual(result, { path: candidate, source: 'path' }); + }); + + it('does NOT split on ";" on posix (semicolon is part of the dir name)', () => { + const probed: string[] = []; + resolveLspBinary( + opts({ + envPath: '/a;/b', + isExecutable: (p) => { + probed.push(p); + return false; + }, + }), + ); + // Managed probe + one single PATH entry '/a;/b'. + assert.strictEqual(probed.length, 2); + assert.strictEqual(probed[1], path.join('/a;/b', 'inference-lsp')); + }); + + it('skips empty PATH segments', () => { + const dir = path.join(path.sep, 'real'); + const candidate = path.join(dir, 'inference-lsp'); + const result = resolveLspBinary( + opts({ + envPath: `::${dir}::`, + isExecutable: (p) => p === candidate, + }), + ); + assert.deepStrictEqual(result, { path: candidate, source: 'path' }); + }); + + it('returns null when PATH is empty', () => { + const result = resolveLspBinary( + opts({ envPath: '', isExecutable: () => false }), + ); + assert.strictEqual(result, null); + }); + }); + + describe('precedence', () => { + it('settings wins over managed and PATH', () => { + const configured = path.join(path.sep, 'custom', 'lsp'); + const result = resolveLspBinary( + opts({ + configuredPath: configured, + inferenceHome: home, + envPath: path.join(path.sep, 'usr', 'bin'), + isExecutable: () => true, + }), + ); + assert.deepStrictEqual(result, { + path: configured, + source: 'settings', + }); + }); + + it('managed wins over PATH', () => { + const result = resolveLspBinary( + opts({ + inferenceHome: home, + envPath: path.join(path.sep, 'usr', 'bin'), + isExecutable: () => true, + }), + ); + assert.deepStrictEqual(result, { + path: managedPosix, + source: 'managed', + }); + }); + + it('returns null when nothing matches anywhere', () => { + const result = resolveLspBinary( + opts({ + inferenceHome: home, + envPath: [ + path.join(path.sep, 'a'), + path.join(path.sep, 'b'), + ].join(':'), + isExecutable: () => false, + }), + ); + assert.strictEqual(result, null); + }); + }); +}); + +describe('resolveLspBinary (real filesystem)', () => { + let homeDir: string; + let pathDir: string; + let managedBinary: string; + let pathBinary: string; + let nonExecFile: string; + + const binaryName = lspBinaryName(isWin); + + before(() => { + homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-home-')); + fs.mkdirSync(path.join(homeDir, 'bin')); + managedBinary = path.join(homeDir, 'bin', binaryName); + + pathDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lsp-path-')); + pathBinary = path.join(pathDir, binaryName); + + nonExecFile = path.join(homeDir, 'not-executable'); + fs.writeFileSync(nonExecFile, 'plain file\n'); + fs.chmodSync(nonExecFile, 0o644); + }); + + after(() => { + fs.rmSync(homeDir, { recursive: true }); + fs.rmSync(pathDir, { recursive: true }); + }); + + function fsOpts( + overrides: Partial, + ): ResolveLspBinaryOptions { + return { + configuredPath: '', + inferenceHome: homeDir, + isWindows: isWin, + envPath: '', + isExecutable: fsIsExecutable, + ...overrides, + }; + } + + function createExecutable(filePath: string): void { + fs.writeFileSync(filePath, '#!/bin/sh\n'); + fs.chmodSync(filePath, 0o755); + } + + it('finds a real managed binary', () => { + createExecutable(managedBinary); + try { + const result = resolveLspBinary(fsOpts({})); + assert.deepStrictEqual(result, { + path: managedBinary, + source: 'managed', + }); + } finally { + fs.rmSync(managedBinary); + } + }); + + it('finds a real binary via PATH when managed location is empty', () => { + createExecutable(pathBinary); + try { + const sep = isWin ? ';' : ':'; + const result = resolveLspBinary( + fsOpts({ envPath: [os.tmpdir(), pathDir].join(sep) }), + ); + assert.deepStrictEqual(result, { + path: pathBinary, + source: 'path', + }); + } finally { + fs.rmSync(pathBinary); + } + }); + + it('resolves a real executable via configured settings path', () => { + createExecutable(managedBinary); + try { + const result = resolveLspBinary( + fsOpts({ configuredPath: managedBinary }), + ); + assert.deepStrictEqual(result, { + path: managedBinary, + source: 'settings', + }); + } finally { + fs.rmSync(managedBinary); + } + }); + + it('returns null for a configured path pointing at a missing file, even when managed exists', () => { + createExecutable(managedBinary); + try { + const result = resolveLspBinary( + fsOpts({ + configuredPath: path.join(homeDir, 'does-not-exist'), + }), + ); + assert.strictEqual(result, null); + } finally { + fs.rmSync(managedBinary); + } + }); + + it('returns null for a configured non-executable file on unix, even when managed exists', () => { + if (isWin) { + // On windows the probe is F_OK: existence implies usable. + return; + } + createExecutable(managedBinary); + try { + const result = resolveLspBinary( + fsOpts({ configuredPath: nonExecFile }), + ); + assert.strictEqual(result, null); + } finally { + fs.rmSync(managedBinary); + } + }); + + it('ignores a non-executable managed binary on unix and falls through to PATH', () => { + if (isWin) { + return; + } + fs.writeFileSync(managedBinary, 'not executable\n'); + fs.chmodSync(managedBinary, 0o644); + createExecutable(pathBinary); + try { + const result = resolveLspBinary(fsOpts({ envPath: pathDir })); + assert.deepStrictEqual(result, { + path: pathBinary, + source: 'path', + }); + } finally { + fs.rmSync(managedBinary); + fs.rmSync(pathBinary); + } + }); + + it('returns null when no binary exists anywhere', () => { + const result = resolveLspBinary(fsOpts({ envPath: pathDir })); + assert.strictEqual(result, null); + }); +}); + +describe('lspActionForConfigChange', () => { + it('ignores changes outside inference.lsp.*', () => { + for (const enabled of [true, false]) { + for (const running of [true, false]) { + assert.strictEqual( + lspActionForConfigChange({ + affectsLsp: false, + enabled, + running, + }), + 'none', + ); + } + } + }); + + it('stops a running client when disabled', () => { + assert.strictEqual( + lspActionForConfigChange({ + affectsLsp: true, + enabled: false, + running: true, + }), + 'stop', + ); + }); + + it('does nothing when disabled and already stopped', () => { + assert.strictEqual( + lspActionForConfigChange({ + affectsLsp: true, + enabled: false, + running: false, + }), + 'none', + ); + }); + + it('restarts a running client on lsp config change', () => { + assert.strictEqual( + lspActionForConfigChange({ + affectsLsp: true, + enabled: true, + running: true, + }), + 'restart', + ); + }); + + it('restarts (i.e., starts) a stopped client when enabled', () => { + assert.strictEqual( + lspActionForConfigChange({ + affectsLsp: true, + enabled: true, + running: false, + }), + 'restart', + ); + }); +}); diff --git a/editors/vscode/src/test/settings-schema.test.ts b/editors/vscode/src/test/settings-schema.test.ts index 92366348..07937c6c 100644 --- a/editors/vscode/src/test/settings-schema.test.ts +++ b/editors/vscode/src/test/settings-schema.test.ts @@ -16,14 +16,16 @@ describe('settings schema (QA Section 8)', () => { const properties = contributes.configuration.properties; const settingKeys = Object.keys(properties); - it('has exactly 3 settings', () => { - assert.strictEqual(settingKeys.length, 3); + it('has exactly 5 settings', () => { + assert.strictEqual(settingKeys.length, 5); }); - it('contains inference.path, inference.autoInstall, inference.checkForUpdates', () => { + it('contains inference.path, inference.autoInstall, inference.checkForUpdates, inference.lsp.enabled, inference.lsp.path', () => { assert.ok(settingKeys.includes('inference.path')); assert.ok(settingKeys.includes('inference.autoInstall')); assert.ok(settingKeys.includes('inference.checkForUpdates')); + assert.ok(settingKeys.includes('inference.lsp.enabled')); + assert.ok(settingKeys.includes('inference.lsp.path')); }); it('inference.path has type=string and default=""', () => { @@ -43,13 +45,26 @@ describe('settings schema (QA Section 8)', () => { assert.strictEqual(setting.type, 'boolean'); assert.strictEqual(setting.default, true); }); + + it('inference.lsp.enabled has type=boolean and default=true', () => { + const setting = properties['inference.lsp.enabled']; + assert.strictEqual(setting.type, 'boolean'); + assert.strictEqual(setting.default, true); + }); + + it('inference.lsp.path has type=string, default="", and machine scope', () => { + const setting = properties['inference.lsp.path']; + assert.strictEqual(setting.type, 'string'); + assert.strictEqual(setting.default, ''); + assert.strictEqual(setting.scope, 'machine'); + }); }); describe('commands schema (QA Section 8)', () => { const commands: Array<{ command: string; title: string }> = contributes.commands; - it('has exactly 10 commands registered', () => { - assert.strictEqual(commands.length, 10); + it('has exactly 11 commands registered', () => { + assert.strictEqual(commands.length, 11); }); it('contains expected command IDs', () => { @@ -59,6 +74,7 @@ describe('commands schema (QA Section 8)', () => { assert.ok(ids.includes('inference.updateToolchain')); assert.ok(ids.includes('inference.selectVersion')); assert.ok(ids.includes('inference.runDoctor')); + assert.ok(ids.includes('inference.restartLsp')); assert.ok(ids.includes('inference.showOutput')); assert.ok(ids.includes('inference.resetPathAcceptance')); assert.ok(ids.includes('inference.refreshConfigView')); @@ -67,6 +83,24 @@ describe('commands schema (QA Section 8)', () => { }); }); +describe('activation events (QA Section 1)', () => { + const activationEvents: string[] = packageJson.activationEvents; + + it('activates on inference language files and .inf workspaces', () => { + assert.ok(activationEvents.includes('onLanguage:inference')); + assert.ok(activationEvents.includes('workspaceContains:**/*.inf')); + assert.ok(activationEvents.includes('onView:inference.configView')); + }); +}); + +describe('runtime dependencies', () => { + it('declares vscode-languageclient 9.x (bundled by esbuild, not external)', () => { + const dependencies = packageJson.dependencies; + assert.ok(dependencies); + assert.match(dependencies['vscode-languageclient'], /^\^9\./); + }); +}); + describe('walkthrough schema (QA Section 7)', () => { const walkthroughs: Array<{ id: string; diff --git a/ide/base-db/Cargo.toml b/ide/base-db/Cargo.toml index 8d50920c..5ffd36dc 100644 --- a/ide/base-db/Cargo.toml +++ b/ide/base-db/Cargo.toml @@ -6,3 +6,6 @@ license = { workspace = true } homepage = { workspace = true } repository = { workspace = true } description = "Base Database for Inference IDE support" + +[dependencies] +inference-vfs.workspace = true diff --git a/ide/base-db/README.md b/ide/base-db/README.md index 3a002dcc..99745f55 100644 --- a/ide/base-db/README.md +++ b/ide/base-db/README.md @@ -1,50 +1,115 @@ -# inference-base-db - Base Database +# inference-base-db -Source file handling and position utilities for Inference IDE support. +Text-positioning primitives shared across the Inference IDE stack. This crate +holds the small, dependency-light plain-old-data (POD) types that let the +higher IDE layers talk about *where* something is in a file, plus the +[`LineIndex`] that converts between the compiler's byte offsets and the +line/character positions the Language Server Protocol speaks. -## Status +## Where It Sits -Skeleton implementation. See the LSP plan for the full feature roadmap. +``` +apps/lsp + | +ide/ide -> ide/ide-db -> ide/base-db -> ide/vfs +``` + +`base-db` depends only on `ide/vfs` (for `FileId`). It has no dependency on any +compiler crate, and no compiler crate depends on it — it is IDE-only plumbing +that `ide-db` and everything above it build position handling on top of. + +## Two Coordinate Systems + +The compiler and the editor disagree about how to name a position in a file: + +- The compiler's `Location` (in `core/ast`) carries byte `offset_start` / + `offset_end` **and** 1-based line / 1-based *byte* column fields. The IDE + stack uses only the byte **offsets**; it never reads the compiler's + line/column fields, because they are 1-based and column-in-bytes, which is + neither what LSP wants nor cheap to translate without re-scanning the line. +- LSP positions are 0-based line and 0-based **UTF-16 code unit** character — + this is the position encoding [every LSP client must support](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocuments), regardless of what encoding the server would prefer. + +[`LineIndex`] is the single bridge between the two: byte offset ⇄ [`LineCol`]. +Everything else in this crate is a POD carrying a [`FileId`] alongside an +offset or range, with no conversion logic of its own. + +Keeping this crate free of compiler dependencies is deliberate: it converts +offsets and nothing more, so it can be built, tested, and reasoned about in +isolation from parsing, type checking, or analysis. + +## Key Types -## Purpose +| Type | Role | +|---|---| +| `TextRange { start: u32, end: u32 }` | A half-open byte range, `start..end`, `end` exclusive | +| `LineCol { line: u32, character: u32 }` | 0-based line, 0-based UTF-16 column — exactly LSP's `Position` shape | +| `FilePosition { file_id: FileId, offset: u32 }` | A byte offset scoped to a specific file | +| `FileRange { file_id: FileId, range: TextRange }` | A byte range scoped to a specific file | +| `LineIndex` | Owns a copy of one file's text; converts `u32` offset ⇄ `LineCol` | -Provides the foundation for source-level operations: -- Source file content management -- Line/column to byte offset conversion -- Position and range utilities for diagnostics +All five types are `Clone + Copy` (`LineIndex` is `Clone` only, since it owns +text) and comparable with `PartialEq`/`Eq`, so they behave like the plain data +they are — no reference into an arena, no lifetime. -## Planned Types +## `LineIndex` + +`LineIndex::new(text: &str)` builds the index once by recording the byte offset +where every line starts (splitting on `'\n'`; a `'\r'` before it is *not* a line +terminator on its own and stays part of the preceding line's content). From +then on: + +- `line_col(offset: u32) -> LineCol` converts a byte offset to a line/UTF-16 + column. An offset past the end of the text clamps to the end position; an + offset that lands inside a multi-byte character rounds down to that + character's start. +- `offset(line_col: LineCol) -> Option` converts the other way. It returns + `None` only when the line itself is out of range; a `character` past the end + of a valid line clamps to the line's end (the LSP-specified behavior), and a + `character` that lands inside a character rounds down to that character's + start. + +### Why the index holds the text + +UTF-16 column arithmetic needs to inspect the actual characters on a line — any +character above U+FFFF (an astral character, e.g. an emoji) is a surrogate pair +and counts as **two** UTF-16 units, not one. `LineIndex` therefore keeps an +owned copy of the source text and scans the relevant line on demand rather than +precomputing every column. This duplicates bytes already held elsewhere (in the +`Vfs` overlay or a `ClosureFile`), a deliberate v1 trade-off of a small amount +of memory for a self-contained, obviously-correct conversion with no dependency +on a second data structure being in sync. + +## Usage ```rust -/// A source file with content and line index -pub struct SourceFile { - pub id: FileId, - pub content: Arc, - pub line_index: LineIndex, -} - -/// Efficient line/column <-> offset conversion -pub struct LineIndex { /* ... */ } - -/// A position in a file (line, column) -pub struct FilePosition { - pub file_id: FileId, - pub offset: TextSize, -} - -/// A range in a file -pub struct FileRange { - pub file_id: FileId, - pub range: TextRange, -} +use inference_base_db::{LineIndex, LineCol}; + +let source = "fn main() -> i32 {\n return 42;\n}"; +let index = LineIndex::new(source); + +// Byte offset of `42` -> LSP line/character. +let offset = source.find("42").unwrap() as u32; +assert_eq!(index.line_col(offset), LineCol { line: 1, character: 11 }); + +// And back: an LSP position -> byte offset. +assert_eq!(index.offset(LineCol { line: 1, character: 11 }), Some(offset)); ``` -## Dependencies +## Testing -- `inference-vfs` - For `FileId` and `ChangeSet` +Unit tests live inline in `line_index.rs` and `lib.rs`. `line_index.rs` covers: +empty text, no trailing newline, a trailing newline producing an empty final +line, consecutive newlines, `\r` staying inside its line's content, two- and +three-byte UTF-8 characters that are one UTF-16 unit, four-byte astral +characters that are a UTF-16 surrogate pair (`😀`, `𝔘`), multi-byte content +spanning several lines, and a round-trip property test that every char-boundary +offset in a set of representative strings survives `line_col` → `offset` +unchanged. `lib.rs` covers the PODs' `Copy`/equality behavior. -## Building +## Related Resources -```bash -cargo build -p inference-base-db -``` +- [`ide/vfs`](../vfs/README.md) — the `FileId` these PODs are keyed on +- [`ide/ide-db`](../ide-db/README.md) — builds one `LineIndex` per file in an + analysis closure (`ClosureFile::line_index`) +- [LSP Specification — Position](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#position) — the 0-based line / UTF-16 column contract `LineIndex` implements diff --git a/ide/base-db/src/lib.rs b/ide/base-db/src/lib.rs index e69de29b..0785e23b 100644 --- a/ide/base-db/src/lib.rs +++ b/ide/base-db/src/lib.rs @@ -0,0 +1,135 @@ +//! Text-positioning primitives shared across the Inference IDE stack. +//! +//! This crate holds the small, dependency-light plain-old-data types that let +//! the higher IDE layers talk about *where* something is in a file, plus the +//! [`LineIndex`] that converts between the compiler's byte offsets and the +//! line/character positions the Language Server Protocol speaks. +//! +//! # Two coordinate systems +//! +//! The compiler and the editor disagree about how to name a position: +//! +//! * The compiler's `Location` (in `core/ast`) carries byte `offset_start` / +//! `offset_end` **and** 1-based line / 1-based *byte* column fields. The IDE +//! stack uses only the byte **offsets**; it never reads the compiler's +//! line/column fields, because they are 1-based and column-in-bytes, which is +//! neither what LSP wants nor cheap to translate. +//! * LSP positions are 0-based line and 0-based **UTF-16 code unit** character. +//! +//! [`LineIndex`] is the single bridge: byte offset ⇄ [`LineCol`]. Everything +//! else here is a POD carrying a [`FileId`] alongside an offset or range. +//! +//! Keeping this crate free of compiler dependencies is deliberate: it converts +//! offsets and nothing more, so it can be reused and tested in isolation. + +mod line_index; + +pub use inference_vfs::FileId; +pub use line_index::LineIndex; + +/// A half-open range of byte offsets within a single file, `start..end`. +/// +/// `end` is exclusive. An empty range has `start == end`. Offsets are byte +/// positions into UTF-8 source text, matching the compiler's `Location` +/// offsets. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct TextRange { + /// Inclusive start byte offset. + pub start: u32, + /// Exclusive end byte offset. + pub end: u32, +} + +/// A 0-based line and 0-based UTF-16 code-unit character, in LSP coordinates. +/// +/// `character` counts UTF-16 code units from the start of the line, so a +/// character above U+FFFF (which is a surrogate pair in UTF-16) advances it by +/// two. This is the position encoding every LSP client must support. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct LineCol { + /// 0-based line number. + pub line: u32, + /// 0-based offset within the line, in UTF-16 code units. + pub character: u32, +} + +/// A byte offset within a specific file. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct FilePosition { + /// The file the offset refers to. + pub file_id: FileId, + /// Byte offset into that file's text. + pub offset: u32, +} + +/// A byte range within a specific file. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct FileRange { + /// The file the range refers to. + pub file_id: FileId, + /// Byte range within that file's text. + pub range: TextRange, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn text_range_is_pod_and_comparable() { + let a = TextRange { start: 3, end: 7 }; + let b = a; // Copy + assert_eq!(a, b); + assert_eq!(a.start, 3); + assert_eq!(a.end, 7); + assert_ne!(a, TextRange { start: 3, end: 8 }); + } + + #[test] + fn line_col_is_pod_and_comparable() { + let a = LineCol { + line: 2, + character: 5, + }; + let b = a; // Copy + assert_eq!(a, b); + assert_eq!(a.line, 2); + assert_eq!(a.character, 5); + assert_ne!( + a, + LineCol { + line: 2, + character: 6 + } + ); + } + + #[test] + fn file_position_and_range_carry_their_file() { + use std::path::PathBuf; + + let mut vfs = inference_vfs::Vfs::default(); + let file = vfs.intern(&PathBuf::from("/a.inf")); + + let pos = FilePosition { + file_id: file, + offset: 12, + }; + assert_eq!( + pos, + FilePosition { + file_id: file, + offset: 12 + } + ); + assert_eq!(pos.file_id, file); + assert_eq!(pos.offset, 12); + + let range = FileRange { + file_id: file, + range: TextRange { start: 1, end: 4 }, + }; + assert_eq!(range.range, TextRange { start: 1, end: 4 }); + assert_eq!(range.file_id, file); + } +} diff --git a/ide/base-db/src/line_index.rs b/ide/base-db/src/line_index.rs new file mode 100644 index 00000000..42f7c33f --- /dev/null +++ b/ide/base-db/src/line_index.rs @@ -0,0 +1,391 @@ +//! Byte offset ⇄ line/UTF-16-column conversion for a single file's text. + +use crate::LineCol; + +/// A precomputed index over a file's text that converts between byte offsets +/// and LSP-style [`LineCol`] positions (0-based line, 0-based UTF-16 column). +/// +/// # Line splitting +/// +/// Lines are split on the LSP 3.17 end-of-line set — `'\n'`, `'\r\n'`, and a lone +/// `'\r'` — so this index's line count always matches a conformant client's. The +/// terminator is never part of a line's content: `"a\r\nb"` has two lines +/// starting at byte offsets `[0, 3]` (line 0 is `"a"`, line 1 is `"b"`), and +/// `"a\rb"` likewise splits at the bare `'\r'` into `"a"` and `"b"`. A trailing +/// terminator produces a final empty line. +/// +/// # Why it holds the text +/// +/// UTF-16 column arithmetic needs to inspect the actual characters on a line +/// (a char above U+FFFF counts as two UTF-16 units), so the index keeps an owned +/// copy of the text and scans the relevant line on demand. This duplicates the +/// source bytes already held elsewhere as an `Arc`, a deliberate v1 +/// trade-off of memory for a self-contained, obviously-correct conversion. +/// +/// # Relationship to the compiler's `Location` +/// +/// The compiler's `Location` (in `core/ast`) reports 1-based lines and 1-based +/// *byte* columns. Those fields are never consumed here. The IDE stack feeds +/// this index a byte **offset** (`Location::offset_start` / `offset_end`) and +/// receives a 0-based, UTF-16-column [`LineCol`] suitable for LSP. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LineIndex { + /// Owned copy of the file text, scanned during conversion. + text: Box, + /// Byte offset at which each line starts. Always begins with `0`; a new entry + /// is pushed for the byte immediately following every line terminator in the + /// LSP 3.17 set (`'\n'`, `'\r\n'`, and a lone `'\r'`). + line_starts: Vec, +} + +impl LineIndex { + /// Builds the index for `text`, recording the byte offset of every line + /// start. + #[must_use = "constructing a LineIndex is pointless if it is discarded"] + pub fn new(text: &str) -> Self { + let mut line_starts = vec![0u32]; + let bytes = text.as_bytes(); + for (byte_index, &byte) in bytes.iter().enumerate() { + // Split on the LSP 3.17 EOL set: after every `'\n'`, and after a + // `'\r'` that is not immediately followed by `'\n'` (so a `'\r\n'` + // pair counts once, at its `'\n'`). + let is_terminator = match byte { + b'\n' => true, + b'\r' => bytes.get(byte_index + 1) != Some(&b'\n'), + _ => false, + }; + if is_terminator { + line_starts.push((byte_index + 1) as u32); + } + } + Self { + text: text.into(), + line_starts, + } + } + + /// Converts a byte `offset` into its [`LineCol`]. + /// + /// An `offset` past the end of the text clamps to the end position. An + /// `offset` that falls inside a multi-byte character rounds down to that + /// character's start. + #[must_use = "the converted position is the reason to call this"] + pub fn line_col(&self, offset: u32) -> LineCol { + let mut offset = (offset as usize).min(self.text.len()); + while !self.text.is_char_boundary(offset) { + offset -= 1; + } + + let line = self + .line_starts + .partition_point(|&start| start as usize <= offset) + - 1; + let line_start = self.line_starts[line] as usize; + let character = self.text[line_start..offset] + .chars() + .map(|ch| ch.len_utf16() as u32) + .sum(); + + LineCol { + line: line as u32, + character, + } + } + + /// Converts a [`LineCol`] into a byte offset. + /// + /// Returns `None` only when `line_col.line` is out of range. A `character` + /// past the end of the line clamps to the line's end offset (the LSP rule: + /// "if the character value is greater than the line length it defaults back + /// to the line length"). A `character` that lands inside a character rounds + /// down to that character's start. + #[must_use = "the converted offset is the reason to call this"] + pub fn offset(&self, line_col: LineCol) -> Option { + let line = line_col.line as usize; + let line_start = *self.line_starts.get(line)? as usize; + let line_end = self.line_end(line); + let line_text = &self.text[line_start..line_end]; + + let mut utf16_col = 0u32; + let mut byte_offset = line_start as u32; + for ch in line_text.chars() { + let ch_units = ch.len_utf16() as u32; + if line_col.character < utf16_col + ch_units { + return Some(byte_offset); + } + utf16_col += ch_units; + byte_offset += ch.len_utf8() as u32; + } + Some(line_end as u32) + } + + /// Exclusive byte offset of the end of a line's content. + /// + /// For every line but the last this excludes the whole line terminator: two + /// bytes for `'\r\n'`, one for a lone `'\n'` or `'\r'`. The last line ends at + /// the text length. + fn line_end(&self, line: usize) -> usize { + let Some(&next_start) = self.line_starts.get(line + 1) else { + return self.text.len(); + }; + let next_start = next_start as usize; + let bytes = self.text.as_bytes(); + if next_start >= 2 && bytes[next_start - 2] == b'\r' && bytes[next_start - 1] == b'\n' { + next_start - 2 + } else { + next_start - 1 + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lc(line: u32, character: u32) -> LineCol { + LineCol { line, character } + } + + #[test] + fn empty_text_is_one_empty_line() { + let index = LineIndex::new(""); + assert_eq!(index.line_col(0), lc(0, 0)); + // Past EOF clamps to the sole position. + assert_eq!(index.line_col(5), lc(0, 0)); + assert_eq!(index.offset(lc(0, 0)), Some(0)); + // Character past the (empty) line clamps to line end. + assert_eq!(index.offset(lc(0, 9)), Some(0)); + // Line out of range. + assert_eq!(index.offset(lc(1, 0)), None); + } + + #[test] + fn single_line_no_newline() { + let index = LineIndex::new("hello"); + // First and last positions of the line. + assert_eq!(index.line_col(0), lc(0, 0)); + assert_eq!(index.line_col(5), lc(0, 5)); + assert_eq!(index.line_col(3), lc(0, 3)); + // offset == len maps to the end. + assert_eq!(index.line_col(5), lc(0, 5)); + // offset > len clamps to end. + assert_eq!(index.line_col(100), lc(0, 5)); + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + assert_eq!(index.offset(lc(0, 5)), Some(5)); + // Character past line end clamps to line end. + assert_eq!(index.offset(lc(0, 99)), Some(5)); + // Line out of range. + assert_eq!(index.offset(lc(1, 0)), None); + } + + #[test] + fn trailing_newline_makes_empty_last_line() { + let index = LineIndex::new("abc\n"); + // Line starts: [0, 4]. + assert_eq!(index.line_col(0), lc(0, 0)); + assert_eq!(index.line_col(3), lc(0, 3)); // the '\n' byte -> end of line 0 + assert_eq!(index.line_col(4), lc(1, 0)); // EOF -> start of empty line 1 + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + assert_eq!(index.offset(lc(0, 3)), Some(3)); // end of line 0 content + assert_eq!(index.offset(lc(0, 50)), Some(3)); // clamp to line 0 end + assert_eq!(index.offset(lc(1, 0)), Some(4)); // empty last line + assert_eq!(index.offset(lc(2, 0)), None); // out of range + } + + #[test] + fn multiple_lines_first_and_last_positions() { + let index = LineIndex::new("ab\ncd\nef"); + // Line starts: [0, 3, 6]. + // Line 0 = "ab", line 1 = "cd", line 2 = "ef". + assert_eq!(index.line_col(0), lc(0, 0)); + assert_eq!(index.line_col(2), lc(0, 2)); + assert_eq!(index.line_col(3), lc(1, 0)); + assert_eq!(index.line_col(5), lc(1, 2)); + assert_eq!(index.line_col(6), lc(2, 0)); + assert_eq!(index.line_col(8), lc(2, 2)); + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + assert_eq!(index.offset(lc(0, 2)), Some(2)); + assert_eq!(index.offset(lc(1, 0)), Some(3)); + assert_eq!(index.offset(lc(1, 2)), Some(5)); + assert_eq!(index.offset(lc(2, 0)), Some(6)); + assert_eq!(index.offset(lc(2, 2)), Some(8)); + } + + #[test] + fn consecutive_newlines_are_empty_lines() { + let index = LineIndex::new("\n\n"); + // Line starts: [0, 1, 2]; three lines, all empty. + assert_eq!(index.line_col(0), lc(0, 0)); + assert_eq!(index.line_col(1), lc(1, 0)); + assert_eq!(index.line_col(2), lc(2, 0)); + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + assert_eq!(index.offset(lc(1, 0)), Some(1)); + assert_eq!(index.offset(lc(2, 0)), Some(2)); + assert_eq!(index.offset(lc(3, 0)), None); + // Any character on an empty line clamps to its start. + assert_eq!(index.offset(lc(0, 4)), Some(0)); + assert_eq!(index.offset(lc(1, 4)), Some(1)); + } + + #[test] + fn crlf_is_a_single_line_terminator() { + let index = LineIndex::new("a\r\nb"); + // Line starts: [0, 3]. The '\r\n' is one terminator, excluded from + // content: line 0 = "a", line 1 = "b". + assert_eq!(index.line_col(0), lc(0, 0)); // 'a' + assert_eq!(index.line_col(3), lc(1, 0)); // 'b' + assert_eq!(index.line_col(4), lc(1, 1)); // EOF + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + // A character past 'a' clamps to byte 1, where the '\r\n' terminator + // begins (the terminator itself is not addressable content). + assert_eq!(index.offset(lc(0, 1)), Some(1)); + assert_eq!(index.offset(lc(0, 9)), Some(1)); + assert_eq!(index.offset(lc(1, 0)), Some(3)); // 'b' + assert_eq!(index.offset(lc(1, 1)), Some(4)); // end of "b" + } + + #[test] + fn lone_carriage_return_starts_a_new_line() { + // Classic-Mac line ending: a bare '\r' is a line break in the LSP 3.17 + // EOL set, so a conformant client sees two lines and addresses 'b' at + // line 1 — the index must agree, not report every later line off by one. + let index = LineIndex::new("a\rb"); + // Line starts: [0, 2]. Line 0 = "a", line 1 = "b". + assert_eq!(index.line_col(0), lc(0, 0)); // 'a' + assert_eq!(index.line_col(2), lc(1, 0)); // 'b' — the byte after the '\r' + assert_eq!(index.line_col(3), lc(1, 1)); // EOF + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + assert_eq!(index.offset(lc(0, 1)), Some(1)); // clamp to line 0 content end + assert_eq!(index.offset(lc(1, 0)), Some(2)); // 'b' resolves, not dead + assert_eq!(index.offset(lc(1, 1)), Some(3)); // end of "b" + } + + #[test] + fn consecutive_lone_carriage_returns_are_empty_lines() { + let index = LineIndex::new("\r\r"); + // Line starts: [0, 1, 2]; three lines, all empty. + assert_eq!(index.line_col(0), lc(0, 0)); + assert_eq!(index.line_col(1), lc(1, 0)); + assert_eq!(index.line_col(2), lc(2, 0)); + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + assert_eq!(index.offset(lc(1, 0)), Some(1)); + assert_eq!(index.offset(lc(2, 0)), Some(2)); + assert_eq!(index.offset(lc(3, 0)), None); + } + + #[test] + fn two_byte_char_utf16_is_one_unit() { + // "aéb": a=0, é=bytes 1..3 (0xC3 0xA9), b=3. len = 4. + let index = LineIndex::new("aéb"); + assert_eq!(index.line_col(0), lc(0, 0)); // 'a' + assert_eq!(index.line_col(1), lc(0, 1)); // 'é' start + assert_eq!(index.line_col(2), lc(0, 1)); // inside 'é' -> rounds down to its start + assert_eq!(index.line_col(3), lc(0, 2)); // 'b' + assert_eq!(index.line_col(4), lc(0, 3)); // EOF + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + assert_eq!(index.offset(lc(0, 1)), Some(1)); // 'é' + assert_eq!(index.offset(lc(0, 2)), Some(3)); // 'b' + assert_eq!(index.offset(lc(0, 3)), Some(4)); // end + assert_eq!(index.offset(lc(0, 99)), Some(4)); // clamp to line end + } + + #[test] + fn three_byte_char_utf16_is_one_unit() { + // "∀x": ∀ = bytes 0..3 (U+2200), x = 3. len = 4. + let index = LineIndex::new("∀x"); + assert_eq!(index.line_col(0), lc(0, 0)); // '∀' start + assert_eq!(index.line_col(1), lc(0, 0)); // inside '∀' + assert_eq!(index.line_col(2), lc(0, 0)); // inside '∀' + assert_eq!(index.line_col(3), lc(0, 1)); // 'x' + assert_eq!(index.line_col(4), lc(0, 2)); // EOF + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + assert_eq!(index.offset(lc(0, 1)), Some(3)); // 'x' + assert_eq!(index.offset(lc(0, 2)), Some(4)); // end + } + + #[test] + fn four_byte_char_is_a_surrogate_pair() { + // "😀!": 😀 = bytes 0..4 (U+1F600, two UTF-16 units), ! = 4. len = 5. + let index = LineIndex::new("😀!"); + assert_eq!(index.line_col(0), lc(0, 0)); // '😀' start + assert_eq!(index.line_col(1), lc(0, 0)); // inside '😀' + assert_eq!(index.line_col(2), lc(0, 0)); // inside '😀' + assert_eq!(index.line_col(3), lc(0, 0)); // inside '😀' + assert_eq!(index.line_col(4), lc(0, 2)); // '!' -> after the surrogate pair + assert_eq!(index.line_col(5), lc(0, 3)); // EOF + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + // Character 1 lands in the middle of the surrogate pair -> char start. + assert_eq!(index.offset(lc(0, 1)), Some(0)); + assert_eq!(index.offset(lc(0, 2)), Some(4)); // '!' + assert_eq!(index.offset(lc(0, 3)), Some(5)); // end + assert_eq!(index.offset(lc(0, 50)), Some(5)); // clamp to line end + } + + #[test] + fn astral_math_letter_surrogate_pair() { + // "𝔘y": 𝔘 = U+1D518, bytes 0..4, two UTF-16 units; y = 4. len = 5. + let index = LineIndex::new("𝔘y"); + assert_eq!(index.line_col(0), lc(0, 0)); + assert_eq!(index.line_col(4), lc(0, 2)); // 'y' after the pair + assert_eq!(index.line_col(5), lc(0, 3)); // EOF + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + assert_eq!(index.offset(lc(0, 1)), Some(0)); // mid surrogate -> char start + assert_eq!(index.offset(lc(0, 2)), Some(4)); // 'y' + } + + #[test] + fn multibyte_across_multiple_lines() { + // "é∀\n😀b": line 0 = "é∀", line 1 = "😀b". + // Bytes: é(0..2), ∀(2..5), \n(5), 😀(6..10), b(10). len = 11. + // Line starts: [0, 6]. + let index = LineIndex::new("é∀\n😀b"); + + // Line 0. + assert_eq!(index.line_col(0), lc(0, 0)); // 'é' + assert_eq!(index.line_col(2), lc(0, 1)); // '∀' + assert_eq!(index.line_col(5), lc(0, 2)); // '\n' -> end of line 0 content + // Line 1. + assert_eq!(index.line_col(6), lc(1, 0)); // '😀' + assert_eq!(index.line_col(10), lc(1, 2)); // 'b' after the surrogate pair + assert_eq!(index.line_col(11), lc(1, 3)); // EOF + + assert_eq!(index.offset(lc(0, 0)), Some(0)); + assert_eq!(index.offset(lc(0, 1)), Some(2)); // '∀' + assert_eq!(index.offset(lc(0, 2)), Some(5)); // clamp to line 0 end + assert_eq!(index.offset(lc(1, 0)), Some(6)); // '😀' + assert_eq!(index.offset(lc(1, 2)), Some(10)); // 'b' + assert_eq!(index.offset(lc(1, 3)), Some(11)); // end of file + } + + #[test] + fn round_trip_at_every_char_boundary() { + // Every char-boundary offset must survive line_col -> offset unchanged. + // (Interior bytes of a multi-byte '\r\n' terminator are not addressable + // positions, so CRLF sources are exercised by their own tests instead.) + for source in ["hello", "a\rb", "é∀\n😀b", "\n\n", "\r\r", "abc\n", "😀!"] { + let index = LineIndex::new(source); + for offset in 0..=source.len() { + if !source.is_char_boundary(offset) { + continue; + } + let position = index.line_col(offset as u32); + assert_eq!( + index.offset(position), + Some(offset as u32), + "round trip failed for {source:?} at offset {offset}" + ); + } + } + } +} diff --git a/ide/ide-db/Cargo.toml b/ide/ide-db/Cargo.toml index 6b4b2555..c039f998 100644 --- a/ide/ide-db/Cargo.toml +++ b/ide/ide-db/Cargo.toml @@ -6,3 +6,13 @@ license = { workspace = true } homepage = { workspace = true } repository = { workspace = true } description = "IDE Database for Inference IDE support" + +[dependencies] +inference.workspace = true +inference-analysis.workspace = true +inference-ast.workspace = true +inference-base-db.workspace = true +inference-parser.workspace = true +inference-type-checker.workspace = true +inference-vfs.workspace = true +rustc-hash.workspace = true diff --git a/ide/ide-db/README.md b/ide/ide-db/README.md index 84ca4853..00e62e93 100644 --- a/ide/ide-db/README.md +++ b/ide/ide-db/README.md @@ -1,52 +1,176 @@ -# inference-ide-db - IDE Semantic Database +# inference-ide-db -Semantic database and symbol index for Inference IDE support. +The semantic database for the Inference IDE stack. `ide-db` sits above `vfs` +(path ↔ id ↔ content overlay) and `base-db` (line index and position PODs) and +below the feature layer (`ide/ide`). It answers one question — *"what does +this open file mean?"* — by analyzing each open document as its own project +entry and caching the result. -## Status +## Where It Sits -Skeleton implementation. See the LSP plan for the full feature roadmap. +``` +apps/lsp + | +ide/ide + | +ide/ide-db -----consumes-----> core/inference, core/analysis, + | core/type-checker, core/ast, core/parser +ide/base-db + | +ide/vfs +``` + +`ide-db` is the first layer in the IDE stack that depends on the compiler. It +is also the *only* IDE layer that does: `ide/ide` above it never names a +compiler type in its public API, and everything below it (`vfs`, `base-db`) is +compiler-independent plumbing. + +## What It Owns + +- **[`RootDatabase`]** — the open-document overlay (a `Vfs`) plus a memoized + [`FileAnalysis`] per entry file, with closure-aware invalidation so a + keystroke in one buffer does not force every other open buffer to + re-analyze. +- **[`FileAnalysis`]** — the merged arena (reached through its `TypedContext`), + per-file parse errors, structured type diagnostics, unresolved-import + problems, tagged analysis findings, and per-closure-file line indexes and + paths. +- **[`hit_test`]** — position → AST node resolution, scoped to one file. +- **[`file_defs`]** — a pre-order walk of every definition in one file, + including struct methods and spec-nested definitions. + +## What It Does Not Do + +It leaks no protocol types: every result is either a plain struct defined here +or a compiler type re-exported verbatim (`TypeCheckError`, `AnalysisDiagnostic`, +`NodeId`, `Location`, …). The feature layer above (`ide/ide`) translates these +into editor-terminology PODs; the protocol layer above that (`apps/lsp`) +translates *those* into LSP JSON. Import resolution is **not** reimplemented +here — the closure walk lives in `core/inference` behind a `FileLoader` seam, +and `ide-db` drives it with an overlay-then-disk loader, so the compiler and +the IDE resolve imports identically by construction. + +## Design: Every Open File Is Its Own Project Entry + +`RootDatabase` does not model a single fixed project the way a build tool +does. Each file the editor opens is analyzed **as its own project entry** — its +own directory is the source root its imports resolve against — and the +resulting `FileAnalysis` answers every query for that document, including +goto-definition into a file it imports. This means: + +- Opening one file in a multi-file project is enough to get diagnostics, + hover, and navigation for it; there is no "open the workspace root first" + step. +- The same imported file, if also opened directly by the editor, is analyzed a + *second* time as its own separate entry. This is deliberate duplication, not + a cache miss: v1 has no shared, project-wide semantic index, only + per-entry-file analyses. It is simple, always correct, and the duplicated + work is bounded by how many files the editor happens to have open. + +### Closure-aware invalidation + +A keystroke in one buffer must not force every other open buffer to +re-analyze. Every `FileAnalysis` records the absolute paths of every file in +its import closure, so a content change to path `P` invalidates only the +analyses whose closure contains `P` (`RootDatabase::invalidate`). + +One extra case: opening a **previously unseen** path can satisfy an import +that was missing before, but a missing import was never in any closure (there +was no file to record). So a newly-seen overlay additionally invalidates every +analysis that recorded an unresolved import (`had_missing_import`). This is a +deliberately coarse over-approximation — it may recompute an analysis whose +specific missing import is unrelated to the newly-opened file — chosen because +it is simple and always correct. A file that appears on disk without being +opened is not observed; there is no filesystem watch in v1. -## Purpose +Analyses and the overlay are keyed by exact path spelling. A caller that may +refer to one file by two spellings must canonicalize before calling in, so the +same file always arrives under one path (the LSP layer does this once, per +`ide/vfs`'s path-identity contract). -Caches analysis results and provides symbol indexing: -- Parsed AST per file -- Type-checked results per file -- Symbol index (functions, structs, enums) -- Diagnostics collection +### The overlay-then-disk `FileLoader` -## Planned Types +`core/inference` exposes import resolution behind a `FileLoader` trait — a seam +with exactly two methods, `exists` and `read` — so the same closure-walk logic +drives both the compiler (`DiskLoader`, straight to `std::fs`) and the IDE. This +crate's `VfsLoader` implements that trait by consulting the editor's `Vfs` +overlay first and falling back to disk, so an open, unsaved buffer shadows its +on-disk contents while an import the editor has never opened is still read +from disk. Driving `inference::load_project_resilient` through this loader is +what guarantees the compiler and the IDE can never disagree about which files a +program imports — there is exactly one resolution algorithm, parameterized +over where bytes come from. + +`FileAnalysis::compute` builds the loader, calls `load_project_resilient` +(which never fails fast — every file is parsed resiliently and every problem, +from a broken import to a syntax error, is collected as data rather than +aborting), then type-checks the merged arena losslessly with +`inference::type_check_with_diagnostics` and runs every registered analysis +rule (`inference_analysis::rules::all_rules()`) over the resulting +`TypedContext`. + +## Per-File-Local Offsets + +In the merged multi-file arena, every file's byte offsets start at zero — so an +offset alone never names a file. Both `hit_test` and `file_defs` are therefore +always scoped to one `SourceFileId`: the walk starts at that file's own +top-level definitions and descends only through the ids they own, never +crossing into another file. A naive arena-wide scan by offset would return +false hits from same-numbered positions in an unrelated file; a two-file test +in `hit_test.rs` (`scoped_to_one_file_in_a_two_file_arena`) exists specifically +to guard this. + +## Key Types + +| Type | Role | +|---|---| +| `RootDatabase` | Owns the `Vfs` overlay and the per-entry-file `FileAnalysis` cache | +| `FileAnalysis` | One entry file's memoized analysis: arena, `TypedContext`, parse errors, type errors, import problems, findings | +| `ClosureFile` | One file's path, source text, and `LineIndex` within an analysis closure | +| `AnalysisFinding` | One rule finding, tagged with its rule id (`"A035"`) and `Severity` | +| `NodeHit` | Result of [`hit_test`]: the smallest covering node plus its ancestor chain, outermost first | + +## Usage ```rust -/// Central cache of all analysis state -pub struct RootDatabase { - files: FxHashMap, - symbol_index: SymbolIndex, -} - -/// Analysis results for a single file -pub struct FileAnalysis { - pub ast: Option>, - pub typed: Option>, - pub diagnostics: Vec, -} - -/// Index of all symbols for quick lookup -pub struct SymbolIndex { - functions: FxHashMap>, - structs: FxHashMap>, - enums: FxHashMap>, -} -``` +use std::path::Path; +use inference_ide_db::RootDatabase; -## Dependencies +let mut db = RootDatabase::default(); +let path = Path::new("/project/src/main.inf"); +db.open_document(path, "fn main() -> i32 { return 0; }"); -- `inference-vfs` - For `FileId` -- `inference-base-db` - For `SourceFile`, `LineIndex` -- `core/ast` - For AST types -- `core/type-checker` - For typed AST +// Computed lazily on first request, memoized until invalidated. +let analysis = db.analysis(path); +assert!(analysis.type_errors().is_empty()); +assert!(analysis.findings().is_empty()); -## Building +// A subsequent edit invalidates only analyses whose closure contains `path`. +db.change_document(path, "fn main() -> i32 { return x; }"); +assert!(!db.analysis(path).type_errors().is_empty()); +``` + +## Testing + +Unit tests live alongside each module (`analysis.rs`, `hit_test.rs`, +`symbols.rs`, `loader.rs`). Integration tests in `tests/database.rs` exercise +`RootDatabase` end-to-end: overlay-beats-disk precedence, cross-file +`typed_context` queries into an imported file, missing-import recording with +location and module path, a broken imported file still leaving the entry +analyzable, `use root;` and self-import deduplication, mutually-importing +files terminating, and every closure-invalidation case (a change to an +imported file invalidates the entry, a change to an unrelated open file does +not, and opening a previously-unseen file re-triggers analyses that had a +missing import). -```bash -cargo build -p inference-ide-db ``` +cargo test -p inference-ide-db +``` + +## Related Resources + +- [`ide/vfs`](../vfs/README.md) — the path/overlay store `RootDatabase` wraps +- [`ide/base-db`](../base-db/README.md) — `LineIndex` and the position PODs re-exported here +- [`ide/ide`](../ide/README.md) — the feature layer built on `FileAnalysis` +- [`core/inference`](../../core/inference/README.md) — `load_project_resilient`, `FileLoader`, `type_check_with_diagnostics` +- [`core/analysis`](../../core/analysis/README.md) — the rules run over every `FileAnalysis` diff --git a/ide/ide-db/src/analysis.rs b/ide/ide-db/src/analysis.rs new file mode 100644 index 00000000..9e99af60 --- /dev/null +++ b/ide/ide-db/src/analysis.rs @@ -0,0 +1,300 @@ +//! [`FileAnalysis`]: the memoized result of analyzing one open file as its own +//! project entry. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use inference::{FileParseErrors, ImportProblem, LoadedFile, load_project_resilient}; +use inference_analysis::errors::{LabeledDiagnostic, Severity}; +use inference_analysis::rules::all_rules; +use inference_ast::arena::AstArena; +use inference_ast::ids::{DefId, SourceFileId}; +use inference_base_db::LineIndex; +use inference_type_checker::typed_context::TypedContext; +use inference_type_checker::{TypeCheckDiagnostic, TypeCheckOutcome, check_with_diagnostics}; +use inference_vfs::Vfs; +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::hit_test::{NodeHit, hit_test}; +use crate::loader::VfsLoader; +use crate::symbols::file_defs; + +/// One analysis-rule finding, tagged with the producing rule's id and severity. +/// +/// Both the id (`A0xx`) and the severity are per-rule, not per-finding: they are +/// read once from the [`Rule`](inference_analysis::rule::Rule) and stamped onto +/// every finding it returns. The wrapped [`LabeledDiagnostic`] carries the +/// finding's own message and the module path of the file it belongs to. +#[derive(Debug, Clone)] +pub struct AnalysisFinding { + /// The rule's identifier, e.g. `"A035"`. + pub rule_id: &'static str, + /// The rule's severity. + pub severity: Severity, + /// The finding itself, with its file label and diagnostic. + pub labeled: LabeledDiagnostic, +} + +/// The path, source text, and line index of one file in an analysis closure. +/// +/// Cross-file goto-definition resolves a target's module path to its +/// `ClosureFile`, recovering both the file's path (for the returned location's +/// URI) and a line index for a correct byte-offset → line/column conversion in +/// that file rather than in the file the request came from. +#[derive(Debug, Clone)] +pub struct ClosureFile { + path: PathBuf, + source: Arc, + line_index: LineIndex, +} + +impl ClosureFile { + /// The absolute path this file was read from. + #[must_use = "the path is the reason to call this"] + pub fn path(&self) -> &Path { + &self.path + } + + /// The file's source text. + #[must_use = "the source text is the reason to call this"] + pub fn source(&self) -> &str { + &self.source + } + + /// The file's line index, for byte-offset ↔ line/column conversion. + #[must_use = "the line index is the reason to call this"] + pub fn line_index(&self) -> &LineIndex { + &self.line_index + } +} + +/// The memoized analysis of one file treated as its own project entry. +/// +/// Construction resolves the file's import closure through an overlay-then-disk +/// loader, type-checks the merged program losslessly, and runs every analysis +/// rule — all resiliently, so the result is populated as far as a broken program +/// allows. Every query below is a pure read of that cached result. +/// +/// # The arena is the type context's arena +/// +/// A `FileAnalysis` stores no separate arena: the merged arena lives inside its +/// [`TypedContext`] and is reached through [`TypedContext::arena`]. Type checking +/// never mutates the arena, so this is the same arena the loader produced — kept +/// exactly once rather than cloned alongside the context. +pub struct FileAnalysis { + typed: TypedContext, + parse_errors: Vec, + type_errors: Vec, + import_problems: Vec, + findings: Vec, + /// Per closure file, keyed by module path (empty for the entry). + files: FxHashMap, ClosureFile>, + /// Absolute paths of every file in the closure, for change invalidation. + /// Always includes the entry path itself, even when the entry could not be + /// read, so any event touching the entry can invalidate this analysis. + closure_paths: FxHashSet, + /// Whether any import went unresolved, so a newly-opened file might fix it. + had_missing_import: bool, + /// Monotonic stamp identifying this computation, so tests (and callers) can + /// observe whether a query recomputed. + generation: u64, +} + +impl FileAnalysis { + /// Analyzes `entry` as its own project entry, reading its import closure + /// through `vfs` (overlay first, then disk). + /// + /// `generation` stamps the result; the database bumps it on every compute so + /// a recompute is observable. + #[must_use = "the computed analysis must be stored to be of any use"] + pub(crate) fn compute(vfs: &Vfs, entry: &Path, generation: u64) -> Self { + let loader = VfsLoader::new(vfs); + let parse = load_project_resilient(entry, &loader); + + // The entry is always part of its own closure, even when its read failed + // and the resilient walk recorded no `LoadedFile` for it (an unreadable + // entry yields an empty `files` list and no missing-import record). Without + // this, such an analysis has an empty closure and `had_missing_import == + // false`, so no later event — not even a `didOpen`/`didChange` of the entry + // itself — could ever invalidate it, permanently poisoning the entry's + // cache with empty diagnostics. Inserting the entry unconditionally is a + // no-op when the read succeeded (its `LoadedFile` path is already present). + let mut closure_paths: FxHashSet = + parse.files.iter().map(|f| f.path.clone()).collect(); + closure_paths.insert(entry.to_path_buf()); + let had_missing_import = !parse.import_problems.is_empty(); + let path_by_module: FxHashMap, PathBuf> = parse + .files + .into_iter() + .map(|LoadedFile { module_path, path }| (module_path, path)) + .collect(); + + // Type-check by moving the loader's arena into the checker (it consumes + // the arena); everything afterwards, including per-file source, is read + // back through `typed.arena()`, so the merged arena is stored once. + let TypeCheckOutcome { + typed_context, + errors: type_errors, + } = check_with_diagnostics(parse.arena); + + let files = build_closure_files(typed_context.arena(), &path_by_module); + let findings = run_analysis_rules(&typed_context); + + FileAnalysis { + typed: typed_context, + parse_errors: parse.parse_errors, + type_errors, + import_problems: parse.import_problems, + findings, + files, + closure_paths, + had_missing_import, + generation, + } + } + + /// The merged arena of the analyzed closure (the type context's arena). + #[must_use = "the arena is the reason to call this"] + pub fn arena(&self) -> &AstArena { + self.typed.arena() + } + + /// The type context, populated as far as error recovery allowed. Queries such + /// as `get_node_typeinfo`, `lookup_struct`, and `call_target` answer for the + /// parts of the program that type-checked, even when errors are present. + #[must_use = "the type context is the reason to call this"] + pub fn typed_context(&self) -> &TypedContext { + &self.typed + } + + /// Per-file syntax errors, each labeled with its file's module path. + #[must_use = "the parse errors are the reason to call this"] + pub fn parse_errors(&self) -> &[FileParseErrors] { + &self.parse_errors + } + + /// Structured type-check diagnostics, each carrying its variant, per-file + /// source location, and optional module-path file label. + #[must_use = "the type errors are the reason to call this"] + pub fn type_errors(&self) -> &[TypeCheckDiagnostic] { + &self.type_errors + } + + /// `use` imports that did not resolve to a file, anchored at their directive. + #[must_use = "the import problems are the reason to call this"] + pub fn import_problems(&self) -> &[ImportProblem] { + &self.import_problems + } + + /// Every analysis-rule finding, each tagged with its rule id and severity. + #[must_use = "the findings are the reason to call this"] + pub fn findings(&self) -> &[AnalysisFinding] { + &self.findings + } + + /// The stamp identifying this computation. A larger value on a later query + /// for the same entry means the analysis was recomputed after invalidation. + #[must_use = "the generation is the reason to call this"] + pub fn generation(&self) -> u64 { + self.generation + } + + /// The closure file for `module_path` (empty for the entry file), or `None` + /// if that module is not in this closure. + #[must_use = "the closure file is the reason to call this"] + pub fn file(&self, module_path: &[String]) -> Option<&ClosureFile> { + self.files.get(module_path) + } + + /// The line index of the closure file named by `module_path`. + #[must_use = "the line index is the reason to call this"] + pub fn line_index(&self, module_path: &[String]) -> Option<&LineIndex> { + self.files.get(module_path).map(ClosureFile::line_index) + } + + /// The arena [`SourceFileId`] of the file named by `module_path`. + /// + /// Hit-testing and per-file walks key on `SourceFileId`, while cross-file + /// features name a target by module path; this bridges the two. + #[must_use = "the resolved file id is the reason to call this"] + pub fn source_file_id(&self, module_path: &[String]) -> Option { + self.arena() + .source_file_ids() + .find(|&id| self.arena().source_file_module_path(id) == Some(module_path)) + } + + /// The smallest node in `file` covering `offset`, with its ancestor chain. + /// See [`hit_test`]. + #[must_use = "the covering node is the reason to call this"] + pub fn hit_test(&self, file: SourceFileId, offset: u32) -> Option { + hit_test(self.arena(), file, offset) + } + + /// Every definition in `file` in pre-order, including struct methods and + /// spec-nested defs. See [`file_defs`]. + #[must_use = "the collected definitions are the reason to call this"] + pub fn file_defs(&self, file: SourceFileId) -> Vec { + file_defs(self.arena(), file) + } + + /// Whether `path` is one of the files in this analysis's closure. + pub(crate) fn closure_contains(&self, path: &Path) -> bool { + self.closure_paths.contains(path) + } + + /// Whether any import in this analysis went unresolved. + pub(crate) fn had_missing_import(&self) -> bool { + self.had_missing_import + } +} + +/// Builds the module-path → [`ClosureFile`] map: source text comes from each +/// file's `SourceFileData` in `arena` (already read once), the path from the +/// loader's discovery list. +fn build_closure_files( + arena: &AstArena, + path_by_module: &FxHashMap, PathBuf>, +) -> FxHashMap, ClosureFile> { + let mut files = FxHashMap::default(); + for source_file in arena.source_files() { + let Some(path) = path_by_module.get(&source_file.module_path) else { + // Every lowered file was read through the loader, so it has a path; + // skip defensively rather than fabricate one. + continue; + }; + let source: Arc = Arc::from(source_file.source.as_str()); + let line_index = LineIndex::new(&source); + files.insert( + source_file.module_path.clone(), + ClosureFile { + path: path.clone(), + source, + line_index, + }, + ); + } + files +} + +/// Runs every registered analysis rule on `typed_context`, tagging each finding +/// with its rule's id and severity. +/// +/// Rules run whenever a type context exists — which is always, since the checker +/// recovers from errors — because findings on a partially-typed program are +/// still valid. A rule is trusted not to panic on partial data; a panic here is +/// a compiler bug to surface, not to suppress. +fn run_analysis_rules(typed_context: &TypedContext) -> Vec { + let mut findings = Vec::new(); + for rule in all_rules() { + let rule_id = rule.id(); + let severity = rule.severity(); + for labeled in rule.check(typed_context) { + findings.push(AnalysisFinding { + rule_id, + severity, + labeled, + }); + } + } + findings +} diff --git a/ide/ide-db/src/database.rs b/ide/ide-db/src/database.rs new file mode 100644 index 00000000..f5f1c40d --- /dev/null +++ b/ide/ide-db/src/database.rs @@ -0,0 +1,114 @@ +//! [`RootDatabase`]: the open-document store plus memoized per-file analyses. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use inference_vfs::Vfs; +use rustc_hash::FxHashMap; + +use crate::analysis::FileAnalysis; + +/// Owns the editor's open-document overlay and the per-entry-file analyses +/// derived from it. +/// +/// Each open file is analyzed as its own project entry (its directory is the +/// source root). Analyses are computed lazily on first request and memoized +/// until a document change invalidates them. +/// +/// # Closure-aware invalidation +/// +/// A keystroke in one buffer must not force every other open buffer to +/// re-analyze. Each [`FileAnalysis`] records the absolute paths of every file in +/// its import closure, so a content change to path `P` invalidates only the +/// analyses whose closure contains `P`. +/// +/// One extra case: opening a path that had **no overlay content before** can +/// satisfy an import that was missing, but a missing import is not in any closure +/// (there is no file to record). So an open that newly makes overlay content +/// available additionally invalidates every analysis that recorded an unresolved +/// import. Keying this on the overlay (not on whether the path was ever interned) +/// is what makes a `didClose` then `didOpen` re-fire: interning survives a close, +/// but the overlay does not. This is a deliberately coarse over-approximation — +/// it may recompute an analysis whose specific missing import is unrelated to the +/// new file — chosen because it is simple and always correct. Files that appear +/// on disk without being opened are not observed (there is no filesystem watch in +/// v1). +/// +/// # Path identity +/// +/// Analyses and the overlay are keyed by exact path spelling; a caller that may +/// refer to one file by two spellings must canonicalize before calling in, so +/// the same file always arrives under one path. +#[derive(Default)] +pub struct RootDatabase { + vfs: Vfs, + analyses: FxHashMap, + /// Monotonic source of per-analysis generation stamps. + generation: u64, +} + +impl RootDatabase { + /// Opens `path` with `text` as its in-memory contents (an editor `didOpen`). + /// + /// Interns the path if new and installs its overlay text, then invalidates + /// dependent analyses. + pub fn open_document(&mut self, path: &Path, text: impl Into>) { + // The missing-import widening must fire whenever this open makes content + // available where there was none — not only on a path's very first open. + // Interning survives `didClose` (the `Vfs` never drops ids), so keying on + // "never interned" would miss a close/reopen cycle: reopening a file that + // satisfies a previously-missing import would leave the importing analysis + // stale. Keying on "had no overlay before this open" re-fires correctly and + // still subsumes the truly-first open. + let newly_available = self.vfs.contents_of_path(path).is_none(); + let id = self.vfs.intern(path); + self.vfs.set_contents(id, text.into()); + self.invalidate(path, newly_available); + } + + /// Replaces the in-memory contents of an open `path` (an editor `didChange`). + /// + /// A change never introduces a previously-unseen file, so only closures that + /// contain `path` are invalidated. + pub fn change_document(&mut self, path: &Path, text: impl Into>) { + let id = self.vfs.intern(path); + self.vfs.set_contents(id, text.into()); + self.invalidate(path, false); + } + + /// Drops the in-memory contents of `path` (an editor `didClose`). + /// + /// The path stays interned; only its overlay is removed, so analyses whose + /// closure includes `path` recompute and read it from disk next time. + pub fn close_document(&mut self, path: &Path) { + if let Some(id) = self.vfs.file_id(path) { + self.vfs.remove_contents(id); + } + self.invalidate(path, false); + } + + /// The analysis of `path` treated as a project entry, computed on first + /// request and memoized until invalidated. + pub fn analysis(&mut self, path: &Path) -> &FileAnalysis { + if !self.analyses.contains_key(path) { + self.generation += 1; + let analysis = FileAnalysis::compute(&self.vfs, path, self.generation); + self.analyses.insert(path.to_path_buf(), analysis); + } + &self.analyses[path] + } + + /// Drops every memoized analysis affected by a change to `changed`. + /// + /// `newly_available` is true when this event made overlay content available + /// for `changed` where there was none before (a first `didOpen`, or a reopen + /// after a `didClose`); see the type-level docs for why that widens + /// invalidation to analyses with an unresolved import. + fn invalidate(&mut self, changed: &Path, newly_available: bool) { + self.analyses.retain(|_entry, analysis| { + let closure_touched = analysis.closure_contains(changed); + let may_resolve_missing = newly_available && analysis.had_missing_import(); + !(closure_touched || may_resolve_missing) + }); + } +} diff --git a/ide/ide-db/src/hit_test.rs b/ide/ide-db/src/hit_test.rs new file mode 100644 index 00000000..44ab3f03 --- /dev/null +++ b/ide/ide-db/src/hit_test.rs @@ -0,0 +1,911 @@ +//! Position → node hit-testing: the smallest AST node covering a byte offset. +//! +//! # Per-file-local offsets +//! +//! In the merged multi-file arena every file's byte offsets start at zero, so an +//! offset alone does not name a file. Hit-testing is therefore always scoped to +//! one [`SourceFileId`]: the walk starts from that file's own top-level +//! definitions and descends only through the ids they own, never crossing into +//! another file. A naive arena-wide scan by offset would return false hits from +//! same-numbered positions in unrelated files. + +use inference_ast::arena::AstArena; +use inference_ast::ids::{DefId, ExprId, NodeId, SourceFileId, StmtId, TypeId}; +use inference_ast::nodes::{ArgData, ArgKind, Def, Expr, Location, Stmt, TypeNode}; + +/// The result of a position → node hit-test. +/// +/// [`node`](Self::node) is the smallest AST node whose source range covers the +/// queried offset; [`ancestors`](Self::ancestors) is the chain of enclosing +/// nodes from the covering top-level definition inward to that node's immediate +/// parent, outermost first. The ancestor chain is what lets a feature widen its +/// view — from an identifier out to the call, statement, or definition that +/// encloses it — without re-walking the tree. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NodeHit { + /// The smallest node covering the offset. + pub node: NodeId, + /// Enclosing nodes, outermost first, ending at `node`'s immediate parent. + /// Empty when `node` is itself a top-level definition. + pub ancestors: Vec, +} + +/// Returns the smallest node in `file` whose source range covers `offset`, with +/// its ancestor chain, or `None` when no definition in `file` covers `offset` +/// (whitespace between definitions, or a position past the last one). +/// +/// `offset` is a byte offset local to `file`. `offset_end` is exclusive, so the +/// last byte of a token is covered but the byte immediately after it is not. +#[must_use = "the covering node is the reason to call this"] +pub fn hit_test(arena: &AstArena, file: SourceFileId, offset: u32) -> Option { + // HARD INVARIANT: only this file's own definitions. See the module docs. + let mut current = arena[file] + .defs + .iter() + .map(|&def| NodeId::Def(def)) + .find(|&node| covers(arena.node_location(node), offset))?; + + // Descend into the smallest covering child each step, recording every node + // passed through as an ancestor. `current` ends at the smallest covering + // node; `ancestors` holds the enclosing chain, outermost first. + let mut ancestors = Vec::new(); + while let Some(child) = smallest_covering_child(arena, current, offset) { + ancestors.push(current); + current = child; + } + + Some(NodeHit { + node: current, + ancestors, + }) +} + +/// Among the direct children of `node`, the one with the smallest source range +/// that still covers `offset`, or `None` when no child does (so `node` is the +/// smallest covering node). +fn smallest_covering_child(arena: &AstArena, node: NodeId, offset: u32) -> Option { + children_of(arena, node) + .into_iter() + .filter(|&child| covers(arena.node_location(child), offset)) + .min_by_key(|&child| span_len(arena.node_location(child))) +} + +/// Whether `location` covers `offset` (`start <= offset < end`). +/// +/// A [`Location::default`] (all-zero) marks a node the parser left unlocated; it +/// must never match, so an unlocated node cannot spuriously claim offset 0. Its +/// zero-width `0..0` range already excludes every offset, but the guard states +/// the intent. +fn covers(location: Location, offset: u32) -> bool { + if location == Location::default() { + return false; + } + location.offset_start <= offset && offset < location.offset_end +} + +/// The byte width of a location's source range. +fn span_len(location: Location) -> u32 { + location.offset_end.saturating_sub(location.offset_start) +} + +/// The direct child nodes of `node`, each a candidate for the next descent step. +/// Leaves (identifiers, literals, simple types) have none. +fn children_of(arena: &AstArena, node: NodeId) -> Vec { + match node { + NodeId::Def(id) => def_children(arena, id), + NodeId::Stmt(id) => stmt_children(arena, id), + NodeId::Expr(id) => expr_children(arena, id), + NodeId::Type(id) => type_children(arena, id), + NodeId::Block(id) => arena[id].stmts.iter().map(|&s| NodeId::Stmt(s)).collect(), + NodeId::Ident(_) | NodeId::SourceFile(_) => Vec::new(), + } +} + +fn def_children(arena: &AstArena, id: DefId) -> Vec { + let mut out = Vec::new(); + match &arena[id].kind { + Def::Function { + name, + args, + returns, + body, + .. + } => { + out.push(NodeId::Ident(*name)); + arg_children(args, &mut out); + if let Some(ret) = returns { + out.push(NodeId::Type(*ret)); + } + out.push(NodeId::Block(*body)); + } + Def::ExternFunction { + name, + args, + returns, + .. + } => { + out.push(NodeId::Ident(*name)); + arg_children(args, &mut out); + if let Some(ret) = returns { + out.push(NodeId::Type(*ret)); + } + } + Def::Struct { + name, + fields, + methods, + .. + } => { + out.push(NodeId::Ident(*name)); + for field in fields { + out.push(NodeId::Ident(field.name)); + out.push(NodeId::Type(field.ty)); + } + for &method in methods { + out.push(NodeId::Def(method)); + } + } + Def::Enum { name, variants, .. } => { + out.push(NodeId::Ident(*name)); + for &variant in variants { + out.push(NodeId::Ident(variant)); + } + } + Def::Spec { name, defs, .. } => { + out.push(NodeId::Ident(*name)); + for &nested in defs { + out.push(NodeId::Def(nested)); + } + } + Def::Constant { + name, ty, value, .. + } => { + out.push(NodeId::Ident(*name)); + out.push(NodeId::Type(*ty)); + out.push(NodeId::Expr(*value)); + } + Def::TypeAlias { name, ty, .. } => { + out.push(NodeId::Ident(*name)); + out.push(NodeId::Type(*ty)); + } + } + out +} + +/// Adds the arena-backed children of each argument: a named argument contributes +/// its name identifier and type; `self` contributes no node (the keyword has no +/// arena entry). +fn arg_children(args: &[ArgData], out: &mut Vec) { + for arg in args { + match &arg.kind { + ArgKind::Named { name, ty, .. } => { + out.push(NodeId::Ident(*name)); + out.push(NodeId::Type(*ty)); + } + ArgKind::Ignored { ty } | ArgKind::TypeOnly(ty) => out.push(NodeId::Type(*ty)), + ArgKind::SelfRef { .. } => {} + } + } +} + +fn stmt_children(arena: &AstArena, id: StmtId) -> Vec { + let mut out = Vec::new(); + match &arena[id].kind { + Stmt::Block(block) => out.push(NodeId::Block(*block)), + Stmt::Expr(expr) | Stmt::Return { expr } | Stmt::Assert { expr } => { + out.push(NodeId::Expr(*expr)); + } + Stmt::Assign { left, right } => { + out.push(NodeId::Expr(*left)); + out.push(NodeId::Expr(*right)); + } + Stmt::Loop { condition, body } => { + if let Some(condition) = condition { + out.push(NodeId::Expr(*condition)); + } + out.push(NodeId::Block(*body)); + } + Stmt::If { + condition, + then_block, + else_block, + } => { + out.push(NodeId::Expr(*condition)); + out.push(NodeId::Block(*then_block)); + if let Some(else_block) = else_block { + out.push(NodeId::Block(*else_block)); + } + } + Stmt::VarDef { + name, ty, value, .. + } => { + out.push(NodeId::Ident(*name)); + out.push(NodeId::Type(*ty)); + if let Some(value) = value { + out.push(NodeId::Expr(*value)); + } + } + Stmt::TypeDef { name, ty } => { + out.push(NodeId::Ident(*name)); + out.push(NodeId::Type(*ty)); + } + Stmt::ConstDef(def) => out.push(NodeId::Def(*def)), + Stmt::Break => {} + } + out +} + +fn expr_children(arena: &AstArena, id: ExprId) -> Vec { + let mut out = Vec::new(); + match &arena[id].kind { + Expr::Binary { left, right, .. } => { + out.push(NodeId::Expr(*left)); + out.push(NodeId::Expr(*right)); + } + Expr::PrefixUnary { expr, .. } | Expr::Parenthesized { expr } => { + out.push(NodeId::Expr(*expr)); + } + Expr::FunctionCall { function, args, .. } => { + out.push(NodeId::Expr(*function)); + for (name, arg) in args { + if let Some(name) = name { + out.push(NodeId::Ident(*name)); + } + out.push(NodeId::Expr(*arg)); + } + } + Expr::ArrayIndexAccess { array, index } => { + out.push(NodeId::Expr(*array)); + out.push(NodeId::Expr(*index)); + } + Expr::MemberAccess { expr, name } | Expr::TypeMemberAccess { expr, name } => { + out.push(NodeId::Expr(*expr)); + out.push(NodeId::Ident(*name)); + } + Expr::StructLiteral { name, fields } => { + out.push(NodeId::Ident(*name)); + for (field, value) in fields { + out.push(NodeId::Ident(*field)); + out.push(NodeId::Expr(*value)); + } + } + Expr::Identifier(ident) => out.push(NodeId::Ident(*ident)), + Expr::ArrayLiteral { elements } => { + for &element in elements { + out.push(NodeId::Expr(element)); + } + } + Expr::Type(ty) => out.push(NodeId::Type(*ty)), + Expr::NumberLiteral { .. } + | Expr::BoolLiteral { .. } + | Expr::StringLiteral { .. } + | Expr::UnitLiteral + | Expr::Uzumaki => {} + } + out +} + +fn type_children(arena: &AstArena, id: TypeId) -> Vec { + let mut out = Vec::new(); + match &arena[id].kind { + TypeNode::Simple(_) => {} + TypeNode::Array { element, size } => { + out.push(NodeId::Type(*element)); + out.push(NodeId::Expr(*size)); + } + TypeNode::Generic { base, params } => { + out.push(NodeId::Ident(*base)); + for ¶m in params { + out.push(NodeId::Ident(param)); + } + } + TypeNode::Function { params, ret } => { + for ¶m in params { + out.push(NodeId::Type(param)); + } + if let Some(ret) = ret { + out.push(NodeId::Type(*ret)); + } + } + TypeNode::QualifiedName { qualifier, name } => { + out.push(NodeId::Ident(*qualifier)); + out.push(NodeId::Ident(*name)); + } + TypeNode::Qualified { qualifier, name } => { + for &segment in qualifier { + out.push(NodeId::Ident(segment)); + } + out.push(NodeId::Ident(*name)); + } + TypeNode::Custom(ident) => out.push(NodeId::Ident(*ident)), + } + out +} + +#[cfg(test)] +mod tests { + // Test offsets are found in short inline sources, so the `usize -> u32` casts + // used to build them cannot truncate. + #![allow(clippy::cast_possible_truncation)] + + use super::*; + use inference_parser::parse; + + /// Parses a single-file program and returns its arena plus the sole file id. + fn single_file(source: &str) -> (AstArena, SourceFileId) { + let arena = parse(source).arena; + let file = arena.source_file_ids().next().expect("one source file"); + (arena, file) + } + + /// The source text a hit's node spans, for readable assertions. + fn hit_text<'a>(arena: &'a AstArena, source: &'a str, hit: &NodeHit) -> &'a str { + let location = arena.node_location(hit.node); + &source[location.offset_start as usize..location.offset_end as usize] + } + + #[test] + fn hits_identifier_at_its_first_byte() { + let source = "fn f() -> i32 { return abc; }"; + let (arena, file) = single_file(source); + let offset = source.find("abc").unwrap() as u32; + let hit = hit_test(&arena, file, offset).expect("a node covers the identifier"); + assert!(matches!(hit.node, NodeId::Ident(_))); + assert_eq!(hit_text(&arena, source, &hit), "abc"); + } + + #[test] + fn hits_identifier_at_its_last_byte() { + let source = "fn f() -> i32 { return abc; }"; + let (arena, file) = single_file(source); + // The last byte of `abc` is covered (offset_end is exclusive). + let offset = (source.find("abc").unwrap() + 2) as u32; + let hit = hit_test(&arena, file, offset).expect("last byte of the identifier"); + assert_eq!(hit_text(&arena, source, &hit), "abc"); + } + + #[test] + fn one_past_identifier_end_is_not_covered_by_it() { + let source = "fn f() -> i32 { return abc; }"; + let (arena, file) = single_file(source); + // The `;` right after `abc` is not part of the identifier. + let offset = (source.find("abc").unwrap() + 3) as u32; + let hit = hit_test(&arena, file, offset).expect("something still covers"); + assert_ne!(hit_text(&arena, source, &hit), "abc"); + } + + #[test] + fn offset_between_tokens_falls_back_to_the_enclosing_block() { + // A space between two statements is inside the function body block but + // inside no statement, so the block is the smallest covering node. + let source = "fn f() { let x: i32 = 1; let y: i32 = 2; }"; + let (arena, file) = single_file(source); + // Pick an offset in the run of spaces between the two `let`s. + let gap = source.find("; let").unwrap() + 2; + let hit = hit_test(&arena, file, gap as u32).expect("the block covers the gap"); + assert!( + matches!(hit.node, NodeId::Block(_)), + "expected the enclosing block, got {:?}", + hit.node + ); + } + + #[test] + fn offset_zero_hits_the_first_definition() { + let source = "fn first() {} fn second() {}"; + let (arena, file) = single_file(source); + let hit = hit_test(&arena, file, 0).expect("the first def starts at 0"); + // Offset 0 is the `f` of `fn`, inside the first def but covered by no + // child (the `fn` keyword precedes the name identifier). + match hit.node { + NodeId::Def(def) => assert_eq!(arena.def_name(def), "first"), + other => panic!("expected the first definition, got {other:?}"), + } + } + + #[test] + fn offset_at_eof_hits_nothing() { + let source = "fn f() {}"; + let (arena, file) = single_file(source); + let hit = hit_test(&arena, file, source.len() as u32); + assert!( + hit.is_none(), + "EOF is past every definition's exclusive end" + ); + } + + #[test] + fn ancestor_chain_is_deterministic_and_outermost_first() { + let source = "fn f() -> i32 { return a + b; }"; + let (arena, file) = single_file(source); + let offset = source.rfind('b').unwrap() as u32; + let hit = hit_test(&arena, file, offset).expect("covers `b`"); + // Innermost node is the identifier `b`. + assert_eq!(hit_text(&arena, source, &hit), "b"); + // Ancestors run outermost-first: Def, Block, Stmt(return), Expr(a + b), + // Expr(b's Identifier expr). Every ancestor must cover the offset and the + // chain must start at the top-level definition. + assert!(matches!(hit.ancestors.first(), Some(NodeId::Def(_)))); + for &ancestor in &hit.ancestors { + assert!(covers(arena.node_location(ancestor), offset)); + } + // Determinism: a second identical query yields the same chain. + let again = hit_test(&arena, file, offset).unwrap(); + assert_eq!(hit, again); + } + + #[test] + fn hits_a_type_annotation() { + let source = "fn f(p: i32) {}"; + let (arena, file) = single_file(source); + let offset = source.find("i32").unwrap() as u32; + let hit = hit_test(&arena, file, offset).expect("covers the type"); + assert!(matches!(hit.node, NodeId::Type(_))); + } + + #[test] + fn hits_the_member_name_of_a_member_access() { + // `p.field`: the `.field` name and the `p` receiver are siblings under the + // member access, so a hit must resolve to the one covering the offset. + let source = "fn f() -> i32 { return p.field; }"; + let (arena, file) = single_file(source); + + let name_hit = hit_test(&arena, file, source.find("field").unwrap() as u32) + .expect("covers the member name"); + assert_eq!(hit_text(&arena, source, &name_hit), "field"); + + // The receiver descends to its own identifier, not the member name. + let recv_hit = hit_test(&arena, file, source.find("p.field").unwrap() as u32) + .expect("covers the receiver"); + assert_eq!(hit_text(&arena, source, &recv_hit), "p"); + } + + #[test] + fn hits_the_callee_and_arguments_of_a_function_call() { + // `g(x, y)`: goto-def dispatches on the callee identifier, hover on an + // argument — both are descent targets under the call expression. + let source = "fn f() -> i32 { return g(x, y); }"; + let (arena, file) = single_file(source); + + let callee = + hit_test(&arena, file, source.find("g(").unwrap() as u32).expect("covers the callee"); + assert_eq!(hit_text(&arena, source, &callee), "g"); + + let arg = + hit_test(&arena, file, source.find("y)").unwrap() as u32).expect("covers the argument"); + assert_eq!(hit_text(&arena, source, &arg), "y"); + } + + #[test] + fn hits_the_name_and_field_of_a_struct_literal() { + // `P { a: 1 }`: goto-def on the struct name, hover on a field name. + let source = "fn f() -> i32 { return P { a: 1 }; }"; + let (arena, file) = single_file(source); + + let name = hit_test(&arena, file, source.find("P {").unwrap() as u32) + .expect("covers the struct name"); + assert_eq!(hit_text(&arena, source, &name), "P"); + + let field = hit_test(&arena, file, source.find("a:").unwrap() as u32) + .expect("covers the field name"); + assert_eq!(hit_text(&arena, source, &field), "a"); + } + + #[test] + fn scoped_to_one_file_in_a_two_file_arena() { + // Two files whose identifiers occupy the same byte range: a query against + // one file must return that file's node, never the other's, even though + // the offset is valid in both. + use inference_parser::parse_into; + + let entry_src = "fn e() -> i32 { return aaa; }"; + let lib_src = "fn l() -> i32 { return bbb; }"; + let parsed = parse_into(AstArena::default(), entry_src, vec![]); + let parsed = parse_into(parsed.arena, lib_src, vec!["lib".to_string()]); + let arena = parsed.arena; + + let entry = arena + .source_file_ids() + .find(|&f| arena[f].module_path.is_empty()) + .unwrap(); + let lib = arena + .source_file_ids() + .find(|&f| arena[f].module_path == vec!["lib".to_string()]) + .unwrap(); + + // `aaa` and `bbb` sit at the same per-file-local offset. + let offset = entry_src.find("aaa").unwrap() as u32; + assert_eq!(offset, lib_src.find("bbb").unwrap() as u32); + + let entry_hit = hit_test(&arena, entry, offset).expect("entry hit"); + let lib_hit = hit_test(&arena, lib, offset).expect("lib hit"); + if let (NodeId::Ident(a), NodeId::Ident(b)) = (entry_hit.node, lib_hit.node) { + assert_eq!(arena.ident_name(a), "aaa"); + assert_eq!(arena.ident_name(b), "bbb"); + } else { + panic!("expected identifier hits in both files"); + } + } + + #[test] + fn unlocated_nodes_are_never_hit() { + // `covers` rejects a default (all-zero) location, so a node the parser + // left unlocated cannot be returned even at offset 0. + assert!(!covers(Location::default(), 0)); + assert!(!covers(Location::default(), 5)); + } + + #[test] + fn hits_the_name_args_and_return_type_of_an_extern_function() { + // An extern function declares a signature but no body, so its descendable + // children are the name, the argument, and the return type. + let source = "external fn hash(seed: i32) -> i64;"; + let (arena, file) = single_file(source); + + let name = hit_test(&arena, file, source.find("hash").unwrap() as u32) + .expect("covers the extern function name"); + assert_eq!(hit_text(&arena, source, &name), "hash"); + + let arg = hit_test(&arena, file, source.find("seed").unwrap() as u32) + .expect("covers the argument name"); + assert_eq!(hit_text(&arena, source, &arg), "seed"); + + let arg_ty = hit_test(&arena, file, source.find("i32").unwrap() as u32) + .expect("covers the argument type"); + assert!(matches!(arg_ty.node, NodeId::Type(_))); + + let ret = hit_test(&arena, file, source.find("i64").unwrap() as u32) + .expect("covers the return type"); + assert!(matches!(ret.node, NodeId::Type(_))); + assert_eq!(hit_text(&arena, source, &ret), "i64"); + } + + #[test] + fn hits_the_name_and_variants_of_an_enum() { + let source = "enum Color { Red, Green, Blue }"; + let (arena, file) = single_file(source); + + let name = hit_test(&arena, file, source.find("Color").unwrap() as u32) + .expect("covers the enum name"); + assert_eq!(hit_text(&arena, source, &name), "Color"); + + let variant = + hit_test(&arena, file, source.find("Green").unwrap() as u32).expect("covers a variant"); + assert_eq!(hit_text(&arena, source, &variant), "Green"); + assert!(matches!(variant.node, NodeId::Ident(_))); + // A variant sits directly under the enum definition. + assert!(matches!(variant.ancestors.first(), Some(NodeId::Def(_)))); + } + + #[test] + fn hits_the_name_and_nested_definition_of_a_spec() { + let source = "spec Bank { fn balance() -> i64 { return 0; } }"; + let (arena, file) = single_file(source); + + let name = hit_test(&arena, file, source.find("Bank").unwrap() as u32) + .expect("covers the spec name"); + assert_eq!(hit_text(&arena, source, &name), "Bank"); + + // Descends through the spec into its nested function's name. + let nested = hit_test(&arena, file, source.find("balance").unwrap() as u32) + .expect("covers the nested function name"); + assert_eq!(hit_text(&arena, source, &nested), "balance"); + // The spec is the outermost ancestor and the nested function's own + // definition also appears on the chain, so there are two `Def` ancestors. + assert!(matches!(nested.ancestors.first(), Some(NodeId::Def(_)))); + assert_eq!( + nested + .ancestors + .iter() + .filter(|a| matches!(a, NodeId::Def(_))) + .count(), + 2 + ); + } + + #[test] + fn hits_the_name_type_and_value_of_a_constant() { + let source = "const MAX: i32 = 100;"; + let (arena, file) = single_file(source); + + let name = hit_test(&arena, file, source.find("MAX").unwrap() as u32) + .expect("covers the constant name"); + assert_eq!(hit_text(&arena, source, &name), "MAX"); + + let ty = hit_test(&arena, file, source.find("i32").unwrap() as u32) + .expect("covers the constant type"); + assert!(matches!(ty.node, NodeId::Type(_))); + + let value = hit_test(&arena, file, source.find("100").unwrap() as u32) + .expect("covers the constant value"); + assert_eq!(hit_text(&arena, source, &value), "100"); + } + + #[test] + fn hits_the_name_and_aliased_type_of_a_type_alias() { + let source = "type Word = u64;"; + let (arena, file) = single_file(source); + + let name = hit_test(&arena, file, source.find("Word").unwrap() as u32) + .expect("covers the alias name"); + assert_eq!(hit_text(&arena, source, &name), "Word"); + + let ty = hit_test(&arena, file, source.find("u64").unwrap() as u32) + .expect("covers the aliased type"); + assert!(matches!(ty.node, NodeId::Type(_))); + assert_eq!(hit_text(&arena, source, &ty), "u64"); + } + + #[test] + fn hits_the_type_of_an_ignored_argument() { + // `_: i32` names no binding, so the type is the argument's only child. + let source = "fn f(_: i32) {}"; + let (arena, file) = single_file(source); + let hit = hit_test(&arena, file, source.find("i32").unwrap() as u32) + .expect("covers the ignored argument type"); + assert!(matches!(hit.node, NodeId::Type(_))); + assert_eq!(hit_text(&arena, source, &hit), "i32"); + } + + #[test] + fn hits_the_type_of_a_positional_type_only_argument() { + // A bare type in argument position (`i32`, no name) is a type-only + // argument; its type is the descent target. + let source = "fn f(i32) {}"; + let (arena, file) = single_file(source); + let hit = hit_test(&arena, file, source.find("i32").unwrap() as u32) + .expect("covers the positional type argument"); + assert!(matches!(hit.node, NodeId::Type(_))); + assert_eq!(hit_text(&arena, source, &hit), "i32"); + } + + #[test] + fn hits_both_sides_of_an_assignment() { + let source = "fn f() { let mut x: i32 = 0; x = 7; }"; + let (arena, file) = single_file(source); + + // The assignment's target is the last `x`, distinct from its declaration. + let left = hit_test(&arena, file, source.rfind('x').unwrap() as u32) + .expect("covers the assignment target"); + assert_eq!(hit_text(&arena, source, &left), "x"); + + let right = hit_test(&arena, file, source.find('7').unwrap() as u32) + .expect("covers the assigned value"); + assert_eq!(hit_text(&arena, source, &right), "7"); + assert!(right.ancestors.iter().any(|a| matches!(a, NodeId::Stmt(_)))); + } + + #[test] + fn hits_the_condition_of_a_conditional_loop() { + let source = "fn f() { let n: i32 = 0; loop n < 3 { break; } }"; + let (arena, file) = single_file(source); + // The condition descends to its own operand identifier. + let cond = hit_test(&arena, file, source.find("n < 3").unwrap() as u32) + .expect("covers the loop condition"); + assert_eq!(hit_text(&arena, source, &cond), "n"); + assert!(cond.ancestors.iter().any(|a| matches!(a, NodeId::Expr(_)))); + } + + #[test] + fn hits_the_body_of_an_infinite_loop() { + // An infinite loop carries no condition, so descent goes straight through + // the body block; the `break` inside it is a childless leaf statement. + let source = "fn f() { loop { break; } }"; + let (arena, file) = single_file(source); + let hit = hit_test(&arena, file, source.find("break").unwrap() as u32) + .expect("covers the break inside the loop body"); + assert!(matches!(hit.node, NodeId::Stmt(_))); + assert!(hit.ancestors.iter().any(|a| matches!(a, NodeId::Block(_)))); + } + + #[test] + fn hits_the_condition_and_then_block_of_an_if_without_else() { + let source = "fn f() { let ok: bool = true; if ok { let y: i32 = 1; } }"; + let (arena, file) = single_file(source); + + // The condition is the second `ok`, in the `if` head. + let cond = hit_test(&arena, file, source.rfind("ok").unwrap() as u32) + .expect("covers the if condition"); + assert_eq!(hit_text(&arena, source, &cond), "ok"); + + // The then-block's inner statement is reachable through the then arm. + let then_hit = hit_test(&arena, file, source.find("y:").unwrap() as u32) + .expect("covers a statement in the then-block"); + assert_eq!(hit_text(&arena, source, &then_hit), "y"); + } + + #[test] + fn hits_the_else_block_of_an_if_else() { + // `z` lives only in the else-block, so reaching it exercises the else arm. + let source = "fn f() { if true { let a: i32 = 1; } else { let z: i32 = 2; } }"; + let (arena, file) = single_file(source); + let hit = hit_test(&arena, file, source.find('z').unwrap() as u32) + .expect("covers a statement in the else-block"); + assert_eq!(hit_text(&arena, source, &hit), "z"); + assert!(hit.ancestors.iter().any(|a| matches!(a, NodeId::Block(_)))); + } + + #[test] + fn hits_a_local_type_definition_statement() { + // A local `type X = ..;` is a statement, distinct from a top-level alias. + let source = "fn f() { type Small = u8; }"; + let (arena, file) = single_file(source); + + let name = hit_test(&arena, file, source.find("Small").unwrap() as u32) + .expect("covers the local type name"); + assert_eq!(hit_text(&arena, source, &name), "Small"); + + let ty = hit_test(&arena, file, source.find("u8").unwrap() as u32) + .expect("covers the local aliased type"); + assert!(matches!(ty.node, NodeId::Type(_))); + assert_eq!(hit_text(&arena, source, &ty), "u8"); + } + + #[test] + fn hits_a_local_constant_definition_statement() { + // A local const lowers to a statement wrapping a constant definition, so + // its name is reached through statement → definition → name. + let source = "fn f() { const LIMIT: i32 = 8; }"; + let (arena, file) = single_file(source); + + let name = hit_test(&arena, file, source.find("LIMIT").unwrap() as u32) + .expect("covers the local constant name"); + assert_eq!(hit_text(&arena, source, &name), "LIMIT"); + assert!(name.ancestors.iter().any(|a| matches!(a, NodeId::Def(_)))); + + let value = hit_test(&arena, file, source.find('8').unwrap() as u32) + .expect("covers the local constant value"); + assert_eq!(hit_text(&arena, source, &value), "8"); + } + + #[test] + fn hits_the_operand_of_a_prefix_unary_expression() { + let source = "fn f() -> i32 { return -k; }"; + let (arena, file) = single_file(source); + let hit = hit_test(&arena, file, source.find('k').unwrap() as u32) + .expect("covers the negated operand"); + assert_eq!(hit_text(&arena, source, &hit), "k"); + assert!(hit.ancestors.iter().any(|a| matches!(a, NodeId::Expr(_)))); + } + + #[test] + fn hits_the_inner_expression_of_a_parenthesized_expression() { + let source = "fn f() -> i32 { return (k); }"; + let (arena, file) = single_file(source); + let hit = hit_test(&arena, file, source.find('k').unwrap() as u32) + .expect("covers the parenthesized inner expression"); + assert_eq!(hit_text(&arena, source, &hit), "k"); + } + + #[test] + fn hits_the_name_of_a_named_call_argument() { + // `g(limit: 5)`: the argument name is a descent target alongside its value. + let source = "fn f() -> i32 { return g(limit: 5); }"; + let (arena, file) = single_file(source); + + let name = hit_test(&arena, file, source.find("limit").unwrap() as u32) + .expect("covers the argument name"); + assert_eq!(hit_text(&arena, source, &name), "limit"); + assert!(matches!(name.node, NodeId::Ident(_))); + assert!(name.ancestors.iter().any(|a| matches!(a, NodeId::Expr(_)))); + + let value = hit_test(&arena, file, source.find('5').unwrap() as u32) + .expect("covers the argument value"); + assert_eq!(hit_text(&arena, source, &value), "5"); + } + + #[test] + fn hits_the_array_and_index_of_an_index_access() { + let source = "fn f(a: [i32; 4]) -> i32 { return a[2]; }"; + let (arena, file) = single_file(source); + + let arr = hit_test(&arena, file, source.find("a[2]").unwrap() as u32) + .expect("covers the indexed array"); + assert_eq!(hit_text(&arena, source, &arr), "a"); + + let index = hit_test(&arena, file, source.find("2]").unwrap() as u32) + .expect("covers the index expression"); + assert_eq!(hit_text(&arena, source, &index), "2"); + } + + #[test] + fn hits_an_element_of_an_array_literal() { + let source = "fn f() { let xs: [i32; 3] = [10, 20, 30]; }"; + let (arena, file) = single_file(source); + let elem = hit_test(&arena, file, source.find("20").unwrap() as u32) + .expect("covers an array-literal element"); + assert_eq!(hit_text(&arena, source, &elem), "20"); + assert!(elem.ancestors.iter().any(|a| matches!(a, NodeId::Expr(_)))); + } + + #[test] + fn hits_the_base_and_parameter_of_a_generic_type() { + // `Vec i32'` is a generic type: its base and each type argument are stored + // as identifiers under the type node. + let source = "fn f(v: Vec i32') {}"; + let (arena, file) = single_file(source); + + let base = hit_test(&arena, file, source.find("Vec").unwrap() as u32) + .expect("covers the generic base"); + assert_eq!(hit_text(&arena, source, &base), "Vec"); + assert!(matches!(base.node, NodeId::Ident(_))); + + let param = hit_test(&arena, file, source.find("i32").unwrap() as u32) + .expect("covers the generic type argument"); + assert_eq!(hit_text(&arena, source, ¶m), "i32"); + assert!(matches!(param.node, NodeId::Ident(_))); + } + + #[test] + fn hits_a_generic_name_used_as_an_expression() { + // A generic name in value position lowers to an `Expr::Type` wrapping the + // generic type, so descent passes through both an expression and a type + // node before reaching the argument identifier. + let source = "fn f() -> i32 { return Buf u8'; }"; + let (arena, file) = single_file(source); + let param = hit_test(&arena, file, source.find("u8").unwrap() as u32) + .expect("covers the generic argument in expression position"); + assert_eq!(hit_text(&arena, source, ¶m), "u8"); + assert!(param.ancestors.iter().any(|a| matches!(a, NodeId::Expr(_)))); + assert!(param.ancestors.iter().any(|a| matches!(a, NodeId::Type(_)))); + } + + #[test] + fn hits_the_element_and_size_of_an_array_type() { + let source = "fn f(a: [i32; 4]) {}"; + let (arena, file) = single_file(source); + + let element = hit_test(&arena, file, source.find("i32").unwrap() as u32) + .expect("covers the array element type"); + assert!(matches!(element.node, NodeId::Type(_))); + assert_eq!(hit_text(&arena, source, &element), "i32"); + + let size = hit_test(&arena, file, source.find('4').unwrap() as u32) + .expect("covers the array size expression"); + assert_eq!(hit_text(&arena, source, &size), "4"); + assert!(size.ancestors.iter().any(|a| matches!(a, NodeId::Type(_)))); + } + + #[test] + fn hits_the_return_type_of_a_function_type_annotation() { + // `fn(i32) -> i64` as a type: the arrow's return type is descendable. + let source = "fn f(cb: fn(i32) -> i64) {}"; + let (arena, file) = single_file(source); + let ret = hit_test(&arena, file, source.find("i64").unwrap() as u32) + .expect("covers the function type's return type"); + assert!(matches!(ret.node, NodeId::Type(_))); + assert_eq!(hit_text(&arena, source, &ret), "i64"); + assert!(ret.ancestors.iter().any(|a| matches!(a, NodeId::Type(_)))); + } + + #[test] + fn function_type_without_return_type_is_the_smallest_covering_node() { + // A `fn(...)` type with no `->` has a `None` return arm. The parser does + // not lower `fn`-type parameters (a pinned quirk), so the annotation has + // no descendable children and is itself the smallest covering node. + let source = "fn f(cb: fn(i32)) {}"; + let (arena, file) = single_file(source); + let hit = hit_test(&arena, file, source.find("fn(i32)").unwrap() as u32) + .expect("covers the function type annotation"); + assert!(matches!(hit.node, NodeId::Type(_))); + assert_eq!(hit_text(&arena, source, &hit), "fn(i32)"); + } + + #[test] + fn hits_the_segments_of_a_qualified_type() { + // `lib::geom::Point`: every `::`-segment qualifier and the leaf name are + // descent targets under the qualified type node. + let source = "fn f(p: lib::geom::Point) {}"; + let (arena, file) = single_file(source); + + let qualifier = hit_test(&arena, file, source.find("geom").unwrap() as u32) + .expect("covers a qualifier segment"); + assert_eq!(hit_text(&arena, source, &qualifier), "geom"); + assert!(matches!(qualifier.node, NodeId::Ident(_))); + + let leaf = hit_test(&arena, file, source.find("Point").unwrap() as u32) + .expect("covers the leaf type name"); + assert_eq!(hit_text(&arena, source, &leaf), "Point"); + assert!(matches!(leaf.node, NodeId::Ident(_))); + } +} diff --git a/ide/ide-db/src/lib.rs b/ide/ide-db/src/lib.rs index e69de29b..7d768479 100644 --- a/ide/ide-db/src/lib.rs +++ b/ide/ide-db/src/lib.rs @@ -0,0 +1,54 @@ +#![warn(clippy::pedantic)] +//! Semantic database for the Inference IDE stack. +//! +//! `ide-db` sits above `vfs` (path ↔ id ↔ content overlay) and `base-db` +//! (line-index and position PODs) and below the feature layer. It answers one +//! question — *"what does this open file mean?"* — by analyzing each open +//! document as its own project entry and caching the result. +//! +//! # What it owns +//! +//! * [`RootDatabase`] — the open-document overlay plus a memoized +//! [`FileAnalysis`] per entry file, with closure-aware invalidation so a +//! keystroke in one buffer does not re-analyze unrelated ones. +//! * [`FileAnalysis`] — the merged arena (via its [`TypedContext`]), per-file +//! parse errors, structured type diagnostics, unresolved-import problems, +//! tagged analysis findings, and per-closure-file line indexes and paths. +//! +//! # What it does not do +//! +//! It leaks no protocol types: every result is compiler data or a plain struct. +//! The feature layer above translates these into LSP responses. Import +//! resolution is **not** reimplemented here — the closure walk lives in +//! `core/inference` behind a reader seam, and `ide-db` drives it with an +//! overlay-then-disk loader, so the compiler and the IDE resolve imports +//! identically. +//! +//! [`TypedContext`]: inference_type_checker::typed_context::TypedContext + +mod analysis; +mod database; +mod hit_test; +mod loader; +mod symbols; + +pub use analysis::{AnalysisFinding, ClosureFile, FileAnalysis}; +pub use database::RootDatabase; +pub use hit_test::{NodeHit, hit_test}; +pub use symbols::file_defs; + +// Re-export the lower IDE layers' position primitives so the feature layer can +// depend on ide-db alone for everything it needs to describe a location. +pub use inference_base_db::{FilePosition, FileRange, LineCol, LineIndex, TextRange}; +pub use inference_vfs::{FileId, Vfs}; + +// Re-export the compiler types that appear in `FileAnalysis`'s public results so +// a consumer names them through ide-db alone. `ide-db` is the single façade the +// feature layer above depends on. +pub use inference::{FileParseErrors, ImportProblem}; +pub use inference_analysis::errors::{AnalysisDiagnostic, LabeledDiagnostic, Severity}; +pub use inference_ast::ids::{DefId, NodeId, SourceFileId}; +pub use inference_ast::nodes::Location; +pub use inference_parser::ParseError; +pub use inference_type_checker::TypeCheckDiagnostic; +pub use inference_type_checker::errors::TypeCheckError; diff --git a/ide/ide-db/src/loader.rs b/ide/ide-db/src/loader.rs new file mode 100644 index 00000000..dd79ad4b --- /dev/null +++ b/ide/ide-db/src/loader.rs @@ -0,0 +1,43 @@ +//! The overlay-then-disk [`FileLoader`] that drives the resilient project walk. + +use std::path::Path; + +use inference::FileLoader; +use inference_vfs::Vfs; + +/// A [`FileLoader`] that consults the editor's in-memory overlay first and falls +/// back to disk. +/// +/// This is the reader ide-db hands to `inference::load_project_resilient`, so an +/// open, unsaved buffer shadows its on-disk contents while imports the editor +/// has never opened are still read from disk. It is the IDE half of the single +/// import-resolution seam the compiler and the IDE share (the compiler passes a +/// `DiskLoader`); the two can therefore never disagree about which files a +/// program imports. +pub(crate) struct VfsLoader<'a> { + vfs: &'a Vfs, +} + +impl<'a> VfsLoader<'a> { + /// Reads through `vfs`'s overlay, falling back to disk for files the overlay + /// does not hold. + #[must_use = "a loader does nothing until it is handed to the closure walk"] + pub(crate) fn new(vfs: &'a Vfs) -> Self { + Self { vfs } + } +} + +impl FileLoader for VfsLoader<'_> { + fn exists(&self, path: &Path) -> bool { + // An open buffer counts as existing even before it is written to disk; + // otherwise fall back to the real filesystem. + self.vfs.contents_of_path(path).is_some() || path.is_file() + } + + fn read(&self, path: &Path) -> std::io::Result { + match self.vfs.contents_of_path(path) { + Some(text) => Ok(text.to_string()), + None => std::fs::read_to_string(path), + } + } +} diff --git a/ide/ide-db/src/symbols.rs b/ide/ide-db/src/symbols.rs new file mode 100644 index 00000000..0c0c0d50 --- /dev/null +++ b/ide/ide-db/src/symbols.rs @@ -0,0 +1,117 @@ +//! Recursive definition walk over a single source file. + +use inference_ast::arena::AstArena; +use inference_ast::ids::{DefId, SourceFileId}; +use inference_ast::nodes::Def; + +/// Collects every definition in `file` in pre-order: each top-level definition, +/// then its nested definitions (a struct's methods, a spec's inner defs), +/// recursively. +/// +/// `arena.function_def_ids()` alone misses struct methods and spec-nested defs, +/// so document symbols and by-name lookup that must see the full hierarchy walk +/// through here instead. A definition always precedes its children, so the flat +/// list still carries the nesting order later phases rebuild a tree from. +/// +/// The walk is scoped to `file`'s own def list. It never touches another file, +/// which matters in the merged multi-file arena where a bare arena-wide scan +/// would mix files together. +#[must_use = "the collected definitions are the reason to call this"] +pub fn file_defs(arena: &AstArena, file: SourceFileId) -> Vec { + let mut defs = Vec::new(); + for &def in &arena[file].defs { + collect_def(arena, def, &mut defs); + } + defs +} + +/// Appends `def` and then, depth-first, every definition nested inside it. +fn collect_def(arena: &AstArena, def: DefId, out: &mut Vec) { + out.push(def); + match &arena[def].kind { + Def::Struct { methods, .. } => { + for &method in methods { + collect_def(arena, method, out); + } + } + Def::Spec { defs, .. } => { + for &nested in defs { + collect_def(arena, nested, out); + } + } + Def::Function { .. } + | Def::ExternFunction { .. } + | Def::Enum { .. } + | Def::Constant { .. } + | Def::TypeAlias { .. } => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use inference_parser::parse; + + /// Parses a single-file program and returns its arena plus the sole file id. + fn single_file(source: &str) -> (AstArena, SourceFileId) { + let arena = parse(source).arena; + let file = arena.source_file_ids().next().expect("one source file"); + (arena, file) + } + + #[test] + fn collects_top_level_functions() { + let (arena, file) = single_file("fn a() {} fn b() {}"); + let names: Vec<&str> = file_defs(&arena, file) + .iter() + .map(|&d| arena.def_name(d)) + .collect(); + assert_eq!(names, vec!["a", "b"]); + } + + #[test] + fn recurses_into_struct_methods() { + let source = "struct Point { x: i32; fn get_x() -> i32 { return self.x; } fn set() {} }"; + let (arena, file) = single_file(source); + let names: Vec<&str> = file_defs(&arena, file) + .iter() + .map(|&d| arena.def_name(d)) + .collect(); + // The struct precedes its methods (pre-order). + assert_eq!(names, vec!["Point", "get_x", "set"]); + } + + #[test] + fn recurses_into_spec_defs() { + let source = "spec S { fn prop() {} fn other() {} }"; + let (arena, file) = single_file(source); + let names: Vec<&str> = file_defs(&arena, file) + .iter() + .map(|&d| arena.def_name(d)) + .collect(); + assert_eq!(names, vec!["S", "prop", "other"]); + } + + #[test] + fn recurses_into_spec_nested_struct_methods() { + // A struct inside a spec: the walk must reach the struct's methods too. + let source = "spec S { struct Inner { v: i32; fn get() -> i32 { return self.v; } } }"; + let (arena, file) = single_file(source); + let names: Vec<&str> = file_defs(&arena, file) + .iter() + .map(|&d| arena.def_name(d)) + .collect(); + assert_eq!(names, vec!["S", "Inner", "get"]); + } + + #[test] + fn collects_mixed_top_level_kinds() { + let source = "const N: i32 = 1; enum E { A, B } struct P { x: i32; } fn f() {}"; + let (arena, file) = single_file(source); + let names: Vec<&str> = file_defs(&arena, file) + .iter() + .map(|&d| arena.def_name(d)) + .collect(); + assert_eq!(names, vec!["N", "E", "P", "f"]); + } +} diff --git a/ide/ide-db/tests/database.rs b/ide/ide-db/tests/database.rs new file mode 100644 index 00000000..4657fde1 --- /dev/null +++ b/ide/ide-db/tests/database.rs @@ -0,0 +1,613 @@ +//! Integration tests for the `RootDatabase` → `FileAnalysis` pipeline: closure +//! loading through the overlay-then-disk loader, closure-aware invalidation, and +//! the partial results a broken program still yields. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use inference_ide_db::{NodeId, RootDatabase, Severity}; + +/// A throwaway source tree under the system temp dir, removed on drop. +struct TempTree { + root: PathBuf, +} + +impl TempTree { + fn new(tag: &str) -> Self { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let unique = COUNTER.fetch_add(1, Ordering::Relaxed); + let root = std::env::temp_dir().join(format!( + "inference-ide-db-{tag}-{}-{nanos}-{unique}", + std::process::id() + )); + std::fs::create_dir_all(&root).expect("create temp tree root"); + TempTree { root } + } + + /// Writes `contents` to `/`, creating parent directories, and + /// returns the absolute path. + fn write(&self, relative: &str, contents: &str) -> PathBuf { + let dest = self.root.join(relative); + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent).expect("create source parent dir"); + } + std::fs::write(&dest, contents).expect("write source file"); + dest + } + + /// The absolute path a relative source name would occupy, without writing it. + fn path(&self, relative: &str) -> PathBuf { + self.root.join(relative) + } +} + +impl Drop for TempTree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.root); + } +} + +/// The definition names of the closure file named by `module_path`, in order. +fn def_names(db: &mut RootDatabase, entry: &Path, module_path: &[String]) -> Vec { + let analysis = db.analysis(entry); + let arena = analysis.arena(); + arena + .source_files() + .find(|sf| sf.module_path == module_path) + .map(|sf| { + sf.defs + .iter() + .map(|&d| arena.def_name(d).to_string()) + .collect() + }) + .unwrap_or_default() +} + +// Closure loading + +#[test] +fn overlay_text_beats_disk_contents() { + let tree = TempTree::new("overlay-wins"); + let entry = tree.write("main.inf", "pub fn disk_fn() {}"); + let mut db = RootDatabase::default(); + + // Open the same file with different in-memory text; analysis must use it. + db.open_document(&entry, "pub fn overlay_fn() {}"); + + assert_eq!(def_names(&mut db, &entry, &[]), vec!["overlay_fn"]); +} + +#[test] +fn import_is_resolved_from_disk() { + let tree = TempTree::new("import-disk"); + let entry = tree.write( + "main.inf", + "use lib::helper;\npub fn main() -> i32 { return 0; }", + ); + let helper = tree.write("lib/helper.inf", "pub fn help() -> i32 { return 7; }"); + let mut db = RootDatabase::default(); + + let lib_mod = vec!["lib".to_string(), "helper".to_string()]; + let analysis = db.analysis(&entry); + // The imported file is in the closure, with its path recovered. + let file = analysis.file(&lib_mod).expect("imported file in closure"); + assert_eq!(file.path(), helper.as_path()); + assert!(analysis.source_file_id(&lib_mod).is_some()); +} + +#[test] +fn closure_maps_each_imported_file_to_its_source_line_index_and_a_hittable_arena() { + // Cross-file features need the target file's own source text, line index, and + // arena file id — a goto-def into an import must resolve against the imported + // file, not the one the request came from. This checks the full round-trip. + let tree = TempTree::new("cross-file-map"); + let entry = tree.write( + "main.inf", + "use lib::helper;\npub fn main() -> i32 { return 0; }", + ); + // Two lines so the line index has real work to do. + let helper_src = "pub fn help() -> i32 {\n return 7;\n}"; + tree.write("lib/helper.inf", helper_src); + let mut db = RootDatabase::default(); + + let lib_mod = vec!["lib".to_string(), "helper".to_string()]; + let analysis = db.analysis(&entry); + let file = analysis.file(&lib_mod).expect("imported file in closure"); + + // The imported file's own source text is retained verbatim. + assert_eq!(file.source(), helper_src); + + // Its line index converts an offset within the imported file correctly: the + // `return` on line 1 (0-based) starts after the first newline. + let return_offset = helper_src.find("return").unwrap() as u32; + let position = file.line_index().line_col(return_offset); + assert_eq!(position.line, 1); + assert_eq!(position.character, 4); + + // Hit-testing the imported file's own arena id finds a node inside it, using + // the imported file's per-file-local offset (not the entry's). + let lib_file = analysis + .source_file_id(&lib_mod) + .expect("imported file has an arena id"); + let help_offset = helper_src.find("help").unwrap() as u32; + let hit = analysis + .hit_test(lib_file, help_offset) + .expect("a node covers `help` in the imported file"); + if let NodeId::Ident(ident) = hit.node { + assert_eq!(analysis.arena().ident_name(ident), "help"); + } else { + panic!("expected the `help` identifier, got {:?}", hit.node); + } +} + +#[test] +fn typed_context_answers_for_a_node_in_an_imported_file() { + // Cross-file identity has historically hidden bugs (#63): confirm the merged + // type context answers `get_node_typeinfo` for an expression that lives in an + // imported file, addressed by that file's own per-file-local offset. + let tree = TempTree::new("cross-file-typeinfo"); + let entry = tree.write( + "main.inf", + "use lib::helper;\npub fn main() -> i32 { return 0; }", + ); + let helper_src = "pub fn help() -> i32 { return 7; }"; + tree.write("lib/helper.inf", helper_src); + let mut db = RootDatabase::default(); + + let lib_mod = vec!["lib".to_string(), "helper".to_string()]; + let analysis = db.analysis(&entry); + let lib_file = analysis + .source_file_id(&lib_mod) + .expect("imported file has an arena id"); + + // The `7` literal in the imported file is typed against its `i32` return. + let literal_offset = helper_src.find('7').unwrap() as u32; + let hit = analysis + .hit_test(lib_file, literal_offset) + .expect("a node covers the literal in the imported file"); + assert!( + analysis + .typed_context() + .get_node_typeinfo(hit.node) + .is_some(), + "the type context must answer for the imported file's literal" + ); +} + +#[test] +fn missing_import_is_recorded_with_location_and_module_path() { + let tree = TempTree::new("missing-import"); + // A header line pushes the `use` directive off byte 0 and onto line 2, so the + // recorded location is distinguishable from a dropped `Location::default()` + // (which is all zeros). A byte-0 fixture cannot tell the two apart. + let src = "// header\nuse nope;\npub fn main() {}"; + let entry = tree.write("main.inf", src); + let mut db = RootDatabase::default(); + + let analysis = db.analysis(&entry); + assert_eq!(analysis.import_problems().len(), 1); + let problem = &analysis.import_problems()[0]; + assert_eq!(problem.referenced_as, "nope"); + assert!(problem.importing_module_path.is_empty()); + + // The location spans exactly the `use nope;` directive, at a nonzero offset on + // the second line — not the origin a lost location would default to. + let use_start = src + .find("use nope;") + .expect("fixture contains the directive") as u32; + assert!(use_start > 0, "the directive must not start at byte 0"); + assert_eq!(problem.location.offset_start, use_start); + assert_eq!( + problem.location.offset_end, + use_start + "use nope;".len() as u32 + ); + assert_eq!(problem.location.start_line, 2); + assert_eq!(problem.location.start_column, 1); +} + +#[test] +fn broken_imported_file_yields_labeled_parse_errors_and_entry_still_analyzed() { + let tree = TempTree::new("broken-import"); + let entry = tree.write( + "main.inf", + "use broken;\npub fn main() -> i32 { return 0; }", + ); + tree.write("broken.inf", "pub fn oops( { return 1; }"); + let mut db = RootDatabase::default(); + + let analysis = db.analysis(&entry); + // The broken file's syntax errors are collected, labeled with its module. + assert_eq!(analysis.parse_errors().len(), 1); + assert_eq!( + analysis.parse_errors()[0].module_path, + vec!["broken".to_string()] + ); + assert!(!analysis.parse_errors()[0].errors.is_empty()); + + // The entry is still fully analyzed. + assert_eq!(def_names(&mut db, &entry, &[]), vec!["main"]); +} + +#[test] +fn use_root_handle_is_not_a_missing_import() { + let tree = TempTree::new("root-handle"); + let entry = tree.write("main.inf", "use root;\npub fn main() {}"); + let mut db = RootDatabase::default(); + + let analysis = db.analysis(&entry); + assert!( + analysis.import_problems().is_empty(), + "`use root;` names the entry, not a file to load" + ); +} + +#[test] +fn self_import_of_entry_is_deduplicated() { + let tree = TempTree::new("self-import"); + let entry = tree.write( + "main.inf", + "use lib::helper;\npub fn main() -> i32 { return 0; }", + ); + tree.write("lib/helper.inf", "use main;\npub fn help() {}"); + let mut db = RootDatabase::default(); + + let analysis = db.analysis(&entry); + let entry_files = analysis + .arena() + .source_files() + .filter(|sf| sf.module_path.is_empty()) + .count(); + assert_eq!(entry_files, 1, "the entry is analyzed exactly once"); + assert!(analysis.import_problems().is_empty()); +} + +#[test] +fn mutually_importing_files_terminate() { + let tree = TempTree::new("mutual"); + let entry = tree.write("main.inf", "use a;\npub fn main() {}"); + tree.write("a.inf", "use b;\npub fn fa() {}"); + tree.write("b.inf", "use a;\npub fn fb() {}"); + let mut db = RootDatabase::default(); + + let analysis = db.analysis(&entry); + let modules: Vec> = analysis + .arena() + .source_files() + .map(|sf| sf.module_path.clone()) + .collect(); + assert_eq!( + modules, + vec![ + Vec::::new(), + vec!["a".to_string()], + vec!["b".to_string()], + ], + ); + assert!(analysis.import_problems().is_empty()); +} + +// Closure-aware invalidation + +#[test] +fn change_to_imported_file_invalidates_entry_analysis() { + let tree = TempTree::new("invalidate-dep"); + let entry = tree.write( + "main.inf", + "use lib::helper;\npub fn main() -> i32 { return 0; }", + ); + let helper = tree.write("lib/helper.inf", "pub fn help() -> i32 { return 1; }"); + let mut db = RootDatabase::default(); + db.open_document( + &entry, + "use lib::helper;\npub fn main() -> i32 { return 0; }", + ); + + let first = db.analysis(&entry).generation(); + // Changing a file in the closure must drop the entry's memoized analysis. + db.change_document(&helper, "pub fn help() -> i32 { return 2; }"); + let second = db.analysis(&entry).generation(); + + assert!( + second > first, + "changing an imported file must force a recompute ({first} -> {second})" + ); +} + +#[test] +fn change_to_unrelated_file_does_not_invalidate_entry_analysis() { + let tree = TempTree::new("invalidate-unrelated"); + let entry = tree.write("main.inf", "pub fn main() -> i32 { return 0; }"); + let unrelated = tree.path("other.inf"); + let mut db = RootDatabase::default(); + db.open_document(&entry, "pub fn main() -> i32 { return 0; }"); + + let first = db.analysis(&entry).generation(); + // A file outside the entry's closure must not disturb its memoized analysis. + db.change_document(&unrelated, "pub fn other() {}"); + let second = db.analysis(&entry).generation(); + + assert_eq!( + first, second, + "an unrelated change must not recompute the entry ({first} -> {second})" + ); +} + +#[test] +fn opening_a_previously_unseen_file_reanalyzes_a_missing_import() { + let tree = TempTree::new("resolve-missing"); + let entry = tree.write("main.inf", "use future;\npub fn main() {}"); + let mut db = RootDatabase::default(); + db.open_document(&entry, "use future;\npub fn main() {}"); + + let first = db.analysis(&entry); + let first_gen = first.generation(); + assert_eq!(first.import_problems().len(), 1, "future.inf is missing"); + + // Open the previously-unseen file the import was looking for. + let future = tree.path("future.inf"); + db.open_document(&future, "pub fn soon() {}"); + + let second = db.analysis(&entry); + assert!( + second.generation() > first_gen, + "a newly-opened file must re-analyze an entry with a missing import" + ); + assert!( + second.import_problems().is_empty(), + "the import now resolves to the opened overlay" + ); +} + +#[test] +fn reopening_a_closed_file_reresolves_a_missing_import() { + let tree = TempTree::new("reopen-missing"); + // `main.inf` imports `lib`, which exists only as an editor buffer, never on + // disk. Interning survives `didClose`, so a widening keyed on "path never + // interned" would fire on the first open but not the reopen, leaving the + // import stale until the entry itself is edited. + let src = "use lib;\npub fn main() -> i32 { return 0; }"; + let entry = tree.write("main.inf", src); + let lib = tree.path("lib.inf"); + let mut db = RootDatabase::default(); + db.open_document(&entry, src); + + assert_eq!( + db.analysis(&entry).import_problems().len(), + 1, + "lib is missing before it is opened" + ); + + let lib_src = "pub fn helper() -> i32 { return 7; }"; + db.open_document(&lib, lib_src); + assert!( + db.analysis(&entry).import_problems().is_empty(), + "the first open of lib resolves the import" + ); + + db.close_document(&lib); + assert_eq!( + db.analysis(&entry).import_problems().len(), + 1, + "closing lib removes its overlay, so the import is missing again" + ); + + let before_reopen = db.analysis(&entry).generation(); + // Reopening lib with the same content must re-resolve the import, not serve + // the stale analysis computed while it was closed. + db.open_document(&lib, lib_src); + let reopened = db.analysis(&entry); + assert!( + reopened.import_problems().is_empty(), + "reopening lib must re-resolve the import" + ); + assert!( + reopened.generation() > before_reopen, + "reopening lib must recompute the entry ({before_reopen} -> {})", + reopened.generation() + ); +} + +#[test] +fn analysis_of_an_unreadable_entry_recovers_after_didopen() { + let tree = TempTree::new("unreadable-entry"); + // The entry is never on disk. An early, out-of-order request (a stray hover, + // say) races ahead of `didOpen` and memoizes an analysis of the unreadable + // entry — an empty arena with no missing-import record. Unless the entry is + // part of its own closure, no later event can ever evict that poisoned result. + let entry = tree.path("ghost.inf"); + let mut db = RootDatabase::default(); + + let (first_gen, first_files) = { + let first = db.analysis(&entry); + (first.generation(), first.arena().source_files().count()) + }; + assert_eq!(first_files, 0, "an unreadable entry yields an empty arena"); + + // `didOpen` now supplies the content; the poisoned analysis must recompute. + let source = "pub fn f() -> i32 { return broken; }"; + db.open_document(&entry, source); + let (recovered_gen, recovered_files, has_type_errors) = { + let recovered = db.analysis(&entry); + ( + recovered.generation(), + recovered.arena().source_files().count(), + !recovered.type_errors().is_empty(), + ) + }; + assert!( + recovered_gen > first_gen, + "didOpen of the entry must recompute its poisoned analysis" + ); + assert_eq!(recovered_files, 1, "the opened overlay is now analyzed"); + assert!( + has_type_errors, + "the undeclared variable must surface once analysis actually runs" + ); + + // A subsequent `didChange` likewise recomputes — the entry stays evictable. + let before_change = db.analysis(&entry).generation(); + db.change_document(&entry, "pub fn f() -> i32 { return 0; }"); + assert!( + db.analysis(&entry).generation() > before_change, + "didChange of the entry must recompute" + ); +} + +// Partial semantics: a broken program still answers + +#[test] +fn type_error_still_leaves_a_queryable_typed_context() { + let tree = TempTree::new("type-error"); + // `bad` returns bool where i32 is declared; `ok` is well-typed. + let source = "fn ok() -> i32 { return 1; } fn bad() -> i32 { return true; }"; + let entry = tree.write("main.inf", source); + let mut db = RootDatabase::default(); + db.open_document(&entry, source); + + let analysis = db.analysis(&entry); + assert!( + !analysis.type_errors().is_empty(), + "the bool/i32 mismatch must surface as a type diagnostic" + ); + + // The typed context still answers for the well-typed part: the `1` literal. + let entry_file = analysis.source_file_id(&[]).expect("entry file present"); + let offset = source.find("return 1").unwrap() as u32 + "return ".len() as u32; + let hit = analysis + .hit_test(entry_file, offset) + .expect("a node covers the literal `1`"); + assert!(matches!(hit.node, NodeId::Expr(_))); + assert!( + analysis + .typed_context() + .get_node_typeinfo(hit.node) + .is_some(), + "get_node_typeinfo must answer for the well-typed literal" + ); +} + +#[test] +fn parse_error_in_entry_still_runs_type_checking() { + let tree = TempTree::new("parse-error"); + // A missing `)` — the resilient parser recovers and the checker still runs. + let source = "fn main( { return 0; }"; + let entry = tree.write("main.inf", source); + let mut db = RootDatabase::default(); + db.open_document(&entry, source); + + let analysis = db.analysis(&entry); + // The entry's own syntax error is collected under the empty module path. + assert!( + analysis + .parse_errors() + .iter() + .any(|fe| fe.module_path.is_empty() && !fe.errors.is_empty()), + "the entry's parse error must be recorded" + ); + + // Type checking ran on the recovered body, not merely the parser: the + // recovered `fn main` has no return type (Unit) yet `return 0;` yields i32, so + // the checker must report that mismatch. Querying the always-present typed + // context proves nothing — this must observe a fact that only running the + // checker produces, or the test stays green even if checking were skipped on + // every file with a syntax error (i.e. every file mid-edit). + assert!( + !analysis.type_errors().is_empty(), + "the recovered `fn main` must be type-checked; `return 0` in a unit fn is a mismatch" + ); + + // The checker also populated node types for the recovered body: the `0` + // literal has an inferred type, which a bare `TypedContext::new` would lack. + let entry_file = analysis.source_file_id(&[]).expect("entry file present"); + let literal_offset = source + .find("return 0") + .expect("recovered body has `return 0`") as u32 + + "return ".len() as u32; + let hit = analysis + .hit_test(entry_file, literal_offset) + .expect("a node covers the recovered literal `0`"); + assert!( + analysis + .typed_context() + .get_node_typeinfo(hit.node) + .is_some(), + "type checking must have inferred a type for the recovered body's literal" + ); +} + +#[test] +fn analysis_of_trivially_broken_source_does_not_panic() { + // Each source lowers to two or more error-placeholder functions on the + // resilient parse path, so the whole-program call graph shared by A035/A036 + // sees duplicate (non-injective) `FnKey`s. Building it must tolerate that + // deterministically rather than aborting the analysis (in debug builds, the + // whole LSP process). Reaching `findings()` proves every rule ran. + for (tag, source) in [ + ("stray-forall", "forall { }"), + ("two-semicolons", ";;"), + ("two-idents", "foo bar"), + ( + "valid-then-two-stray", + "fn f() -> i32 { return 1; }\nforall { }\nexists { }", + ), + ] { + let tree = TempTree::new(tag); + let entry = tree.write("main.inf", source); + let mut db = RootDatabase::default(); + db.open_document(&entry, source); + + let analysis = db.analysis(&entry); + let _ = analysis.findings(); + assert!( + analysis + .parse_errors() + .iter() + .any(|fe| !fe.errors.is_empty()), + "{tag}: the broken source must still surface parse errors" + ); + } +} + +// Analysis findings are tagged with rule id and severity + +#[test] +fn analysis_findings_are_tagged_with_rule_id_and_severity() { + let tree = TempTree::new("findings"); + // `break` outside a loop is analysis rule A001 (an error). + let source = "pub fn main() { break; }"; + let entry = tree.write("main.inf", source); + let mut db = RootDatabase::default(); + db.open_document(&entry, source); + + let analysis = db.analysis(&entry); + let break_finding = analysis + .findings() + .iter() + .find(|f| f.rule_id == "A001") + .expect("break outside loop must be reported as A001"); + assert_eq!(break_finding.severity, Severity::Error); +} + +// Def walk over the public API + +#[test] +fn file_defs_covers_struct_methods_spec_fns_and_constants() { + let tree = TempTree::new("def-walk"); + let source = "const N: i32 = 1; struct P { x: i32; fn get() -> i32 { return self.x; } } spec S { fn prop() {} }"; + let entry = tree.write("main.inf", source); + let mut db = RootDatabase::default(); + db.open_document(&entry, source); + + let analysis = db.analysis(&entry); + let entry_file = analysis.source_file_id(&[]).expect("entry file present"); + let names: Vec<&str> = analysis + .file_defs(entry_file) + .iter() + .map(|&d| analysis.arena().def_name(d)) + .collect(); + assert_eq!(names, vec!["N", "P", "get", "S", "prop"]); +} diff --git a/ide/ide/Cargo.toml b/ide/ide/Cargo.toml index ab4a9c69..e8fb99c5 100644 --- a/ide/ide/Cargo.toml +++ b/ide/ide/Cargo.toml @@ -6,3 +6,9 @@ license = { workspace = true } homepage = { workspace = true } repository = { workspace = true } description = "Inference IDE support" + +[dependencies] +inference-ide-db.workspace = true +inference-ast.workspace = true +inference-type-checker.workspace = true +rustc-hash.workspace = true diff --git a/ide/ide/README.md b/ide/ide/README.md index c040fe30..19874f57 100644 --- a/ide/ide/README.md +++ b/ide/ide/README.md @@ -1,60 +1,180 @@ -# inference-ide - IDE API +# inference-ide -High-level IDE API for Inference language support. +The feature layer of the Inference IDE stack: plain-old-data answers to the +questions an editor asks about a document. [`AnalysisHost`] owns the +open-document state (delegating to `ide-db`'s `RootDatabase`); [`Analysis`] +borrows it to answer feature queries — diagnostics, document symbols, hover, +goto-definition, completions, and inlay hints. -## Status +## Where It Sits -Skeleton implementation. See the LSP plan for the full feature roadmap. - -## Purpose - -Public API boundary for IDE features. Returns plain-old-data (POD) types only - no compiler internals exposed. +``` +apps/lsp + | +ide/ide -----re-exports position PODs from-----> ide/ide-db + | +ide/ide-db -> ide/base-db -> ide/vfs +``` -## Planned Types +Every result this crate returns is a plain struct in editor terminology +(`Diagnostic`, `DocumentSymbol`, `Hover`, `NavigationTarget`, `CompletionItem`, +`InlayHint`) — **no compiler type crosses this boundary**. The protocol layer +above (`apps/lsp`) maps these straight onto LSP responses without needing to +know anything about `inference_ast`, `inference_type_checker`, or +`inference_analysis`. + +## Coordinates + +Positions in and out of this crate are **byte offsets** into a document's +current text, and ranges are byte ranges — not LSP line/character. The +protocol layer converts them with the [`LineIndex`] this crate re-exports from +`ide-db`. An open document is addressed by its path; the entry file's own +module path is the empty slice, which is how a query reaches the document it +was asked about rather than one of its imports. + +## Design: Single Document, Single Thread + +Each open file is analyzed as its own project entry (its import closure +resolved through the overlay-then-disk loader in `ide-db`), and the resulting +analysis answers every query for that document — including goto-definition +into an imported file, whose `NavigationTarget` carries that file's real path +and ranges in that file's own coordinates (`closure_line_index` fetches the +right `LineIndex` for it without re-analyzing the target as its own entry). + +A query borrows the database with `&mut self` because the analysis is computed +lazily and memoized on first use. This is not an accident of implementation — +it is exactly the access pattern the LSP main loop needs: it is +single-threaded by design (see `apps/lsp`), so there is never a second caller +to conflict with the mutable borrow. + +## Feature-Per-Module Layout + +| Module | Feature | Depends on | +|---|---|---| +| `diagnostics.rs` | Merged, sorted `Diagnostic`s: syntax, import, type, and analysis-rule findings | `FileAnalysis` | +| `document_symbols.rs` | The definition hierarchy (functions, structs with fields/methods, enums with variants, specs) | `FileAnalysis`, `syntax.rs` | +| `hover.rs` | Type and documentation for the position under the cursor | `type_render.rs`, `nondet_docs.rs`, `syntax.rs` | +| `goto_definition.rs` | Resolves an identifier to its declaration, possibly in another file | `syntax.rs` | +| `completions.rs` | Keyword / local / top-level-def / imported-module suggestions, or struct-member-only after `.` | `type_render.rs`, `syntax.rs` | +| `inlay_hints.rs` | Non-det block and uzumaki (`@`) annotations | `nondet_docs.rs`, `syntax.rs` | +| `nondet_docs.rs` | The verbatim hover/inlay text for `forall`/`exists`/`unique`/`assume`/`@` | — | +| `syntax.rs` | Shared per-file AST navigation: child enumeration, name lookup, signature extraction | `ide-db` (`NodeHit`, `file_defs`) | +| `type_render.rs` | Renders a checked `TypeInfo` as a source-like string for hovers and completions | `inference-type-checker` | + +`lib.rs` wires these together: `AnalysisHost` owns the `RootDatabase`; +`Analysis<'_>` is a thin borrowing façade whose methods each resolve the +document's `FileAnalysis` and delegate to the matching module. + +## Features + +### Diagnostics + +`Analysis::diagnostics(path)` merges four sources into one sorted list, each +tagged with a `code`: `"syntax"` (resilient parser errors), `"import"` +(unresolved or broken imports — a broken *imported* file surfaces as one +summary diagnostic anchored on the `use` directive that pulls it in, not as its +own per-file-local errors), `"type"` (structured type-check diagnostics via +`inference::type_check_with_diagnostics`), and an analysis rule id (`"A001"` +through `"A041"`, see `core/analysis`). Only the *entry* file's own diagnostics +are returned — an imported file's offsets are local to that file and would be +misplaced if surfaced directly. + +### Hover + +`Analysis::hover(path, offset)` dispatches on what covers the position: + +- A non-det block keyword (`forall` / `exists` / `unique` / `assume`) returns + its **verification meaning** — what proof obligation the block introduces — + authored once in `nondet_docs.rs` and served verbatim, so the wording never + drifts between the hover and the inlay hint. For example, hovering `forall` + explains that it fans out one computation path per value of every `@` inside + it and requires *all* paths to succeed, and that it lowers to the `BI_forall` + quantifier constructor in the generated Rocq. +- A `@` (uzumaki) expression gets its own explanation: that it is not a random + pick but a value standing for *every* value of its type at once, quantified + by the enclosing non-det block. +- An identifier resolves by its syntactic role: a definition's own name shows + its one-line signature; a parameter or field shows its type; a call callee + (free function, method, or `::`-qualified) shows the target's signature, + resolved cross-file when the target is defined in an imported module; a + struct-literal name or field shows the struct's signature or the field's + type. +- A type annotation or a typed expression falls back to rendering its checked + `TypeInfo` (`type_render.rs`). + +### Goto Definition + +`Analysis::goto_definition(path, offset)` resolves the identifier at a +position to its declaration, wherever it lives. A `NavigationTarget` always +carries the target file's own absolute path and byte ranges in that file's own +coordinates, because offsets are per-file-local in the merged arena — a +cross-file jump into an imported struct's field, an imported constant, or a +`lib::helper()` call all resolve correctly, using the type checker's recorded +call target rather than re-deriving it from source text. + +### Document Symbols + +`Analysis::document_symbols(path)` builds the outline of the entry file: every +top-level definition, with struct fields and methods, enum variants, and +spec-nested definitions as children. Each symbol carries both a whole-`range` +(for "reveal declaration") and a narrower `selection_range` spanning just the +name (for "highlight this identifier"). + +### Completions + +`Analysis::completions(path, offset)` distinguishes two contexts. Right after +a `.` whose receiver has a known struct type, only that struct's fields and +*instance* methods (those taking `self`) are offered — an associated function +reachable only as `Type::make()` is excluded. Everywhere else, the suggestions +are every reserved keyword (kept in sync with the parser's keyword table), +locals in scope at the cursor (params, plus `let` bindings declared strictly +before it — Inference forbids shadowing, so this is unambiguous), the +document's own top-level definitions, and the modules it imports together with +their `pub` top-level definitions. + +### Inlay Hints + +`Analysis::inlay_hints(path, range)` places a short annotation right after +every non-det block's opening keyword (e.g. `▸ every path must succeed` after +`forall`) and right after every `@`, with the uzumaki's concrete declared type +appended when known (`▸ ranges over every value of its type (i32)`). An +optional `range` clips the result to an editor's visible viewport. + +## Usage ```rust -/// Mutable host for applying changes -pub struct AnalysisHost { - db: RootDatabase, -} - -/// Immutable snapshot for queries (thread-safe) -pub struct Analysis { - db: Arc, -} - -impl Analysis { - /// Get diagnostics for a file - pub fn diagnostics(&self, file_id: FileId) -> Vec; +use std::path::PathBuf; +use inference_ide::AnalysisHost; - /// Go to definition at position - pub fn goto_definition(&self, pos: FilePosition) -> Option; +let mut host = AnalysisHost::default(); +let path = PathBuf::from("/project/src/main.inf"); +host.open_document(&path, "fn add(a: i32, b: i32) -> i32 { return a + b; }"); - /// Get hover information at position - pub fn hover(&self, pos: FilePosition) -> Option; +let mut analysis = host.analysis(); +assert!(analysis.diagnostics(&path).is_empty()); +assert_eq!(analysis.document_symbols(&path).len(), 1); - /// Get document symbols - pub fn document_symbols(&self, file_id: FileId) -> Vec; - - /// Get completions at position - pub fn completions(&self, pos: FilePosition) -> Vec; -} +let offset = "fn add".len() as u32 - 3; // the `add` identifier +assert!(analysis.hover(&path, offset).is_some()); ``` -## Design Principles - -1. **POD Return Types** - No `Rc`, `Arc`, or internal compiler types in public API -2. **Snapshot Queries** - `Analysis` is immutable; changes go through `AnalysisHost` -3. **Editor Terminology** - Uses offsets, ranges, positions (not AST node IDs) +## Testing -## Dependencies +Each feature module carries its own unit tests, built on the shared +`test_utils.rs` helpers (`single`, `with_lib`, and byte-offset finders `at` / +`after` / `nth` that read the offset out of the source text rather than +hardcoding it). `lib.rs` additionally tests the `AnalysisHost` lifecycle: +open → query, change → reanalyze, close → still usable, and +`closure_line_index` serving an imported file's line index without +re-analyzing it as its own entry. -- `inference-ide-db` - Semantic database -- `inference-base-db` - Position utilities -- `inference-vfs` - File identity +``` +cargo test -p inference-ide +``` -## Building +## Related Resources -```bash -cargo build -p inference-ide -``` +- [`ide/ide-db`](../ide-db/README.md) — `RootDatabase`, `FileAnalysis`, `hit_test`, `file_defs` +- [`ide/base-db`](../base-db/README.md) — `LineIndex`, `TextRange`, re-exported here +- [`apps/lsp`](../../apps/lsp/README.md) — the protocol layer that maps this crate's PODs onto LSP +- [`core/type-checker`](../../core/type-checker/README.md) — `TypeInfo`, rendered by `type_render.rs` diff --git a/ide/ide/src/completions.rs b/ide/ide/src/completions.rs new file mode 100644 index 00000000..697538aa --- /dev/null +++ b/ide/ide/src/completions.rs @@ -0,0 +1,458 @@ +//! Completion suggestions for a position in a document. +//! +//! Two contexts are distinguished. Right after a `.` whose receiver has a known +//! struct type, only that struct's fields and instance methods are offered. +//! Everywhere else the suggestions are keywords, the locals in scope, the +//! document's own top-level definitions, and the modules it imports. + +use inference_ast::arena::AstArena; +use inference_ast::ids::{DefId, ExprId, NodeId, SourceFileId}; +use inference_ast::nodes::{ArgKind, Def, Stmt}; +use inference_ide_db::{FileAnalysis, NodeHit}; +use inference_type_checker::type_info::{TypeInfo, TypeInfoKind}; +use rustc_hash::FxHashSet; + +use crate::syntax::{ + def_signature, enclosing_function, find_def_by_name, imported_module_paths, in_scope_locals, + method_has_self, +}; +use crate::type_render::render_type; + +/// The category of a completion, used by the editor to pick an icon. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CompletionItemKind { + Keyword, + Function, + Struct, + Enum, + Variable, + Field, + Method, + Constant, + Module, + Snippet, +} + +/// One completion suggestion. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CompletionItem { + pub label: String, + pub kind: CompletionItemKind, + pub detail: Option, +} + +/// Every reserved word the lexer recognizes, offered in keyword position. +/// +/// This mirrors `inference_parser`'s `SyntaxKind::from_keyword`; keeping the full +/// set (including the primitive type names) means the completion list never +/// drifts from what the parser actually treats as a keyword. +const KEYWORDS: &[&str] = &[ + "fn", "let", "mut", "spec", "struct", "enum", "const", "type", "external", "return", "loop", + "if", "else", "assert", "break", "use", "from", "self", "pub", "assume", "forall", "exists", + "unique", "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "bool", "true", "false", +]; + +/// Computes completions for byte `offset` in the entry file. +#[must_use] +pub(crate) fn completions(file: &FileAnalysis, offset: u32) -> Vec { + let arena = file.arena(); + let Some(entry) = file.source_file_id(&[]) else { + return Vec::new(); + }; + let source = arena[entry].source.as_str(); + + if let Some(items) = member_completions(file, entry, source, offset) { + return items; + } + + let mut items = Vec::new(); + push_keywords(&mut items); + push_locals(file, entry, offset, &mut items); + push_top_level_defs(file, entry, &mut items); + push_imported(file, entry, &mut items); + dedup(items) +} + +fn push_keywords(items: &mut Vec) { + for &keyword in KEYWORDS { + items.push(CompletionItem { + label: keyword.to_string(), + kind: CompletionItemKind::Keyword, + detail: None, + }); + } +} + +/// The locals visible at `offset`: the enclosing function's params, and the `let` +/// bindings declared before the cursor (a later binding is not yet in scope). +fn push_locals( + file: &FileAnalysis, + entry: SourceFileId, + offset: u32, + items: &mut Vec, +) { + let arena = file.arena(); + let Some(hit) = enclosing_hit(file, entry, offset) else { + return; + }; + let Some(function) = enclosing_function(arena, &hit) else { + return; + }; + if let Def::Function { args, .. } = &arena[function].kind { + for arg in args { + if let ArgKind::Named { name, ty, .. } = &arg.kind { + items.push(CompletionItem { + label: arena.ident_name(*name).to_string(), + kind: CompletionItemKind::Variable, + detail: Some(render_type(&TypeInfo::from_type_id(arena, *ty))), + }); + } + } + } + for stmt in in_scope_locals(arena, &hit, offset) { + if let Stmt::VarDef { name, ty, .. } = &arena[stmt].kind { + items.push(CompletionItem { + label: arena.ident_name(*name).to_string(), + kind: CompletionItemKind::Variable, + detail: Some(render_type(&TypeInfo::from_type_id(arena, *ty))), + }); + } + } +} + +fn push_top_level_defs(file: &FileAnalysis, entry: SourceFileId, items: &mut Vec) { + let arena = file.arena(); + for &def in &arena[entry].defs { + items.push(def_completion(file, entry, def)); + } +} + +/// Modules imported by the entry file plus each module's `pub` top-level defs, so +/// a name from an imported module can be completed. +fn push_imported(file: &FileAnalysis, entry: SourceFileId, items: &mut Vec) { + let arena = file.arena(); + for module_path in imported_module_paths(arena, entry) { + if let Some(name) = module_path.last() { + items.push(CompletionItem { + label: name.clone(), + kind: CompletionItemKind::Module, + detail: None, + }); + } + let Some(sfid) = file.source_file_id(&module_path) else { + continue; + }; + for &def in &arena[sfid].defs { + if crate::syntax::def_is_public(arena, def) { + items.push(def_completion(file, sfid, def)); + } + } + } +} + +fn def_completion(file: &FileAnalysis, sfid: SourceFileId, def: DefId) -> CompletionItem { + let arena = file.arena(); + CompletionItem { + label: arena.def_name(def).to_string(), + kind: def_kind(arena, def), + detail: def_signature(arena, sfid, def), + } +} + +fn def_kind(arena: &AstArena, def: DefId) -> CompletionItemKind { + match &arena[def].kind { + Def::Function { .. } | Def::ExternFunction { .. } => CompletionItemKind::Function, + Def::Enum { .. } => CompletionItemKind::Enum, + Def::Constant { .. } => CompletionItemKind::Constant, + Def::Spec { .. } => CompletionItemKind::Module, + // A type alias names a type, so it shares the struct icon in the list. + Def::Struct { .. } | Def::TypeAlias { .. } => CompletionItemKind::Struct, + } +} + +/// The completions after a `.`, or `None` when the cursor is not in member +/// position. An in-member cursor whose receiver is not a known struct yields an +/// empty list — no fields to offer — rather than falling back to the general set. +fn member_completions( + file: &FileAnalysis, + entry: SourceFileId, + source: &str, + offset: u32, +) -> Option> { + let receiver_end = member_receiver_end(source, offset)?; + let receiver = receiver_expr(file, entry, receiver_end)?; + let Some(type_info) = file + .typed_context() + .get_node_typeinfo(NodeId::Expr(receiver)) + else { + return Some(Vec::new()); + }; + let TypeInfoKind::Struct(bare, key) = &type_info.kind else { + return Some(Vec::new()); + }; + Some(struct_members(file, bare, key)) +} + +/// The byte offset at which the receiver expression ends (just before the `.`), +/// or `None` when `offset` is not in member position. +fn member_receiver_end(source: &str, offset: u32) -> Option { + let bytes = source.as_bytes(); + let mut cursor = (offset as usize).min(bytes.len()); + while cursor > 0 && is_ident_byte(bytes[cursor - 1]) { + cursor -= 1; + } + if cursor == 0 || bytes[cursor - 1] != b'.' { + return None; + } + let mut end = cursor - 1; + while end > 0 && bytes[end - 1].is_ascii_whitespace() { + end -= 1; + } + if end == 0 { + return None; + } + u32::try_from(end).ok() +} + +fn is_ident_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || byte == b'_' +} + +/// The outermost expression that ends exactly at `receiver_end` — the whole +/// receiver of the member access being typed. +fn receiver_expr(file: &FileAnalysis, entry: SourceFileId, receiver_end: u32) -> Option { + let arena = file.arena(); + let hit = file.hit_test(entry, receiver_end - 1)?; + outermost_first(&hit).find_map(|node| match node { + NodeId::Expr(expr) if arena[expr].location.offset_end == receiver_end => Some(expr), + _ => None, + }) +} + +fn outermost_first(hit: &NodeHit) -> impl Iterator + '_ { + hit.ancestors + .iter() + .copied() + .chain(std::iter::once(hit.node)) +} + +/// The fields and instance methods of the struct identified by `key`. +fn struct_members(file: &FileAnalysis, bare: &str, key: &str) -> Vec { + let arena = file.arena(); + let ctx = file.typed_context(); + let mut items = Vec::new(); + let Some(info) = ctx.lookup_struct(key) else { + return items; + }; + for field in &info.fields { + items.push(CompletionItem { + label: field.name.clone(), + kind: CompletionItemKind::Field, + detail: Some(render_type(&field.type_info)), + }); + } + let Some(module_path) = ctx.module_path_of_struct_key(key) else { + return items; + }; + let Some(sfid) = file.source_file_id(&module_path) else { + return items; + }; + let Some(struct_def) = find_def_by_name(arena, sfid, bare) else { + return items; + }; + if let Def::Struct { methods, .. } = &arena[struct_def].kind { + for &method in methods { + if method_has_self(arena, method) { + items.push(CompletionItem { + label: arena.def_name(method).to_string(), + kind: CompletionItemKind::Method, + detail: def_signature(arena, sfid, method), + }); + } + } + } + items +} + +/// The hit that locates `offset` within a definition, tolerating a cursor one +/// byte past the token it is completing. +/// +/// The one-byte fallback exists only to complete a just-typed identifier, so it +/// fires only when the byte at `offset - 1` is part of an identifier. A +/// punctuation byte such as a closing `}` must not pull the cursor back inside +/// the preceding definition, which would leak that function's params and locals +/// at file scope. +fn enclosing_hit(file: &FileAnalysis, entry: SourceFileId, offset: u32) -> Option { + if let Some(hit) = file.hit_test(entry, offset) { + return Some(hit); + } + let back = offset.checked_sub(1)?; + let source = file.arena()[entry].source.as_str(); + if source + .as_bytes() + .get(back as usize) + .copied() + .is_some_and(is_ident_byte) + { + file.hit_test(entry, back) + } else { + None + } +} + +/// Removes exact duplicates while preserving first-seen order (a local and a +/// same-named top-level def keep distinct entries by kind). +fn dedup(items: Vec) -> Vec { + let mut seen: FxHashSet<(String, CompletionItemKind)> = FxHashSet::default(); + items + .into_iter() + .filter(|item| seen.insert((item.label.clone(), item.kind))) + .collect() +} + +#[cfg(test)] +mod tests { + #![allow(clippy::cast_possible_truncation)] + + use super::{CompletionItem, CompletionItemKind}; + use crate::test_utils::{at, single, with_lib}; + + fn complete(source: &str, offset: u32) -> Vec { + let (mut host, path) = single(source); + host.analysis().completions(&path, offset) + } + + fn has(items: &[CompletionItem], label: &str, kind: CompletionItemKind) -> bool { + items + .iter() + .any(|item| item.label == label && item.kind == kind) + } + + #[test] + fn top_level_context_offers_keywords_and_definitions() { + let source = "struct Widget { w: i32; }\nfn compute() -> i32 { return 1; }"; + let items = complete(source, 0); + assert!(has(&items, "fn", CompletionItemKind::Keyword)); + assert!(has(&items, "forall", CompletionItemKind::Keyword)); + assert!(has(&items, "Widget", CompletionItemKind::Struct)); + assert!(has(&items, "compute", CompletionItemKind::Function)); + } + + #[test] + fn locals_declared_before_the_cursor_are_offered_later_ones_are_not() { + let source = "fn f() -> i32 { let early: i32 = 1; let later: i32 = 2; return early; }"; + let items = complete(source, at(source, "let later")); + assert!(has(&items, "early", CompletionItemKind::Variable)); + assert!( + !items.iter().any(|item| item.label == "later"), + "a not-yet-declared local is out of scope" + ); + // The enclosing function and keywords are still available. + assert!(has(&items, "f", CompletionItemKind::Function)); + assert!(has(&items, "let", CompletionItemKind::Keyword)); + } + + #[test] + fn params_are_offered_as_locals() { + let source = "fn f(seed: i32) -> i32 { return 0; }"; + let items = complete(source, at(source, "return")); + assert!(has(&items, "seed", CompletionItemKind::Variable)); + } + + #[test] + fn a_local_from_a_closed_sibling_block_is_not_offered() { + // Valid code (zero diagnostics): `inner`'s `if` block closes before the + // cursor, so it is out of scope and must not be offered — accepting it + // would produce an undeclared-variable error. + let source = "fn f(c: bool) -> i32 {\n\ + if c {\n\ + let inner: i32 = 1;\n\ + assert(inner > 0);\n\ + }\n\ + let z: i32 = 0;\n\ + return z;\n\ +}"; + let items = complete(source, at(source, "z;")); + assert!( + has(&items, "z", CompletionItemKind::Variable), + "the in-scope local is offered" + ); + assert!( + !items.iter().any(|item| item.label == "inner"), + "a local from an already-closed sibling block is out of scope: {items:?}" + ); + } + + #[test] + fn completions_after_the_closing_brace_do_not_leak_function_scope() { + // The cursor is one byte past `}`, at top-level file scope. The one-byte + // fallback must not pull it back inside the function and offer that + // function's params and locals, none of which are usable here. + let source = + "fn f(secret_param: i32) -> i32 { let secret_local: i32 = 1; return secret_local; }\n"; + let brace = source.rfind('}').expect("a closing brace") as u32; + let items = complete(source, brace + 1); + assert!( + !items + .iter() + .any(|item| item.kind == CompletionItemKind::Variable), + "no function-scoped names leak at top level after `}}`: {items:?}" + ); + // Top-level definitions are still offered at this position. + assert!(has(&items, "f", CompletionItemKind::Function)); + } + + #[test] + fn after_dot_on_a_struct_offers_only_fields_and_methods() { + let source = "struct P { x: i32; fn get(self) -> i32 { return self.x; } }\n\ +fn m(p: P) -> i32 { return p.; }"; + let items = complete(source, at(source, "p.;") + "p.".len() as u32); + let mut labels: Vec<&str> = items.iter().map(|item| item.label.as_str()).collect(); + labels.sort_unstable(); + assert_eq!(labels, vec!["get", "x"]); + assert!(has(&items, "x", CompletionItemKind::Field)); + assert!(has(&items, "get", CompletionItemKind::Method)); + assert!( + items + .iter() + .all(|item| item.kind != CompletionItemKind::Keyword), + "member context excludes keywords" + ); + } + + #[test] + fn after_dot_on_a_scalar_is_empty() { + let source = "fn m() -> i32 { let n: i32 = 1; return n.; }"; + let items = complete(source, at(source, "n.;") + "n.".len() as u32); + assert!( + items.is_empty(), + "a scalar receiver has no members: {items:?}" + ); + } + + #[test] + fn after_dot_offers_instance_methods_but_not_associated_functions() { + // `inst` takes `self` (callable as `p.inst()`); `make` does not, so it is + // reached as `P::make()` and must not appear after `.`. + let source = "struct P { x: i32; \ +fn inst(self) -> i32 { return self.x; } \ +fn make() -> i32 { return 1; } }\n\ +fn m(p: P) -> i32 { return p.; }"; + let items = complete(source, at(source, "p.;") + "p.".len() as u32); + assert!(has(&items, "inst", CompletionItemKind::Method)); + assert!( + !items.iter().any(|item| item.label == "make"), + "an associated function is not offered after `.`: {items:?}" + ); + } + + #[test] + fn imported_module_and_its_public_defs_are_offered() { + let entry = "use lib;\nfn main() -> i32 { return 0; }"; + let lib = "pub fn exported() -> i32 { return 1; }"; + let (mut host, path) = with_lib(entry, lib); + let items = host.analysis().completions(&path, at(entry, "return 0")); + assert!(has(&items, "lib", CompletionItemKind::Module)); + assert!(has(&items, "exported", CompletionItemKind::Function)); + } +} diff --git a/ide/ide/src/diagnostics.rs b/ide/ide/src/diagnostics.rs new file mode 100644 index 00000000..1baf54eb --- /dev/null +++ b/ide/ide/src/diagnostics.rs @@ -0,0 +1,424 @@ +//! Merged, editor-ready diagnostics for one open document. + +use inference_ast::ids::SourceFileId; +use inference_ast::nodes::{Directive, Location}; +use inference_ide_db::{ + FileAnalysis, FileParseErrors, ImportProblem, Severity as DbSeverity, TextRange, + TypeCheckDiagnostic, +}; +use inference_type_checker::errors::TypeCheckError; +use rustc_hash::FxHashSet; + +use crate::syntax::text_range; + +/// The severity of a [`Diagnostic`], in editor terminology and LSP ordering. +/// +/// A local mirror of the analysis crate's severity so the feature API leaks no +/// compiler type; the variant order matches LSP `DiagnosticSeverity` +/// (Error before Warning before Info). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Severity { + Error, + Warning, + Info, +} + +impl From for Severity { + fn from(severity: DbSeverity) -> Self { + match severity { + DbSeverity::Error => Severity::Error, + DbSeverity::Warning => Severity::Warning, + DbSeverity::Info => Severity::Info, + } + } +} + +/// One diagnostic anchored in the open document, ready to hand to the editor. +/// +/// `range` is a byte range in the open file's current text; the LSP layer +/// converts it to line/character with the file's line index. `code` groups +/// diagnostics by source: `"syntax"`, `"import"`, `"type"`, or an analysis rule +/// id (`"A001"`..`"A041"`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Diagnostic { + pub range: TextRange, + pub severity: Severity, + pub code: Option, + pub message: String, +} + +/// Collects every diagnostic that belongs to the entry file of `file`. +/// +/// Only the entry file's diagnostics are returned: an imported file's offsets are +/// local to that file and would be misplaced here. An imported file that failed +/// to parse still surfaces — as a single entry-file diagnostic on the `use` +/// directive that pulled it in — so the user sees why analysis is degraded. +#[must_use] +pub(crate) fn diagnostics(file: &FileAnalysis) -> Vec { + let mut out = Vec::new(); + push_entry_syntax_errors(file, &mut out); + push_import_problems(file, &mut out); + push_broken_import_summaries(file, &mut out); + push_entry_type_errors(file, &mut out); + push_entry_findings(file, &mut out); + out.sort_by_key(|d| (d.range.start, d.range.end)); + dedup_exact(out) +} + +/// Drops exact-duplicate diagnostics (same range, severity, code, and message), +/// keeping the first. A single logical problem must reach the editor once even +/// when an upstream phase pushes it twice (e.g. a checker error emitted on two +/// non-mutually-exclusive paths for one node), so this is a final belt-and-braces +/// pass independent of any upstream de-duplication. +fn dedup_exact(diagnostics: Vec) -> Vec { + let mut seen: FxHashSet<(TextRange, Severity, Option, String)> = FxHashSet::default(); + diagnostics + .into_iter() + .filter(|d| seen.insert((d.range, d.severity, d.code.clone(), d.message.clone()))) + .collect() +} + +fn push_entry_syntax_errors(file: &FileAnalysis, out: &mut Vec) { + let Some(entry) = file + .parse_errors() + .iter() + .find(|f| f.module_path.is_empty()) + else { + return; + }; + for error in &entry.errors { + out.push(Diagnostic { + range: text_range(error.span), + severity: Severity::Error, + code: Some("syntax".to_string()), + message: error.message.clone(), + }); + } +} + +fn push_import_problems(file: &FileAnalysis, out: &mut Vec) { + for problem in file.import_problems() { + if !problem.importing_module_path.is_empty() { + continue; // Anchored in an imported file, not the open document. + } + out.push(Diagnostic { + range: text_range(problem.location), + severity: Severity::Error, + code: Some("import".to_string()), + message: import_message(problem), + }); + } +} + +fn import_message(problem: &ImportProblem) -> String { + let base = format!("cannot find imported module `{}`", problem.referenced_as); + match &problem.suggestion { + Some(name) => format!("{base}; did you mean `{name}`?"), + None => base, + } +} + +/// Surfaces each imported file that failed to parse as one diagnostic on the +/// `use` directive that imports it, so a broken import degrades analysis visibly +/// instead of silently. +fn push_broken_import_summaries(file: &FileAnalysis, out: &mut Vec) { + let Some(entry) = file.source_file_id(&[]) else { + return; + }; + for broken in file.parse_errors() { + if broken.module_path.is_empty() || broken.errors.is_empty() { + continue; + } + let Some(location) = use_directive_location(file, entry, &broken.module_path) else { + // A transitively-imported broken file has no `use` directive in the + // open document to anchor on; its own file's diagnostics carry the + // detail. Skipping keeps the range honest rather than misplacing it. + continue; + }; + out.push(Diagnostic { + range: text_range(location), + severity: Severity::Error, + code: Some("import".to_string()), + message: broken_import_message(broken), + }); + } +} + +fn broken_import_message(broken: &FileParseErrors) -> String { + let module = broken.module_path.join("::"); + let count = broken.errors.len(); + let plural = if count == 1 { "error" } else { "errors" }; + format!("imported module `{module}` could not be analyzed: {count} syntax {plural}") +} + +/// The location of the entry-file `use` directive whose path names `module_path`, +/// or `None` when the module is not directly imported by the open document. +fn use_directive_location( + file: &FileAnalysis, + entry: SourceFileId, + module_path: &[String], +) -> Option { + let arena = file.arena(); + let target = module_path.join("::"); + arena[entry].directives.iter().find_map(|directive| { + let Directive::Use(use_directive) = directive; + let path = use_directive + .segments + .iter() + .map(|&segment| arena.ident_name(segment)) + .collect::>() + .join("::"); + (path == target).then_some(use_directive.location) + }) +} + +fn push_entry_type_errors(file: &FileAnalysis, out: &mut Vec) { + let import_locations = entry_import_problem_locations(file); + for diagnostic in file.type_errors() { + if diagnostic.file_label.is_some() { + continue; // Belongs to an imported file. + } + if is_redundant_import_error(&diagnostic.error, &import_locations) { + continue; // The authoritative `import` diagnostic already covers it. + } + out.push(Diagnostic { + range: text_range(*diagnostic.error.location()), + severity: Severity::Error, + code: Some("type".to_string()), + message: type_message(diagnostic), + }); + } +} + +/// The `use`-directive locations of every unresolved import anchored in the entry +/// file. A directive that failed to resolve already carries an authoritative +/// `import` diagnostic; the type checker independently complains about the same +/// directive, and those complaints are suppressed against this set. +fn entry_import_problem_locations(file: &FileAnalysis) -> Vec { + file.import_problems() + .iter() + .filter(|problem| problem.importing_module_path.is_empty()) + .map(|problem| problem.location) + .collect() +} + +/// Whether a type error merely restates that an import did not resolve at a +/// directive already reported by an `import` diagnostic. Only the two +/// import-resolution variants qualify, and only when their location matches a +/// recorded [`ImportProblem`] — so a genuine, otherwise-unreported type error is +/// never hidden. In an IDE a project context always exists, so the checker's +/// `FileImportWithoutProjectContext` message ("build the project") is both +/// redundant and wrong here. +fn is_redundant_import_error(error: &TypeCheckError, import_locations: &[Location]) -> bool { + matches!( + error, + TypeCheckError::FileImportWithoutProjectContext { .. } + | TypeCheckError::ImportResolutionFailed { .. } + ) && import_locations.contains(error.location()) +} + +/// The type error's message without its leading `line:col:` prefix, which the +/// separate `range` already conveys. +fn type_message(diagnostic: &TypeCheckDiagnostic) -> String { + let full = diagnostic.error.to_string(); + let prefix = format!("{}: ", diagnostic.error.location()); + full.strip_prefix(&prefix).unwrap_or(&full).to_string() +} + +fn push_entry_findings(file: &FileAnalysis, out: &mut Vec) { + for finding in file.findings() { + if !finding.labeled.module_path.is_empty() { + continue; // Belongs to an imported file. + } + out.push(Diagnostic { + range: text_range(*finding.labeled.diagnostic.location()), + severity: finding.severity.into(), + code: Some(finding.rule_id.to_string()), + message: finding.labeled.diagnostic.to_string(), + }); + } +} + +#[cfg(test)] +mod tests { + use super::{Diagnostic, dedup_exact}; + use crate::TextRange; + use crate::diagnostics::Severity; + use crate::test_utils::{after, at, nth, single, with_lib}; + + #[test] + fn clean_file_has_no_diagnostics() { + let src = "fn add(a: i32, b: i32) -> i32 { return a + b; }"; + let (mut host, path) = single(src); + assert!(host.analysis().diagnostics(&path).is_empty()); + } + + #[test] + fn undeclared_variable_is_a_type_diagnostic_at_the_use() { + let src = "fn f() -> i32 { return x; }"; + let (mut host, path) = single(src); + let diagnostics = host.analysis().diagnostics(&path); + let diagnostic = diagnostics + .iter() + .find(|d| d.message.contains("undeclared variable `x`")) + .expect("an undeclared-variable diagnostic"); + assert_eq!(diagnostic.code.as_deref(), Some("type")); + assert_eq!(diagnostic.severity, Severity::Error); + assert_eq!( + diagnostic.range, + TextRange { + start: at(src, "x"), + end: at(src, "x") + 1, + } + ); + // The redundant `line:col:` prefix is stripped from the message. + assert!(!diagnostic.message.starts_with(char::is_numeric)); + } + + #[test] + fn duplicate_local_is_an_a041_finding_on_the_second_declaration() { + let src = "fn f() { let a: i32 = 1; let a: i32 = 2; }"; + let (mut host, path) = single(src); + let diagnostics = host.analysis().diagnostics(&path); + let finding = diagnostics + .iter() + .find(|d| d.code.as_deref() == Some("A041")) + .expect("an A041 finding"); + assert_eq!(finding.severity, Severity::Error); + assert_eq!(finding.range.start, nth(src, "let a", 1)); + assert!(finding.message.contains("already declared")); + } + + #[test] + fn syntax_error_is_a_syntax_diagnostic() { + let src = "fn f() { let x: i32 = ; }"; + let (mut host, path) = single(src); + let diagnostics = host.analysis().diagnostics(&path); + assert!( + diagnostics + .iter() + .any(|d| d.code.as_deref() == Some("syntax") && d.severity == Severity::Error), + "expected a syntax diagnostic, got {diagnostics:?}" + ); + } + + #[test] + fn diagnostics_are_sorted_by_range_start() { + let src = "fn f() -> i32 { let a: i32 = 1; let a: i32 = 2; return z; }"; + let (mut host, path) = single(src); + let diagnostics = host.analysis().diagnostics(&path); + let starts: Vec = diagnostics.iter().map(|d| d.range.start).collect(); + let mut sorted = starts.clone(); + sorted.sort_unstable(); + assert_eq!(starts, sorted, "diagnostics come out ordered by position"); + } + + #[test] + fn broken_import_surfaces_on_the_use_directive() { + let entry = "use lib;\nfn main() -> i32 { return 0; }"; + let lib = "fn g() { let x: i32 = ; }"; + let (mut host, path) = with_lib(entry, lib); + let diagnostics = host.analysis().diagnostics(&path); + let diagnostic = diagnostics + .iter() + .find(|d| d.code.as_deref() == Some("import")) + .expect("an import diagnostic"); + assert!(diagnostic.message.contains("lib"), "{}", diagnostic.message); + assert!( + diagnostic.range.start >= at(entry, "use lib;") + && diagnostic.range.end <= after(entry, "use lib;"), + "range {:?} falls within the use directive", + diagnostic.range + ); + } + + #[test] + fn missing_import_reports_cannot_find_module() { + // `lib` is never opened and not on disk, so the import does not resolve. + let src = "use libx;\nfn main() -> i32 { return 0; }"; + let (mut host, path) = single(src); + let diagnostics = host.analysis().diagnostics(&path); + let diagnostic = diagnostics + .iter() + .find(|d| d.code.as_deref() == Some("import")) + .expect("an import diagnostic"); + assert!( + diagnostic + .message + .contains("cannot find imported module `libx`"), + "{}", + diagnostic.message + ); + assert!( + diagnostic.range.start >= at(src, "use libx;") + && diagnostic.range.end <= after(src, "use libx;"), + "anchored on the use directive" + ); + } + + #[test] + fn a_missing_import_does_not_also_report_a_project_context_type_error() { + // `libx` is absent, so the resilient walk records an ImportProblem and the + // type checker independently emits `FileImportWithoutProjectContext` for + // the same directive. The `import` diagnostic is authoritative; the + // contradictory "build the project" type error is suppressed (an IDE + // always has a project context). + let src = "use libx;\nfn main() -> i32 { return 0; }"; + let (mut host, path) = single(src); + let diagnostics = host.analysis().diagnostics(&path); + assert!( + diagnostics + .iter() + .any(|d| d.code.as_deref() == Some("import")), + "the missing-import diagnostic remains: {diagnostics:?}" + ); + assert!( + !diagnostics + .iter() + .any(|d| d.message.contains("file imports require a project context")), + "the contradictory project-context type error is suppressed: {diagnostics:?}" + ); + } + + #[test] + fn exact_duplicate_diagnostics_are_dropped() { + // A single problem must reach the editor once even when an upstream phase + // pushes it twice for one node; distinct diagnostics are preserved. + let base = Diagnostic { + range: TextRange { start: 5, end: 10 }, + severity: Severity::Error, + code: Some("type".to_string()), + message: "type mismatch".to_string(), + }; + assert_eq!( + dedup_exact(vec![base.clone(), base.clone()]).len(), + 1, + "exact duplicates collapse to one" + ); + let other = Diagnostic { + message: "a different message".to_string(), + ..base.clone() + }; + assert_eq!( + dedup_exact(vec![base, other]).len(), + 2, + "diagnostics differing in any field are kept" + ); + } + + #[test] + fn imported_file_diagnostics_do_not_leak_into_the_entry() { + // The entry is clean; only the single import summary should show, never the + // imported file's own per-file-local diagnostics (they'd be misplaced). + let entry = "use lib;\nfn main() -> i32 { return 0; }"; + let lib = "fn g() { let x: i32 = ; }"; + let (mut host, path) = with_lib(entry, lib); + let diagnostics = host.analysis().diagnostics(&path); + assert!( + diagnostics + .iter() + .all(|d| d.code.as_deref() == Some("import")), + "only import summaries belong to the entry, got {diagnostics:?}" + ); + } +} diff --git a/ide/ide/src/document_symbols.rs b/ide/ide/src/document_symbols.rs new file mode 100644 index 00000000..5add5eeb --- /dev/null +++ b/ide/ide/src/document_symbols.rs @@ -0,0 +1,294 @@ +//! The definition hierarchy of one document, for the outline / breadcrumb view. + +use inference_ast::arena::AstArena; +use inference_ast::ids::{DefId, IdentId}; +use inference_ast::nodes::{Def, Field}; +use inference_ide_db::{FileAnalysis, TextRange}; + +use crate::syntax::{def_name_ident, text_range}; + +/// The category of a [`DocumentSymbol`], in editor terminology. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum SymbolKind { + Function, + Struct, + Enum, + EnumVariant, + Field, + Method, + Spec, + Constant, + TypeAlias, +} + +/// A definition and the definitions nested inside it, forming the document +/// outline. `range` spans the whole definition; `selection_range` is just its +/// name, so an editor can reveal the declaration and highlight the identifier. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DocumentSymbol { + pub name: String, + pub kind: SymbolKind, + pub range: TextRange, + pub selection_range: TextRange, + pub children: Vec, +} + +/// Builds the outline of the entry file: top-level definitions, each carrying its +/// nested definitions (struct fields and methods, enum variants, spec-nested +/// defs) as children. +#[must_use] +pub(crate) fn document_symbols(file: &FileAnalysis) -> Vec { + let arena = file.arena(); + let Some(entry) = file.source_file_id(&[]) else { + return Vec::new(); + }; + arena[entry] + .defs + .iter() + .filter_map(|&def| def_symbol(arena, def)) + .collect() +} + +/// Whether `name` can be shown as an LSP symbol name. Parse-error recovery emits +/// a zero-width (empty) name identifier, and truly-absent names fall back to +/// ``; LSP 3.17 forbids an empty `DocumentSymbol.name`, so such recovered +/// definitions are dropped from the outline entirely rather than surfaced. +fn is_displayable(name: &str) -> bool { + !name.trim().is_empty() && name != "" +} + +/// A leaf symbol for the identifier `name`, or `None` when the identifier is a +/// parse-error placeholder (see [`is_displayable`]). +fn ident_symbol(arena: &AstArena, name: IdentId, kind: SymbolKind) -> Option { + let text = arena.ident_name(name); + if !is_displayable(text) { + return None; + } + let range = text_range(arena[name].location); + Some(DocumentSymbol { + name: text.to_string(), + kind, + range, + selection_range: range, + children: Vec::new(), + }) +} + +fn field_symbol(arena: &AstArena, field: &Field) -> Option { + ident_symbol(arena, field.name, SymbolKind::Field) +} + +/// A struct method: a `Def::Function` rendered as a `Method` leaf. +fn method_symbol(arena: &AstArena, method: DefId) -> Option { + let mut symbol = def_symbol(arena, method)?; + symbol.kind = SymbolKind::Method; + Some(symbol) +} + +/// The outline symbol for `def`, or `None` when the definition is a parse-error +/// placeholder with no displayable name (see [`is_displayable`]). +fn def_symbol(arena: &AstArena, def: DefId) -> Option { + let text = arena.def_name(def); + if !is_displayable(text) { + return None; + } + let range = text_range(arena[def].location); + let selection_range = text_range(arena[def_name_ident(arena, def)].location); + let name = text.to_string(); + let (kind, children) = match &arena[def].kind { + Def::Function { .. } | Def::ExternFunction { .. } => (SymbolKind::Function, Vec::new()), + Def::Struct { + fields, methods, .. + } => { + let mut children: Vec = fields + .iter() + .filter_map(|field| field_symbol(arena, field)) + .collect(); + children.extend( + methods + .iter() + .filter_map(|&method| method_symbol(arena, method)), + ); + (SymbolKind::Struct, children) + } + Def::Enum { variants, .. } => { + let children = variants + .iter() + .filter_map(|&variant| ident_symbol(arena, variant, SymbolKind::EnumVariant)) + .collect(); + (SymbolKind::Enum, children) + } + Def::Spec { defs, .. } => { + let children = defs + .iter() + .filter_map(|&nested| def_symbol(arena, nested)) + .collect(); + (SymbolKind::Spec, children) + } + Def::Constant { .. } => (SymbolKind::Constant, Vec::new()), + Def::TypeAlias { .. } => (SymbolKind::TypeAlias, Vec::new()), + }; + Some(DocumentSymbol { + name, + kind, + range, + selection_range, + children, + }) +} + +#[cfg(test)] +mod tests { + use super::{DocumentSymbol, SymbolKind}; + use crate::test_utils::{at, single}; + + const SOURCE: &str = "const MAX: i32 = 1;\n\ +type Handle = i32;\n\ +enum Color { Red, Green }\n\ +struct Point { px: i32; py: i32; fn getx(self) -> i32 { return self.px; } }\n\ +spec Laws { fn commutes() {} }\n\ +fn entry() { return; }"; + + fn symbols(source: &str) -> Vec { + let (mut host, path) = single(source); + host.analysis().document_symbols(&path) + } + + fn child<'a>(symbol: &'a DocumentSymbol, name: &str) -> &'a DocumentSymbol { + symbol + .children + .iter() + .find(|child| child.name == name) + .unwrap_or_else(|| panic!("child `{name}` present")) + } + + fn top<'a>(symbols: &'a [DocumentSymbol], name: &str) -> &'a DocumentSymbol { + symbols + .iter() + .find(|symbol| symbol.name == name) + .unwrap_or_else(|| panic!("top-level `{name}` present")) + } + + #[test] + fn top_level_order_and_kinds() { + let symbols = symbols(SOURCE); + let summary: Vec<(&str, SymbolKind)> = symbols + .iter() + .map(|symbol| (symbol.name.as_str(), symbol.kind)) + .collect(); + assert_eq!( + summary, + vec![ + ("MAX", SymbolKind::Constant), + ("Handle", SymbolKind::TypeAlias), + ("Color", SymbolKind::Enum), + ("Point", SymbolKind::Struct), + ("Laws", SymbolKind::Spec), + ("entry", SymbolKind::Function), + ] + ); + } + + #[test] + fn selection_ranges_point_at_the_name() { + let symbols = symbols(SOURCE); + for name in ["MAX", "Handle", "Color", "Point", "Laws", "entry"] { + let symbol = top(&symbols, name); + assert_eq!( + symbol.selection_range.start, + at(SOURCE, name), + "selection range of `{name}` is its identifier" + ); + assert!( + symbol.range.start <= symbol.selection_range.start + && symbol.range.end >= symbol.selection_range.end, + "whole-definition range of `{name}` contains its name" + ); + } + } + + #[test] + fn struct_children_are_fields_then_methods() { + let symbols = symbols(SOURCE); + let point = top(&symbols, "Point"); + let children: Vec<(&str, SymbolKind)> = point + .children + .iter() + .map(|c| (c.name.as_str(), c.kind)) + .collect(); + assert_eq!( + children, + vec![ + ("px", SymbolKind::Field), + ("py", SymbolKind::Field), + ("getx", SymbolKind::Method), + ] + ); + assert_eq!( + child(point, "getx").selection_range.start, + at(SOURCE, "getx") + ); + } + + #[test] + fn enum_children_are_variants() { + let symbols = symbols(SOURCE); + let color = top(&symbols, "Color"); + let children: Vec<(&str, SymbolKind)> = color + .children + .iter() + .map(|c| (c.name.as_str(), c.kind)) + .collect(); + assert_eq!( + children, + vec![ + ("Red", SymbolKind::EnumVariant), + ("Green", SymbolKind::EnumVariant), + ] + ); + } + + #[test] + fn spec_children_are_its_nested_functions() { + let symbols = symbols(SOURCE); + let laws = top(&symbols, "Laws"); + assert_eq!(laws.children.len(), 1); + assert_eq!(child(laws, "commutes").kind, SymbolKind::Function); + } + + #[test] + fn empty_file_has_no_symbols() { + assert!(symbols("").is_empty()); + } + + #[test] + fn a_nameless_recovered_definition_is_skipped() { + // `enum { ... }` recovers with a zero-width (empty) name identifier; LSP + // 3.17 forbids an empty `DocumentSymbol.name`, so the whole recovered + // definition is dropped from the outline rather than surfaced. + let symbols = symbols("enum { Red, Green }\nfn f() {}\n"); + assert!( + symbols + .iter() + .all(|symbol| !symbol.name.trim().is_empty() && symbol.name != ""), + "no empty or `` symbol names: {symbols:?}" + ); + let names: Vec<&str> = symbols.iter().map(|symbol| symbol.name.as_str()).collect(); + assert_eq!(names, vec!["f"], "only the named function survives"); + } + + #[test] + fn only_the_entry_files_symbols_are_returned() { + use crate::test_utils::with_lib; + let entry = "use lib;\nfn only_me() -> i32 { return 0; }"; + let lib = "pub fn hidden() -> i32 { return 1; }"; + let (mut host, path) = with_lib(entry, lib); + let names: Vec = host + .analysis() + .document_symbols(&path) + .into_iter() + .map(|symbol| symbol.name) + .collect(); + assert_eq!(names, vec!["only_me".to_string()]); + } +} diff --git a/ide/ide/src/goto_definition.rs b/ide/ide/src/goto_definition.rs new file mode 100644 index 00000000..7d44198b --- /dev/null +++ b/ide/ide/src/goto_definition.rs @@ -0,0 +1,583 @@ +//! Jump-to-definition: resolves the identifier at a position to its declaration. +//! +//! Definitions may live in an imported file, so a [`NavigationTarget`] carries +//! the target file's real path and ranges in that file's own coordinates +//! (offsets are per-file-local in the merged arena). + +use std::path::PathBuf; + +use inference_ast::arena::AstArena; +use inference_ast::ids::{DefId, ExprId, IdentId, NodeId, SourceFileId, StmtId, TypeId}; +use inference_ast::nodes::{ArgKind, Def, Expr, Location, Stmt, TypeNode}; +use inference_ide_db::{FileAnalysis, NodeHit, TextRange}; +use inference_type_checker::type_info::TypeInfoKind; + +use crate::syntax::{ + def_is_public, def_name_ident, enclosing_function, find_def_by_name, find_method, + imported_module_paths, in_scope_locals, is_call_callee, resolve_qualified_module, text_range, +}; + +/// A place a definition lives: the file's path, the whole declaration's range, +/// and the narrower range of just its name (what an editor highlights). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NavigationTarget { + pub path: PathBuf, + pub full_range: TextRange, + pub focus_range: TextRange, +} + +/// Resolves the definition of the identifier at byte `offset` in the entry file. +/// +/// Returns the target(s), or `None` when the offset is not on a resolvable +/// identifier. A single definition is the norm; the `Vec` leaves room for a +/// future ambiguous case without changing the signature. +#[must_use] +pub(crate) fn goto_definition(file: &FileAnalysis, offset: u32) -> Option> { + let entry = file.source_file_id(&[])?; + let hit = file.hit_test(entry, offset)?; + let NodeId::Ident(ident) = hit.node else { + return None; + }; + let grandparent = hit.ancestors.iter().rev().nth(1).copied(); + let target = match hit.ancestors.last().copied()? { + NodeId::Expr(expr) => goto_in_expr(file, entry, &hit, expr, ident, grandparent, offset)?, + NodeId::Type(type_id) => goto_in_type(file, entry, type_id, ident)?, + NodeId::Def(def) => goto_in_def(file, entry, def, ident)?, + NodeId::Stmt(stmt) => goto_in_stmt(file, entry, stmt, ident)?, + _ => return None, + }; + Some(vec![target]) +} + +fn path_of(file: &FileAnalysis, sfid: SourceFileId) -> Option { + let module_path = file.arena().source_file_module_path(sfid)?; + Some(file.file(module_path)?.path().to_path_buf()) +} + +fn nav_for_def(file: &FileAnalysis, sfid: SourceFileId, def: DefId) -> Option { + let arena = file.arena(); + Some(NavigationTarget { + path: path_of(file, sfid)?, + full_range: text_range(arena[def].location), + focus_range: text_range(arena[def_name_ident(arena, def)].location), + }) +} + +fn nav_at_ident( + file: &FileAnalysis, + sfid: SourceFileId, + full: Location, + focus: IdentId, +) -> Option { + Some(NavigationTarget { + path: path_of(file, sfid)?, + full_range: text_range(full), + focus_range: text_range(file.arena()[focus].location), + }) +} + +fn goto_in_expr( + file: &FileAnalysis, + entry: SourceFileId, + hit: &NodeHit, + expr: ExprId, + ident: IdentId, + grandparent: Option, + offset: u32, +) -> Option { + let arena = file.arena(); + match &arena[expr].kind { + Expr::Identifier(_) => { + if is_call_callee(arena, grandparent, expr) { + return goto_call(file, expr); + } + let name = arena.ident_name(ident); + if let Some(local) = resolve_local(file, hit, name, offset) { + return nav_at_ident(file, entry, arena[local].location, local); + } + goto_value_def(file, entry, name) + } + // A member access is either a method call (its access expression is the + // function of an enclosing call) or a plain field read. + Expr::MemberAccess { expr: receiver, .. } => { + if is_call_callee(arena, grandparent, expr) { + goto_call(file, expr) + } else { + goto_field(file, *receiver, ident) + } + } + // A `Type::member` is a `::`-qualified/associated call when it is a + // call's function, an enum variant when its access type is an enum, and + // otherwise a module-qualified item (a constant such as `lib::MAX`). + Expr::TypeMemberAccess { expr: base, .. } => { + if is_call_callee(arena, grandparent, expr) { + goto_call(file, expr) + } else { + goto_variant(file, expr, ident).or_else(|| { + let qualifier = access_qualifier_segments(arena, *base)?; + goto_module_member(file, entry, &qualifier, ident) + }) + } + } + Expr::StructLiteral { name, .. } => { + if *name == ident { + let (sfid, def) = resolve_type_def(file, entry, arena.ident_name(ident))?; + return nav_for_def(file, sfid, def); + } + let struct_name = arena.ident_name(*name); + let (sfid, struct_def) = resolve_type_def(file, entry, struct_name)?; + goto_field_in_struct(file, sfid, struct_def, arena.ident_name(ident)) + } + _ => None, + } +} + +/// The declaration of a local (param or `let`) named `name` visible at `offset`, +/// resolved syntactically: params first, then the in-scope `let` binding whose +/// name matches. Only bindings whose enclosing block encloses the use site are +/// considered (via [`in_scope_locals`]), so a binding in an already-closed +/// sibling block does not resolve here. Inference forbids shadowing, so a name +/// resolves to at most one declaration; the nearest before the use is returned. +fn resolve_local(file: &FileAnalysis, hit: &NodeHit, name: &str, offset: u32) -> Option { + let arena = file.arena(); + let function = enclosing_function(arena, hit)?; + if let Def::Function { args, .. } = &arena[function].kind { + for arg in args { + if let ArgKind::Named { name: param, .. } = &arg.kind + && arena.ident_name(*param) == name + { + return Some(*param); + } + } + } + + in_scope_locals(arena, hit, offset) + .into_iter() + .filter_map(|stmt| match &arena[stmt].kind { + Stmt::VarDef { name: declared, .. } if arena.ident_name(*declared) == name => { + Some(*declared) + } + _ => None, + }) + .max_by_key(|&declared| arena[declared].location.offset_end) +} + +/// The definition a call resolves to (free function or method), via the checker's +/// recorded call target — so a cross-file or re-exported call lands in the right +/// file. +fn goto_call(file: &FileAnalysis, callee: ExprId) -> Option { + let arena = file.arena(); + let target = file.typed_context().call_target(callee)?; + let sfid = file.source_file_id(&target.module_path)?; + let def = match &target.receiver_struct { + Some(struct_name) => { + let struct_def = find_def_by_name(arena, sfid, struct_name)?; + find_method(arena, struct_def, &target.name)? + } + None => find_def_by_name(arena, sfid, &target.name)?, + }; + nav_for_def(file, sfid, def) +} + +/// A top-level definition (function or constant) used as a value: same file +/// first, then a `pub` definition of a directly-imported module. +fn goto_value_def( + file: &FileAnalysis, + entry: SourceFileId, + name: &str, +) -> Option { + let arena = file.arena(); + if let Some(def) = find_def_by_name(arena, entry, name) { + return nav_for_def(file, entry, def); + } + for module_path in imported_module_paths(arena, entry) { + let Some(sfid) = file.source_file_id(&module_path) else { + continue; + }; + if let Some(def) = find_def_by_name(arena, sfid, name) + && def_is_public(arena, def) + { + return nav_for_def(file, sfid, def); + } + } + None +} + +/// The field declaration named like `field` on the struct value `receiver`. +fn goto_field(file: &FileAnalysis, receiver: ExprId, field: IdentId) -> Option { + let arena = file.arena(); + let ctx = file.typed_context(); + let type_info = ctx.get_node_typeinfo(NodeId::Expr(receiver))?; + let TypeInfoKind::Struct(bare, key) = &type_info.kind else { + return None; + }; + let module_path = ctx.module_path_of_struct_key(key)?; + let sfid = file.source_file_id(&module_path)?; + let struct_def = find_def_by_name(arena, sfid, bare)?; + goto_field_in_struct(file, sfid, struct_def, arena.ident_name(field)) +} + +fn goto_field_in_struct( + file: &FileAnalysis, + sfid: SourceFileId, + struct_def: DefId, + field_name: &str, +) -> Option { + let arena = file.arena(); + let Def::Struct { fields, .. } = &arena[struct_def].kind else { + return None; + }; + let field = fields + .iter() + .find(|field| arena.ident_name(field.name) == field_name)?; + nav_at_ident(file, sfid, arena[field.name].location, field.name) +} + +/// The variant declaration named like `variant` on the enum value `access` +/// (`Enum::Variant`). +fn goto_variant(file: &FileAnalysis, access: ExprId, variant: IdentId) -> Option { + let arena = file.arena(); + let ctx = file.typed_context(); + let type_info = ctx.get_node_typeinfo(NodeId::Expr(access))?; + let TypeInfoKind::Enum(bare, key) = &type_info.kind else { + return None; + }; + let info = ctx.lookup_enum(key)?; + let sfid = file.source_file_id(&ctx.module_path_of_scope(info.definition_scope_id))?; + let enum_def = find_def_by_name(arena, sfid, bare)?; + let Def::Enum { variants, .. } = &arena[enum_def].kind else { + return None; + }; + let target = variants + .iter() + .copied() + .find(|&candidate| arena.ident_name(candidate) == arena.ident_name(variant))?; + nav_at_ident(file, sfid, arena[target].location, target) +} + +/// Resolves a bare type name (struct or enum) to its defining file and def. +fn resolve_type_def( + file: &FileAnalysis, + entry: SourceFileId, + name: &str, +) -> Option<(SourceFileId, DefId)> { + let arena = file.arena(); + let ctx = file.typed_context(); + if let Some(module_path) = ctx.struct_module_path(name, &[]) + && let Some(sfid) = file.source_file_id(&module_path) + && let Some(def) = find_def_by_name(arena, sfid, name) + { + return Some((sfid, def)); + } + if let Some(key) = ctx.canonical_enum_key(name, &[]) + && let Some(info) = ctx.lookup_enum(&key) + { + let module_path = ctx.module_path_of_scope(info.definition_scope_id); + if let Some(sfid) = file.source_file_id(&module_path) + && let Some(def) = find_def_by_name(arena, sfid, name) + { + return Some((sfid, def)); + } + } + let def = find_def_by_name(arena, entry, name)?; + Some((entry, def)) +} + +/// Resolves a type reference at `ident` to its definition. A bare (`Custom`) type +/// resolves by name in the entry scope; a `::`-qualified type (`lib::T`) resolves +/// through its qualifier segments to the module that defines it — the qualifier +/// is never dropped, so an imported type is reachable by its qualified spelling. +fn goto_in_type( + file: &FileAnalysis, + entry: SourceFileId, + type_id: TypeId, + ident: IdentId, +) -> Option { + let arena = file.arena(); + match &arena[type_id].kind { + TypeNode::Qualified { qualifier, name } if *name == ident => { + goto_module_member(file, entry, qualifier, *name) + } + TypeNode::QualifiedName { qualifier, name } if *name == ident => { + goto_module_member(file, entry, std::slice::from_ref(qualifier), *name) + } + _ => { + let (sfid, def) = resolve_type_def(file, entry, arena.ident_name(ident))?; + nav_for_def(file, sfid, def) + } + } +} + +/// The definition named `leaf` in the module named by a reference's `::`-qualifier +/// segments — the target of a qualified spelling such as `lib::T` (type position) +/// or `lib::MAX` (value position) that names an imported item without a selective +/// `use`. A cross-module target must be `pub`; an entry-file target need not be. +fn goto_module_member( + file: &FileAnalysis, + entry: SourceFileId, + qualifier: &[IdentId], + leaf: IdentId, +) -> Option { + let arena = file.arena(); + let sfid = resolve_qualified_module(file, entry, qualifier)?; + let def = find_def_by_name(arena, sfid, arena.ident_name(leaf))?; + if sfid != entry && !def_is_public(arena, def) { + return None; + } + nav_for_def(file, sfid, def) +} + +/// The `::`-qualifier segments carried by the base of a `TypeMemberAccess`: the +/// `lib` of `lib::MAX`, or the `[a, b]` of `a::b::MAX`. `None` when the base is +/// not a plain qualifier chain of identifiers. +fn access_qualifier_segments(arena: &AstArena, base: ExprId) -> Option> { + match &arena[base].kind { + Expr::Identifier(id) => Some(vec![*id]), + Expr::TypeMemberAccess { expr, name } => { + let mut segments = access_qualifier_segments(arena, *expr)?; + segments.push(*name); + Some(segments) + } + _ => None, + } +} + +fn goto_in_def( + file: &FileAnalysis, + entry: SourceFileId, + def: DefId, + ident: IdentId, +) -> Option { + let arena = file.arena(); + if def_name_ident(arena, def) == ident { + return nav_for_def(file, entry, def); + } + match &arena[def].kind { + Def::Function { args, .. } | Def::ExternFunction { args, .. } => { + for arg in args { + if let ArgKind::Named { name, .. } = &arg.kind + && *name == ident + { + return nav_at_ident(file, entry, arena[*name].location, *name); + } + } + None + } + Def::Struct { fields, .. } => { + let field = fields.iter().find(|field| field.name == ident)?; + nav_at_ident(file, entry, arena[field.name].location, field.name) + } + _ => None, + } +} + +fn goto_in_stmt( + file: &FileAnalysis, + entry: SourceFileId, + stmt: StmtId, + ident: IdentId, +) -> Option { + let arena = file.arena(); + match &arena[stmt].kind { + Stmt::VarDef { name, .. } | Stmt::TypeDef { name, .. } if *name == ident => { + nav_at_ident(file, entry, arena[stmt].location, *name) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::cast_possible_truncation)] + + use crate::NavigationTarget; + use crate::test_utils::{at, module_path, nth, single, with_lib}; + + fn goto(source: &str, offset: u32) -> Option> { + let (mut host, path) = single(source); + host.analysis().goto_definition(&path, offset) + } + + fn one(source: &str, offset: u32) -> NavigationTarget { + let mut targets = goto(source, offset).expect("a definition"); + assert_eq!(targets.len(), 1, "exactly one target"); + targets.remove(0) + } + + const OBJ: &str = "struct P { x: i32; }\n\ +fn helper() -> i32 { return 7; }\n\ +fn use_it(p: P) -> i32 { let v: i32 = helper(); return v + p.x; }"; + + #[test] + fn goto_local_variable_reaches_its_let() { + let target = one(OBJ, at(OBJ, "v + p.x")); + assert_eq!(target.path, module_path("main")); + assert_eq!(target.focus_range.start, at(OBJ, "v: i32")); + } + + #[test] + fn goto_parameter_reaches_its_declaration() { + let target = one(OBJ, at(OBJ, "p.x")); + assert_eq!(target.focus_range.start, at(OBJ, "p: P")); + } + + #[test] + fn goto_field_in_member_access_reaches_the_field() { + let target = one(OBJ, at(OBJ, "p.x") + "p.".len() as u32); + assert_eq!(target.focus_range.start, at(OBJ, "x: i32")); + } + + #[test] + fn goto_same_file_call_reaches_the_function() { + let target = one(OBJ, at(OBJ, "helper();")); + assert_eq!(target.focus_range.start, at(OBJ, "helper")); + } + + #[test] + fn goto_struct_name_in_type_position_reaches_the_struct() { + let target = one(OBJ, at(OBJ, "p: P") + "p: ".len() as u32); + assert_eq!( + target.focus_range.start, + at(OBJ, "struct P") + "struct ".len() as u32 + ); + } + + #[test] + fn goto_method_call_via_receiver_reaches_the_method() { + let source = "struct Q { y: i32; fn getq(self) -> i32 { return self.y; } }\n\ +fn m(q: Q) -> i32 { return q.getq(); }"; + let target = one(source, at(source, "q.getq()") + "q.".len() as u32); + assert_eq!(target.focus_range.start, at(source, "getq")); + } + + // The return type is `i32`, not `R`, so `"R {"` occurs exactly twice — the + // struct declaration (0) and the literal (1) — and `nth(_, 1)` reliably lands + // on the literal rather than a return-type `R`. + const LITERAL: &str = "struct R { z: i32; }\n\ +fn mk() -> i32 { let r: R = R { z: 1 }; return r.z; }"; + + #[test] + fn goto_struct_literal_name_reaches_the_struct() { + let target = one(LITERAL, nth(LITERAL, "R {", 1)); + assert_eq!( + target.focus_range.start, + at(LITERAL, "struct R") + "struct ".len() as u32 + ); + } + + #[test] + fn goto_struct_literal_field_reaches_the_field() { + let target = one(LITERAL, at(LITERAL, "z: 1")); + assert_eq!(target.focus_range.start, at(LITERAL, "z: i32")); + } + + #[test] + fn goto_imported_constant_used_as_a_value() { + let entry = "use lib::{MAX};\nfn main() -> i32 { return MAX; }"; + let lib = "pub const MAX: i32 = 99;"; + let (mut host, path) = with_lib(entry, lib); + let mut targets = host + .analysis() + .goto_definition(&path, at(entry, "return MAX") + "return ".len() as u32) + .expect("a definition for the imported constant"); + assert_eq!(targets.len(), 1, "exactly one target"); + let target = targets.remove(0); + assert_eq!(target.path, module_path("lib")); + assert_eq!(target.focus_range.start, at(lib, "MAX")); + } + + #[test] + fn goto_enum_variant_reaches_the_variant() { + let source = "enum Color { Red, Green }\n\ +fn f() -> Color { let c: Color = Color::Red; return c; }"; + let target = one(source, at(source, "Color::Red") + "Color::".len() as u32); + assert_eq!(target.focus_range.start, at(source, "Red")); + } + + #[test] + fn goto_definition_name_reaches_itself() { + let source = "fn helper() -> i32 { return 7; }"; + let target = one(source, at(source, "helper")); + assert_eq!(target.focus_range.start, at(source, "helper")); + } + + #[test] + fn goto_unresolved_name_is_none() { + let source = "fn f() -> i32 { return zzz; }"; + assert!(goto(source, at(source, "zzz")).is_none()); + } + + #[test] + fn goto_local_in_a_closed_sibling_block_does_not_resolve() { + // `inner` is declared inside the `if` block; at the use after the block + // has closed it is out of scope (the checker reports it undeclared), so + // goto must not teleport into the sibling block. Contrast with the + // in-scope `let z`, whose block encloses the use. + let source = "fn f(c: bool) -> i32 {\n\ +if c {\n\ +let inner: i32 = 1;\n\ +assert(inner > 0);\n\ +}\n\ +let z: i32 = 0;\n\ +return z + inner;\n\ +}"; + assert!( + goto(source, at(source, "inner;")).is_none(), + "a use after the declaring block closed is out of scope" + ); + // The sibling `z`, declared in the enclosing function body, still resolves. + let target = one(source, at(source, "z + inner")); + assert_eq!(target.focus_range.start, at(source, "z: i32")); + } + + #[test] + fn goto_qualified_type_reaches_the_imported_struct() { + // `lib::T` is the qualified spelling of an imported type; goto must follow + // the qualifier into lib.inf rather than dropping it and returning None. + let entry = "use lib;\nfn main() -> i32 { let t: lib::T = lib::mk(); return t.v; }\n"; + let lib = "pub struct T { v: i32; }\npub fn mk() -> T { return T { v: 1 }; }\n"; + let (mut host, path) = with_lib(entry, lib); + let target = host + .analysis() + .goto_definition(&path, at(entry, "lib::T") + "lib::".len() as u32) + .expect("a definition for the qualified type") + .remove(0); + assert_eq!(target.path, module_path("lib")); + assert_eq!( + target.focus_range.start, + at(lib, "struct T") + "struct ".len() as u32 + ); + } + + #[test] + fn goto_qualified_constant_reaches_the_imported_constant() { + // `lib::MAX` reads an imported constant through its qualified spelling; the + // access is a `TypeMemberAccess` that is not an enum variant, so goto must + // fall through to module-member resolution rather than returning None. + let entry = "use lib;\nfn main() -> i32 { return lib::MAX; }\n"; + let lib = "pub const MAX: i32 = 99;\n"; + let (mut host, path) = with_lib(entry, lib); + let target = host + .analysis() + .goto_definition(&path, at(entry, "lib::MAX") + "lib::".len() as u32) + .expect("a definition for the qualified constant") + .remove(0); + assert_eq!(target.path, module_path("lib")); + assert_eq!(target.focus_range.start, at(lib, "MAX")); + } + + #[test] + fn goto_cross_module_function_returns_the_imported_file() { + let entry = "use lib;\nfn main() -> i32 { return lib::helper(); }"; + let lib = "pub fn helper() -> i32 { return 7; }"; + let (mut host, path) = with_lib(entry, lib); + let mut targets = host + .analysis() + .goto_definition(&path, at(entry, "helper();")) + .expect("a cross-module definition"); + assert_eq!(targets.len(), 1, "exactly one target"); + let target = targets.remove(0); + assert_eq!(target.path, module_path("lib")); + assert_eq!(target.focus_range.start, at(lib, "helper")); + } +} diff --git a/ide/ide/src/hover.rs b/ide/ide/src/hover.rs new file mode 100644 index 00000000..593cdefb --- /dev/null +++ b/ide/ide/src/hover.rs @@ -0,0 +1,425 @@ +//! Type and documentation shown when hovering a position in a document. + +use inference_ast::arena::AstArena; +use inference_ast::ids::{DefId, ExprId, IdentId, NodeId, SourceFileId}; +use inference_ast::nodes::{ArgKind, Def, Expr}; +use inference_ide_db::{FileAnalysis, NodeHit, TextRange}; +use inference_type_checker::type_info::TypeInfo; +use inference_type_checker::typed_context::TypedContext; + +use crate::nondet_docs::{UZUMAKI_HOVER, block_hover, block_keyword}; +use crate::syntax::{ + def_name_ident, def_signature, find_def_by_name, find_method, is_call_callee, text_range, +}; +use crate::type_render::render_type; + +/// The information shown in a hover popover: markdown contents plus the source +/// range they describe (so the editor can underline the hovered token). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Hover { + pub contents_markdown: String, + pub range: TextRange, +} + +/// Computes the hover for byte `offset` in the entry file, or `None` when nothing +/// meaningful sits there (whitespace, or a token with no type or documentation). +#[must_use] +pub(crate) fn hover(file: &FileAnalysis, offset: u32) -> Option { + let arena = file.arena(); + let ctx = file.typed_context(); + let entry = file.source_file_id(&[])?; + let hit = file.hit_test(entry, offset)?; + + if let Some(hover) = nondet_keyword_hover(arena, &hit, offset) { + return Some(hover); + } + if let NodeId::Expr(expr) = hit.node + && matches!(arena[expr].kind, Expr::Uzumaki) + { + return Some(Hover { + contents_markdown: UZUMAKI_HOVER.to_string(), + range: text_range(arena[expr].location), + }); + } + if let NodeId::Ident(ident) = hit.node { + return hover_ident(file, entry, &hit, ident); + } + if let NodeId::Type(ty) = hit.node { + return Some(Hover { + contents_markdown: code_block(&render_type(&TypeInfo::from_type_id(arena, ty))), + range: text_range(arena[ty].location), + }); + } + if let NodeId::Expr(expr) = hit.node { + let type_info = ctx.get_node_typeinfo(NodeId::Expr(expr))?; + return Some(Hover { + contents_markdown: code_block(&render_type(&type_info)), + range: text_range(arena[expr].location), + }); + } + None +} + +fn code_block(body: &str) -> String { + format!("```inference\n{body}\n```") +} + +/// A hover for a non-det block keyword, when `offset` falls inside it. +fn nondet_keyword_hover(arena: &AstArena, hit: &NodeHit, offset: u32) -> Option { + let NodeId::Block(block) = hit.node else { + return None; + }; + let data = &arena[block]; + let keyword = block_keyword(data.block_kind)?; + let start = data.location.offset_start; + let end = start.checked_add(u32::try_from(keyword.len()).ok()?)?; + if offset < start || offset >= end { + return None; + } + Some(Hover { + contents_markdown: block_hover(data.block_kind)?.to_string(), + range: TextRange { start, end }, + }) +} + +/// A hover for an identifier, dispatched on the role its parent gives it. +fn hover_ident( + file: &FileAnalysis, + entry: SourceFileId, + hit: &NodeHit, + ident: IdentId, +) -> Option { + let arena = file.arena(); + let ctx = file.typed_context(); + let range = text_range(arena[ident].location); + let parent = hit.ancestors.last().copied(); + let grandparent = hit.ancestors.iter().rev().nth(1).copied(); + + let contents = match parent { + Some(NodeId::Def(def)) => ident_in_def(arena, entry, def, ident)?, + Some(NodeId::Expr(expr)) => ident_in_expr(file, entry, expr, ident, grandparent)?, + Some(NodeId::Type(_)) => type_name_signature(file, entry, ident), + Some(NodeId::Stmt(stmt)) => ident_in_stmt(arena, ctx, stmt, ident)?, + _ => return None, + }; + Some(Hover { + contents_markdown: contents, + range, + }) +} + +/// The def's own name (→ its signature) or one of its params/fields (→ its type). +fn ident_in_def( + arena: &AstArena, + entry: SourceFileId, + def: DefId, + ident: IdentId, +) -> Option { + if def_name_ident(arena, def) == ident { + return def_signature(arena, entry, def).map(|sig| code_block(&sig)); + } + match &arena[def].kind { + Def::Function { args, .. } | Def::ExternFunction { args, .. } => { + for arg in args { + if let ArgKind::Named { name, ty, .. } = &arg.kind + && *name == ident + { + let type_info = TypeInfo::from_type_id(arena, *ty); + return Some(named_type(arena.ident_name(ident), &type_info)); + } + } + None + } + Def::Struct { fields, .. } => { + let field = fields.iter().find(|field| field.name == ident)?; + let type_info = TypeInfo::from_type_id(arena, field.ty); + Some(named_type(arena.ident_name(ident), &type_info)) + } + _ => None, + } +} + +/// An identifier appearing inside an expression: a value reference, a call +/// callee, a member name, or a struct-literal name or field. +fn ident_in_expr( + file: &FileAnalysis, + entry: SourceFileId, + expr: ExprId, + ident: IdentId, + grandparent: Option, +) -> Option { + let arena = file.arena(); + let ctx = file.typed_context(); + match &arena[expr].kind { + Expr::Identifier(_) => { + if is_call_callee(arena, grandparent, expr) { + return callee_signature(file, expr); + } + let type_info = ctx.get_node_typeinfo(NodeId::Expr(expr))?; + Some(named_type(arena.ident_name(ident), &type_info)) + } + Expr::MemberAccess { .. } | Expr::TypeMemberAccess { .. } => { + // A method or `::`-qualified call resolves to its callee's signature; + // a plain field or variant access shows the member's type. + if is_call_callee(arena, grandparent, expr) { + return callee_signature(file, expr); + } + let type_info = ctx.get_node_typeinfo(NodeId::Expr(expr))?; + Some(named_type(arena.ident_name(ident), &type_info)) + } + Expr::StructLiteral { name, .. } => { + if *name == ident { + return Some(type_name_signature(file, entry, ident)); + } + let struct_name = arena.ident_name(*name); + let info = ctx.lookup_struct_in(struct_name, &[])?; + let field = info.get_field_info_by_name(arena.ident_name(ident))?; + Some(named_type(arena.ident_name(ident), &field.type_info)) + } + _ => None, + } +} + +/// A `let name: T` / `type name = …` binding: the declared name's type. +fn ident_in_stmt( + arena: &AstArena, + ctx: &TypedContext, + stmt: inference_ast::ids::StmtId, + ident: IdentId, +) -> Option { + use inference_ast::nodes::Stmt; + match &arena[stmt].kind { + Stmt::VarDef { name, ty, .. } if *name == ident => { + let type_info = ctx + .get_node_typeinfo(NodeId::Ident(ident)) + .unwrap_or_else(|| TypeInfo::from_type_id(arena, *ty)); + Some(named_type(arena.ident_name(ident), &type_info)) + } + Stmt::TypeDef { name, ty } if *name == ident => Some(code_block(&format!( + "type {} = {}", + arena.ident_name(ident), + render_type(&TypeInfo::from_type_id(arena, *ty)) + ))), + _ => None, + } +} + +fn named_type(name: &str, type_info: &TypeInfo) -> String { + code_block(&format!("{name}: {}", render_type(type_info))) +} + +/// The signature of the function a call resolves to, in the callee's own file. +fn callee_signature(file: &FileAnalysis, callee: ExprId) -> Option { + let arena = file.arena(); + let ctx = file.typed_context(); + let target = ctx.call_target(callee)?; + let sfid = file.source_file_id(&target.module_path)?; + let def = match &target.receiver_struct { + Some(struct_name) => { + let struct_def = find_def_by_name(arena, sfid, struct_name)?; + find_method(arena, struct_def, &target.name)? + } + None => find_def_by_name(arena, sfid, &target.name)?, + }; + def_signature(arena, sfid, def).map(|sig| code_block(&sig)) +} + +/// The signature of the struct/enum/type a bare type name refers to — its +/// defining file when cross-module, else the entry file — or the bare type +/// spelling when it names no such definition. +fn type_name_signature(file: &FileAnalysis, entry: SourceFileId, ident: IdentId) -> String { + let arena = file.arena(); + let ctx = file.typed_context(); + let name = arena.ident_name(ident); + + // Resolve the type's defining file for a struct or an enum, so a cross-module + // name shows its real signature (mirrors goto's `resolve_type_def`). + let defining_file = ctx + .struct_module_path(name, &[]) + .or_else(|| enum_module_path(ctx, name)) + .and_then(|module_path| file.source_file_id(&module_path)) + .unwrap_or(entry); + + if let Some(def) = find_def_by_name(arena, defining_file, name) + && let Some(signature) = def_signature(arena, defining_file, def) + { + return code_block(&signature); + } + code_block(name) +} + +/// The defining-file module path of the enum named `name` referenced from the +/// entry file, or `None` if `name` names no visible enum. +fn enum_module_path(ctx: &TypedContext, name: &str) -> Option> { + let key = ctx.canonical_enum_key(name, &[])?; + let info = ctx.lookup_enum(&key)?; + Some(ctx.module_path_of_scope(info.definition_scope_id)) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::cast_possible_truncation)] + + use crate::Hover; + use crate::test_utils::{at, nth, single, with_lib}; + + fn hover_at(source: &str, offset: u32) -> Option { + let (mut host, path) = single(source); + host.analysis().hover(&path, offset) + } + + const OBJ: &str = "struct P { x: i32; fn get(self) -> i32 { return self.x; } }\n\ +fn helper() -> i32 { return 7; }\n\ +fn use_it(p: P) -> i32 { let v: i32 = helper(); return v; }"; + + #[test] + fn hover_local_variable_shows_its_type() { + let hover = hover_at(OBJ, at(OBJ, "return v") + "return ".len() as u32).expect("hover"); + assert_eq!(hover.contents_markdown, "```inference\nv: i32\n```"); + } + + #[test] + fn hover_parameter_shows_its_type() { + let hover = hover_at(OBJ, at(OBJ, "p: P")).expect("hover"); + assert_eq!(hover.contents_markdown, "```inference\np: P\n```"); + } + + #[test] + fn hover_free_call_shows_the_signature() { + let hover = hover_at(OBJ, at(OBJ, "helper();")).expect("hover"); + assert_eq!( + hover.contents_markdown, + "```inference\nfn helper() -> i32\n```" + ); + } + + #[test] + fn hover_field_access_shows_the_field_type() { + let hover = hover_at(OBJ, at(OBJ, "self.x") + "self.".len() as u32).expect("hover"); + assert_eq!(hover.contents_markdown, "```inference\nx: i32\n```"); + } + + #[test] + fn hover_struct_name_in_type_position_shows_its_signature() { + let hover = hover_at(OBJ, at(OBJ, "p: P") + "p: ".len() as u32).expect("hover"); + assert!( + hover.contents_markdown.contains("struct P"), + "{}", + hover.contents_markdown + ); + } + + #[test] + fn hover_each_nondet_keyword_returns_its_doc_and_keyword_range() { + let cases = [ + ("forall", "fn f() { forall { assert(true); } }"), + ("exists", "fn f() { exists { assert(true); } }"), + ("unique", "fn f() { unique { assert(true); } }"), + ("assume", "fn f() { assume { assert(true); } }"), + ]; + for (keyword, source) in cases { + let start = at(source, keyword); + let hover = hover_at(source, start).unwrap_or_else(|| panic!("hover on {keyword}")); + assert!( + hover.contents_markdown.contains(&format!("`{keyword}`")), + "doc for {keyword}: {}", + hover.contents_markdown + ); + assert_eq!(hover.range.start, start); + assert_eq!(hover.range.end, start + keyword.len() as u32); + } + } + + #[test] + fn hover_uzumaki_returns_its_doc() { + let source = "fn f() { forall { let x: i32 = @; assert(x == x); } }"; + let hover = hover_at(source, at(source, "@")).expect("hover on @"); + assert!( + hover.contents_markdown.contains("`@`"), + "{}", + hover.contents_markdown + ); + assert_eq!(hover.range.start, at(source, "@")); + assert_eq!(hover.range.end, at(source, "@") + 1); + } + + #[test] + fn hover_number_literal_shows_its_type() { + let source = "fn f() -> i32 { return 42; }"; + let hover = hover_at(source, at(source, "42")).expect("a number literal has a type"); + assert_eq!(hover.contents_markdown, "```inference\ni32\n```"); + } + + #[test] + fn hover_method_call_shows_the_method_signature() { + let source = "struct Q { y: i32; fn getq(self) -> i32 { return self.y; } }\n\ +fn u(q: Q) -> i32 { return q.getq(); }"; + let hover = hover_at(source, at(source, "q.getq()") + "q.".len() as u32).expect("hover"); + assert_eq!( + hover.contents_markdown, + "```inference\nfn getq(self) -> i32\n```" + ); + } + + #[test] + fn hover_struct_literal_name_and_field() { + let source = "struct R { z: i32; }\n\ +fn mk() -> i32 { let r: R = R { z: 1 }; return r.z; }"; + let name = hover_at(source, nth(source, "R {", 1)).expect("hover on literal name"); + assert!( + name.contents_markdown.contains("struct R"), + "{}", + name.contents_markdown + ); + let field = hover_at(source, at(source, "z: 1")).expect("hover on literal field"); + assert_eq!(field.contents_markdown, "```inference\nz: i32\n```"); + } + + #[test] + fn hover_declaration_name_shows_its_type() { + let source = "fn f() -> i32 { let count: i32 = 5; return count; }"; + let hover = hover_at(source, at(source, "count: i32")).expect("hover on let name"); + assert_eq!(hover.contents_markdown, "```inference\ncount: i32\n```"); + } + + #[test] + fn hover_enum_type_name_shows_its_signature() { + let source = "enum Color { Red, Green }\nfn f(c: Color) -> i32 { return 0; }"; + let hover = hover_at(source, at(source, "c: Color") + "c: ".len() as u32).expect("hover"); + assert!( + hover.contents_markdown.contains("enum Color"), + "{}", + hover.contents_markdown + ); + } + + #[test] + fn hover_definition_name_shows_its_signature() { + let source = "fn add(a: i32, b: i32) -> i32 { return a + b; }"; + let hover = hover_at(source, at(source, "add")).expect("hover on def name"); + assert_eq!( + hover.contents_markdown, + "```inference\nfn add(a: i32, b: i32) -> i32\n```" + ); + } + + #[test] + fn hover_field_of_a_cross_module_struct() { + // The struct is defined in `lib`; hovering the field access in the entry + // must still resolve its type through the imported file's definition. + let entry = "use lib;\nfn use_pt(p: lib::Point) -> i32 { return p.x; }"; + let lib = "pub struct Point { pub x: i32; }"; + let (mut host, path) = with_lib(entry, lib); + let hover = host + .analysis() + .hover(&path, at(entry, "p.x") + "p.".len() as u32) + .expect("hover on cross-module field"); + assert_eq!(hover.contents_markdown, "```inference\nx: i32\n```"); + } + + #[test] + fn hover_whitespace_between_definitions_is_none() { + let source = "fn a() { return; } fn b() { return; }"; + assert!(hover_at(source, at(source, " ") + 1).is_none()); + } +} diff --git a/ide/ide/src/inlay_hints.rs b/ide/ide/src/inlay_hints.rs new file mode 100644 index 00000000..6898dcdb --- /dev/null +++ b/ide/ide/src/inlay_hints.rs @@ -0,0 +1,262 @@ +//! Inline hints that restate what each non-det construct means, at a glance. + +use inference_ast::ids::{ExprId, NodeId, TypeId}; +use inference_ast::nodes::{BlockKind, Expr, Stmt}; +use inference_ide_db::{FileAnalysis, TextRange}; +use inference_type_checker::type_info::TypeInfo; +use rustc_hash::FxHashMap; + +use crate::nondet_docs::{UZUMAKI_INLAY, block_inlay, block_keyword}; +use crate::syntax::walk_file; +use crate::type_render::render_type; + +/// What a non-det [`InlayHint`] annotates. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum InlayHintKind { + /// The header of a `forall` / `exists` / `unique` / `assume` block. + NonDetBlock, + /// A `@` (uzumaki) binding. + Uzumaki, +} + +/// One inline hint placed at a byte `offset` in the open document. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InlayHint { + pub offset: u32, + pub label: String, + pub kind: InlayHintKind, +} + +/// Produces the non-det inlay hints for the entry file, optionally clipped to +/// `range` (used to fetch only the hints for the viewport an editor is showing). +/// +/// A block-header hint sits just after the opening keyword; a uzumaki hint sits +/// just after the `@`, with the binding's concrete type appended when known. +#[must_use] +pub(crate) fn inlay_hints(file: &FileAnalysis, range: Option) -> Vec { + let arena = file.arena(); + let Some(entry) = file.source_file_id(&[]) else { + return Vec::new(); + }; + let source = arena[entry].source.as_str(); + + let mut uzumaki_types: FxHashMap = FxHashMap::default(); + let mut hints = Vec::new(); + walk_file(arena, entry, &mut |node| match node { + NodeId::Stmt(stmt) => { + if let Stmt::VarDef { + ty, + value: Some(value), + .. + } = &arena[stmt].kind + && matches!(arena[*value].kind, Expr::Uzumaki) + { + uzumaki_types.insert(*value, *ty); + } + } + NodeId::Block(block) => { + let data = &arena[block]; + if let Some(hint) = + nondet_block_hint(source, data.block_kind, data.location.offset_start) + { + hints.push(hint); + } + } + NodeId::Expr(expr) => { + if matches!(arena[expr].kind, Expr::Uzumaki) { + let declared = uzumaki_types + .get(&expr) + .map(|&ty| TypeInfo::from_type_id(arena, ty)); + hints.push(InlayHint { + offset: arena[expr].location.offset_end, + label: uzumaki_label(declared.as_ref()), + kind: InlayHintKind::Uzumaki, + }); + } + } + _ => {} + }); + + if let Some(range) = range { + hints.retain(|hint| hint.offset >= range.start && hint.offset < range.end); + } + hints.sort_by_key(|hint| hint.offset); + hints +} + +/// A block-header hint, or `None` for a regular block or when the keyword is not +/// where the location says it should be (a defensive guard against a stray span). +fn nondet_block_hint(source: &str, kind: BlockKind, start: u32) -> Option { + let keyword = block_keyword(kind)?; + let label = block_inlay(kind)?; + let end = start.checked_add(u32::try_from(keyword.len()).ok()?)?; + if source.get(start as usize..end as usize) != Some(keyword) { + return None; + } + Some(InlayHint { + offset: end, + label: label.to_string(), + kind: InlayHintKind::NonDetBlock, + }) +} + +/// The uzumaki hint label: the verbatim text, with the binding's concrete type in +/// parentheses when the declaration named one. +fn uzumaki_label(declared: Option<&TypeInfo>) -> String { + match declared { + Some(ty) => format!("{UZUMAKI_INLAY} ({})", render_type(ty)), + None => UZUMAKI_INLAY.to_string(), + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::cast_possible_truncation)] + + use super::{InlayHint, InlayHintKind}; + use crate::TextRange; + use crate::nondet_docs::{ + ASSUME_INLAY, EXISTS_INLAY, FORALL_INLAY, UNIQUE_INLAY, UZUMAKI_INLAY, + }; + use crate::test_utils::{at, nth, single}; + + const NONDET: &str = "fn f() {\n\ + forall { let a: i32 = @; assert(a == a); }\n\ + exists { let b: i32 = @; assert(b == b); }\n\ + unique { assert(true); }\n\ + assume { assert(true); }\n\ +}"; + + fn hints(source: &str, range: Option) -> Vec { + let (mut host, path) = single(source); + host.analysis().inlay_hints(&path, range) + } + + fn nondet_hint<'a>(hints: &'a [InlayHint], keyword: &str) -> &'a InlayHint { + let offset = at(NONDET, keyword) + keyword.len() as u32; + hints + .iter() + .find(|hint| hint.kind == InlayHintKind::NonDetBlock && hint.offset == offset) + .unwrap_or_else(|| panic!("a hint after `{keyword}`")) + } + + #[test] + fn every_block_kind_gets_a_hint_after_its_keyword() { + let hints = hints(NONDET, None); + for (keyword, label) in [ + ("forall", FORALL_INLAY), + ("exists", EXISTS_INLAY), + ("unique", UNIQUE_INLAY), + ("assume", ASSUME_INLAY), + ] { + assert_eq!(nondet_hint(&hints, keyword).label, label); + } + } + + #[test] + fn each_uzumaki_gets_a_typed_hint_after_the_at() { + let hints = hints(NONDET, None); + let mut uzumaki: Vec<&InlayHint> = hints + .iter() + .filter(|hint| hint.kind == InlayHintKind::Uzumaki) + .collect(); + uzumaki.sort_by_key(|hint| hint.offset); + assert_eq!(uzumaki.len(), 2, "one per `@`"); + for hint in &uzumaki { + assert_eq!(hint.label, format!("{UZUMAKI_INLAY} (i32)")); + } + // Each hint sits just past its own `@`. Asserting both offsets (not only + // the first) catches a regression that collapses the second uzumaki hint + // onto the first's position. + let offsets: Vec = uzumaki.iter().map(|hint| hint.offset).collect(); + assert_eq!( + offsets, + vec![nth(NONDET, "@", 0) + 1, nth(NONDET, "@", 1) + 1] + ); + } + + #[test] + fn hints_are_ordered_by_offset() { + let hints = hints(NONDET, None); + let offsets: Vec = hints.iter().map(|hint| hint.offset).collect(); + let mut sorted = offsets.clone(); + sorted.sort_unstable(); + assert_eq!(offsets, sorted); + } + + #[test] + fn a_range_filter_keeps_only_hints_inside_it() { + let start = at(NONDET, "forall"); + let range = TextRange { + start, + end: start + "forall".len() as u32 + 1, + }; + let filtered = hints(NONDET, Some(range)); + assert_eq!(filtered.len(), 1); + assert_eq!(filtered[0].kind, InlayHintKind::NonDetBlock); + assert_eq!(filtered[0].label, FORALL_INLAY); + } + + #[test] + fn an_uzumaki_without_a_typed_binding_omits_the_type() { + // The second `@` is not the value of a typed `let`, so its hint is the + // bare verbatim text with no parenthetical type. + let source = "fn f() { forall { let x: i32 = @; assert(@ == x); } }"; + let hints = hints(source, None); + let bare = hints + .iter() + .filter(|hint| hint.kind == InlayHintKind::Uzumaki) + .find(|hint| hint.label == UZUMAKI_INLAY); + assert!( + bare.is_some(), + "a standalone `@` gets the untyped label: {hints:?}" + ); + } + + #[test] + fn the_range_filter_is_half_open() { + // A hint exactly at `range.start` is kept; one exactly at `range.end` is + // excluded. Build a window whose start is the forall hint's offset and + // whose end is the first uzumaki hint's offset. + let all = hints(NONDET, None); + let forall_offset = at(NONDET, "forall") + "forall".len() as u32; + let uzumaki_offset = all + .iter() + .find(|hint| hint.kind == InlayHintKind::Uzumaki) + .expect("a uzumaki hint") + .offset; + let window = TextRange { + start: forall_offset, + end: uzumaki_offset, + }; + let filtered = hints(NONDET, Some(window)); + assert!( + filtered.iter().any(|hint| hint.offset == forall_offset), + "the hint at range.start is kept" + ); + assert!( + filtered.iter().all(|hint| hint.offset != uzumaki_offset), + "the hint at range.end is excluded" + ); + } + + #[test] + fn a_forall_marked_function_body_gets_a_header_hint() { + // The non-det kind lives on the body block even when it marks the whole + // function signature (`fn f() forall { … }`), so the hint still appears. + let source = "fn prop(a: i32) forall { assert(a == a); }"; + let hints = hints(source, None); + assert_eq!(hints.len(), 1); + assert_eq!(hints[0].kind, InlayHintKind::NonDetBlock); + assert_eq!(hints[0].label, FORALL_INLAY); + assert_eq!( + hints[0].offset, + at(source, "forall") + "forall".len() as u32 + ); + } + + #[test] + fn a_file_without_nondet_has_no_hints() { + assert!(hints("fn f() -> i32 { return 1; }", None).is_empty()); + } +} diff --git a/ide/ide/src/lib.rs b/ide/ide/src/lib.rs index e69de29b..15cad4be 100644 --- a/ide/ide/src/lib.rs +++ b/ide/ide/src/lib.rs @@ -0,0 +1,258 @@ +#![warn(clippy::pedantic)] +//! The feature layer of the Inference IDE stack: plain-old-data answers to the +//! questions an editor asks about a document. +//! +//! [`AnalysisHost`] owns the open-document state (delegating to `ide-db`'s +//! `RootDatabase`); [`Analysis`] borrows it to answer feature queries — +//! diagnostics, document symbols, hover, goto-definition, completions, and inlay +//! hints. Every result is a plain struct in editor terminology +//! ([`Diagnostic`], [`DocumentSymbol`], [`Hover`], [`NavigationTarget`], +//! [`CompletionItem`], [`InlayHint`]); no compiler type crosses this boundary, so +//! the protocol layer above (`apps/lsp`) maps these straight onto LSP responses. +//! +//! # Coordinates +//! +//! Positions in and out of this crate are **byte offsets** into a document's +//! current text, and ranges are byte ranges. The protocol layer converts them to +//! LSP line/character with the [`LineIndex`] this crate exposes. The open +//! document is addressed by its path; the entry file's module path is the empty +//! slice, which is how a query reaches the document it was asked about. +//! +//! # Single document, single thread +//! +//! Each open file is analyzed as its own project entry (its import closure +//! resolved through the overlay-then-disk loader in `ide-db`), and the resulting +//! analysis answers every query for that document — including goto-definition +//! into an imported file, whose [`NavigationTarget`] carries that file's real path +//! and ranges in its own coordinates. A query borrows the database mutably because +//! the analysis is computed lazily and memoized on first use; the LSP main loop is +//! single-threaded, so this is exactly the access pattern it needs. + +mod completions; +mod diagnostics; +mod document_symbols; +mod goto_definition; +mod hover; +mod inlay_hints; +mod nondet_docs; +mod syntax; +mod type_render; + +#[cfg(test)] +mod test_utils; + +use std::path::Path; +use std::sync::Arc; + +use inference_ide_db::RootDatabase; + +pub use completions::{CompletionItem, CompletionItemKind}; +pub use diagnostics::{Diagnostic, Severity}; +pub use document_symbols::{DocumentSymbol, SymbolKind}; +pub use goto_definition::NavigationTarget; +pub use hover::Hover; +pub use inlay_hints::{InlayHint, InlayHintKind}; + +// Re-export the position primitives the protocol layer needs to turn byte +// offsets into LSP positions, so it depends on `inference-ide` alone. The API is +// path-addressed, so the file-id PODs are intentionally not surfaced here. +pub use inference_ide_db::{LineCol, LineIndex, TextRange}; + +/// Owns the editor's open documents and the analyses derived from them. +/// +/// Construct with [`AnalysisHost::default`], mirror the editor's lifecycle with +/// [`open_document`](Self::open_document) / [`change_document`](Self::change_document) +/// / [`close_document`](Self::close_document), then take an [`Analysis`] to answer +/// feature queries. +#[derive(Default)] +pub struct AnalysisHost { + db: RootDatabase, +} + +impl AnalysisHost { + /// Records `text` as the current contents of `path` (an editor `didOpen`). + pub fn open_document(&mut self, path: &Path, text: impl Into>) { + self.db.open_document(path, text); + } + + /// Replaces the current contents of the open document `path` (a `didChange`). + pub fn change_document(&mut self, path: &Path, text: impl Into>) { + self.db.change_document(path, text); + } + + /// Drops the in-memory contents of `path` (a `didClose`); later analyses read + /// it from disk again. + pub fn close_document(&mut self, path: &Path) { + self.db.close_document(path); + } + + /// Borrows the host to answer feature queries. + #[must_use = "an Analysis does nothing until a query method is called"] + pub fn analysis(&mut self) -> Analysis<'_> { + Analysis { db: &mut self.db } + } +} + +/// A borrowed view over the host that answers feature queries for a document. +/// +/// Each method names its document by path and takes `&mut self` because the +/// document's analysis is computed lazily and cached on first use. +pub struct Analysis<'a> { + db: &'a mut RootDatabase, +} + +impl Analysis<'_> { + /// The diagnostics for the open document `path`: syntax, import, type, and + /// analysis-rule findings that belong to it. + #[must_use = "the diagnostics are the reason to call this"] + pub fn diagnostics(&mut self, path: &Path) -> Vec { + diagnostics::diagnostics(self.db.analysis(path)) + } + + /// The definition outline of the document `path`. + #[must_use = "the symbols are the reason to call this"] + pub fn document_symbols(&mut self, path: &Path) -> Vec { + document_symbols::document_symbols(self.db.analysis(path)) + } + + /// The hover for byte `offset` in the document `path`, if anything is there. + #[must_use = "the hover is the reason to call this"] + pub fn hover(&mut self, path: &Path, offset: u32) -> Option { + hover::hover(self.db.analysis(path), offset) + } + + /// The definition(s) of the identifier at byte `offset` in `path`, if any. + #[must_use = "the navigation targets are the reason to call this"] + pub fn goto_definition(&mut self, path: &Path, offset: u32) -> Option> { + goto_definition::goto_definition(self.db.analysis(path), offset) + } + + /// The completions for byte `offset` in the document `path`. + #[must_use = "the completions are the reason to call this"] + pub fn completions(&mut self, path: &Path, offset: u32) -> Vec { + completions::completions(self.db.analysis(path), offset) + } + + /// The non-det inlay hints for `path`, optionally clipped to `range`. + #[must_use = "the inlay hints are the reason to call this"] + pub fn inlay_hints(&mut self, path: &Path, range: Option) -> Vec { + inlay_hints::inlay_hints(self.db.analysis(path), range) + } + + /// The line index of the document `path`, for byte-offset ↔ line/column + /// conversion; `None` when the document is not analyzable. + #[must_use = "the line index is the reason to call this"] + pub fn line_index(&mut self, path: &Path) -> Option { + self.db.analysis(path).line_index(&[]).cloned() + } + + /// The line index of `target` as it appears in `document`'s analysis closure, + /// or `None` when `target` is not part of that closure. + /// + /// A cross-file [`NavigationTarget`] names a file in `document`'s import + /// closure; converting its byte ranges to LSP positions needs that file's line + /// index. This reuses `document`'s already-computed analysis rather than + /// analyzing `target` as its own entry, which would both duplicate work and, + /// for a non-entry file, resolve a different closure. + #[must_use = "the line index is the reason to call this"] + pub fn closure_line_index(&mut self, document: &Path, target: &Path) -> Option { + let analysis = self.db.analysis(document); + analysis.arena().source_files().find_map(|source_file| { + let closure_file = analysis.file(&source_file.module_path)?; + (closure_file.path() == target).then(|| closure_file.line_index().clone()) + }) + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::cast_possible_truncation)] + + use std::path::PathBuf; + + use crate::{AnalysisHost, LineCol}; + + fn path() -> PathBuf { + PathBuf::from("/inf-test/main.inf") + } + + #[test] + fn open_then_query_answers_features() { + let mut host = AnalysisHost::default(); + let source = "fn add(a: i32, b: i32) -> i32 { return a + b; }"; + host.open_document(&path(), source); + let mut analysis = host.analysis(); + assert!(analysis.diagnostics(&path()).is_empty()); + assert_eq!(analysis.document_symbols(&path()).len(), 1); + let offset = source.find("add").expect("name present") as u32; + assert!(analysis.hover(&path(), offset).is_some()); + } + + #[test] + fn a_change_reanalyzes_and_clears_diagnostics() { + let mut host = AnalysisHost::default(); + host.open_document(&path(), "fn f() -> i32 { return x; }"); + assert!(!host.analysis().diagnostics(&path()).is_empty()); + host.change_document(&path(), "fn f() -> i32 { return 1; }"); + assert!(host.analysis().diagnostics(&path()).is_empty()); + } + + #[test] + fn close_does_not_panic_and_leaves_the_host_usable() { + let mut host = AnalysisHost::default(); + host.open_document(&path(), "fn f() -> i32 { return 1; }"); + let _ = host.analysis().diagnostics(&path()); + host.close_document(&path()); + // Re-opening restores a clean analysis. + host.open_document(&path(), "fn g() -> i32 { return 2; }"); + assert!(host.analysis().diagnostics(&path()).is_empty()); + } + + #[test] + fn line_index_converts_offsets_to_positions() { + let mut host = AnalysisHost::default(); + let source = "fn a() {}\nfn b() {}"; + host.open_document(&path(), source); + let index = host.analysis().line_index(&path()).expect("a line index"); + let offset = source.find('b').expect("b present") as u32; + assert_eq!( + index.line_col(offset), + LineCol { + line: 1, + character: 3 + } + ); + } + + #[test] + fn closure_line_index_serves_an_imported_file_without_re_analysis() { + let mut host = AnalysisHost::default(); + let lib_path = PathBuf::from("/inf-test/lib.inf"); + let lib = "pub fn helper() -> i32 { return 7; }"; + host.open_document(&lib_path, lib); + host.open_document( + &path(), + "use lib;\nfn main() -> i32 { return lib::helper(); }", + ); + + let index = host + .analysis() + .closure_line_index(&path(), &lib_path) + .expect("the imported file is in the closure"); + let offset = lib.find("helper").expect("helper present") as u32; + assert_eq!( + index.line_col(offset), + LineCol { + line: 0, + character: 7 + } + ); + + // A path outside the closure yields nothing. + assert!( + host.analysis() + .closure_line_index(&path(), &PathBuf::from("/inf-test/nope.inf")) + .is_none() + ); + } +} diff --git a/ide/ide/src/nondet_docs.rs b/ide/ide/src/nondet_docs.rs new file mode 100644 index 00000000..a4c9269e --- /dev/null +++ b/ide/ide/src/nondet_docs.rs @@ -0,0 +1,211 @@ +//! Verbatim hover documentation and inlay-hint texts for the non-deterministic +//! constructs (`forall` / `exists` / `unique` / `assume` / `@`). +//! +//! These strings are the mental-model aid requested in issue #33: hovering a +//! non-det keyword explains its proof obligation, and an inlay hint restates it +//! inline at the block header. The content is authored in +//! `.claude/docs/issues/33/nondet_texts.md` and reproduced here **verbatim** — +//! this module is the single in-code source of truth so the feature layer never +//! parses markdown at runtime. +//! +//! The hover payloads are markdown (with a fenced `inference` example); the inlay +//! texts are one short line each, all beginning with the `▸ ` non-det marker and +//! kept `<= 60` chars, per the style convention in the source document. + +use inference_ast::nodes::BlockKind; + +/// Hover markdown for a `forall` block or `forall`-marked function body. +pub(crate) const FORALL_HOVER: &str = r"**`forall` — every path must succeed** + +A `forall` block (or a `forall`-marked function body) fans the computation out +into one path per possible value of every `@` inside it, and requires **all** of +them to reach the end successfully. If even a single path can fail an `assert`, +the block fails. Execution continues past the block only when the property held +for *every* combination of values. + +**Verification meaning.** Lowers to the `BI_forall` quantifier constructor in the +generated Rocq. The prover's obligation is universal: show the block's assertions +hold on **every** path — for all values the inner `@`s could take. One +counterexample discharges nothing; it sinks the proof. + +```inference +fn add_is_commutative(a: i32, b: i32) forall { + // holds for all a, all b + assert(add(a, b) == add(b, a)); +} +```"; + +/// Hover markdown for an `exists` block. +pub(crate) const EXISTS_HOVER: &str = r"**`exists` — at least one path must succeed** + +An `exists` block fans the computation out the same way `forall` does, but only +requires **one** path to reach the end successfully. It states that a solution is +*possible*: some assignment of the inner `@` values makes the block hold. + +**Verification meaning.** Lowers to the `BI_exists` quantifier constructor. The +obligation is existential: exhibit **one** witness path that succeeds. A single +working assignment of the `@` values discharges it — the other paths are free to +fail. + +```inference +exists { + let n: i32 = @; + // proves a solution exists: some n satisfies n * n == 25 + assume { assert(n * n == 25); } +} +```"; + +/// Hover markdown for a `unique` block. +pub(crate) const UNIQUE_HOVER: &str = r#"**`unique` — exactly one path must succeed** + +A `unique` block requires **exactly one** path to reach the end successfully — no +more, no fewer. It states that a solution both *exists* and is *the only one*. + +**Verification meaning.** Conceptually the counting quantifier "there is exactly +one". The obligation has two halves: existence (at least one path succeeds) **and** +uniqueness (no two distinct paths both succeed). Proving only that a solution +exists is not enough — you must also rule out a second one. + +```inference +unique { + let n: i32 = @; + // exactly one n survives the filter: n == 4 + assume { assert(n * 3 == 12); } +} +```"#; + +/// Hover markdown for an `assume` block. +pub(crate) const ASSUME_HOVER: &str = r"**`assume` — keep only the paths where this holds** + +An `assume` block is a **filter**, not a quantifier. It drops every path on which +its body does not succeed and lets the survivors continue. Use it to state a +precondition: the assertions *after* the `assume` only have to hold on the paths +that made it through. + +**Verification meaning.** Lowers to the `BI_assume` constructor (which keeps its +block type). It adds no goal of its own — instead it introduces its condition as a +**hypothesis** the prover may rely on for the rest of the enclosing block, and +narrows what a surrounding `forall`/`exists` has to cover. + +```inference +forall { + let x: i32 = @; + assume { assert(x > 0); } // keep only the positive paths + assert(x - 1 >= 0); // now provable, given x > 0 +} +```"; + +/// Hover markdown for the `@` (uzumaki) value. +pub(crate) const UZUMAKI_HOVER: &str = r"**`@` (uzumaki) — every value of its type, at once** + +`@` is a value that simultaneously stands for **all** values of the type it is +assigned to. It is *not* a random pick: writing `let x: i32 = @;` makes `x` range +over every `i32`, and the block around it splits into one path per value. `@` is +only meaningful inside a non-det block (`forall` / `exists` / `unique` / `assume`), +which is what quantifies over the values it produces. + +**Verification meaning.** Lowers to `BI_uzumaki_num` (`T_i32` / `T_i64`). It is the +source of the quantified variable the surrounding block ranges over — universally +under `forall`, existentially under `exists`. + +```inference +forall { + let x: i32 = @; // x stands for every i32 value + assert(x * 0 == 0); // must hold for all of them +} +```"; + +/// Inlay-hint text shown at the end of a `forall` block header. +pub(crate) const FORALL_INLAY: &str = "▸ every path must succeed"; +/// Inlay-hint text shown at the end of an `exists` block header. +pub(crate) const EXISTS_INLAY: &str = "▸ at least one path must succeed"; +/// Inlay-hint text shown at the end of a `unique` block header. +pub(crate) const UNIQUE_INLAY: &str = "▸ exactly one path must succeed"; +/// Inlay-hint text shown at the end of an `assume` block header. +pub(crate) const ASSUME_INLAY: &str = "▸ keeps only paths where this holds"; +/// Inlay-hint text shown just after a `= @` uzumaki binding. +pub(crate) const UZUMAKI_INLAY: &str = "▸ ranges over every value of its type"; + +/// The source keyword that opens a non-det block, or `None` for a regular block. +/// +/// A non-det block's source range begins at this keyword, so its byte length is +/// what separates the keyword span (for keyword hover) from the block header end +/// (for the inlay-hint anchor). +#[must_use] +pub(crate) fn block_keyword(kind: BlockKind) -> Option<&'static str> { + match kind { + BlockKind::Forall => Some("forall"), + BlockKind::Exists => Some("exists"), + BlockKind::Unique => Some("unique"), + BlockKind::Assume => Some("assume"), + BlockKind::Regular => None, + } +} + +/// The hover markdown for a non-det block kind, or `None` for a regular block. +#[must_use] +pub(crate) fn block_hover(kind: BlockKind) -> Option<&'static str> { + match kind { + BlockKind::Forall => Some(FORALL_HOVER), + BlockKind::Exists => Some(EXISTS_HOVER), + BlockKind::Unique => Some(UNIQUE_HOVER), + BlockKind::Assume => Some(ASSUME_HOVER), + BlockKind::Regular => None, + } +} + +/// The inlay-hint text for a non-det block kind, or `None` for a regular block. +#[must_use] +pub(crate) fn block_inlay(kind: BlockKind) -> Option<&'static str> { + match kind { + BlockKind::Forall => Some(FORALL_INLAY), + BlockKind::Exists => Some(EXISTS_INLAY), + BlockKind::Unique => Some(UNIQUE_INLAY), + BlockKind::Assume => Some(ASSUME_INLAY), + BlockKind::Regular => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_nondet_kind_maps_to_keyword_hover_and_inlay() { + for kind in [ + BlockKind::Forall, + BlockKind::Exists, + BlockKind::Unique, + BlockKind::Assume, + ] { + let keyword = block_keyword(kind).expect("non-det kind has a keyword"); + assert_eq!(keyword.len(), 6, "every non-det keyword is six bytes"); + assert!(block_hover(kind).is_some()); + assert!(block_inlay(kind).unwrap().starts_with("▸ ")); + } + } + + #[test] + fn regular_block_has_no_nondet_content() { + assert!(block_keyword(BlockKind::Regular).is_none()); + assert!(block_hover(BlockKind::Regular).is_none()); + assert!(block_inlay(BlockKind::Regular).is_none()); + } + + #[test] + fn inlay_texts_are_within_the_length_budget() { + for text in [ + FORALL_INLAY, + EXISTS_INLAY, + UNIQUE_INLAY, + ASSUME_INLAY, + UZUMAKI_INLAY, + ] { + assert!(text.starts_with("▸ "), "inlay marker is the black triangle"); + assert!( + text.chars().count() <= 60, + "inlay text stays under 60 chars" + ); + } + } +} diff --git a/ide/ide/src/syntax.rs b/ide/ide/src/syntax.rs new file mode 100644 index 00000000..a7b1a63f --- /dev/null +++ b/ide/ide/src/syntax.rs @@ -0,0 +1,963 @@ +//! Shared AST-navigation helpers scoped to a single source file. +//! +//! Feature queries need two things the lower layers do not expose directly: a +//! pre-order walk of every node in one file (for enumerating non-det blocks and +//! uzumaki expressions), and small primitives for reading a definition's name, +//! signature, and by-name lookup. +//! +//! # Why the child enumeration is reproduced here +//! +//! Byte offsets are per-file-local in the merged multi-file arena, so +//! `AstArena::find_source_file_for_node` cannot attribute a `Block` or `Expr` to +//! a file (it answers only for `Def`s and single-file arenas). Any per-file node +//! enumeration must therefore descend structurally from that file's own +//! definitions, exactly as `ide-db`'s hit-test does. That descent is currently +//! private to `ide-db`, so this module keeps its own copy. The exhaustive matches +//! make a *new* AST variant a compile error in both copies, but a semantic edit +//! to one would not error the other; the natural fix is to expose the descent +//! from `ide-db` (its canonical home) and delete this copy — a follow-up left out +//! of this crate's scope. + +use inference_ast::arena::AstArena; +use inference_ast::ids::{DefId, ExprId, IdentId, NodeId, SourceFileId, StmtId, TypeId}; +use inference_ast::nodes::{ + ArgData, ArgKind, Def, Directive, Expr, Location, Stmt, TypeNode, Visibility, +}; +use inference_ide_db::{FileAnalysis, NodeHit, TextRange, file_defs}; + +/// Converts a compiler [`Location`] to the byte [`TextRange`] the feature API +/// speaks. Both types are foreign, so this free helper stands in for the +/// `From` impl the orphan rule forbids. +#[must_use] +pub(crate) fn text_range(location: Location) -> TextRange { + TextRange { + start: location.offset_start, + end: location.offset_end, + } +} + +/// Visits every node in `file` in pre-order (a definition before its children), +/// scoped to that file's own definition tree so it never crosses into another +/// file's per-file-local offsets. +pub(crate) fn walk_file(arena: &AstArena, file: SourceFileId, visit: &mut impl FnMut(NodeId)) { + for &def in &arena[file].defs { + walk_node(arena, NodeId::Def(def), visit); + } +} + +fn walk_node(arena: &AstArena, node: NodeId, visit: &mut impl FnMut(NodeId)) { + visit(node); + for child in children_of(arena, node) { + walk_node(arena, child, visit); + } +} + +/// The direct child nodes of `node`. Mirrors `ide-db`'s hit-test descent so a +/// walk reaches every node a position query could. +fn children_of(arena: &AstArena, node: NodeId) -> Vec { + match node { + NodeId::Def(id) => def_children(arena, id), + NodeId::Stmt(id) => stmt_children(arena, id), + NodeId::Expr(id) => expr_children(arena, id), + NodeId::Type(id) => type_children(arena, id), + NodeId::Block(id) => arena[id].stmts.iter().map(|&s| NodeId::Stmt(s)).collect(), + NodeId::Ident(_) | NodeId::SourceFile(_) => Vec::new(), + } +} + +fn def_children(arena: &AstArena, id: DefId) -> Vec { + let mut out = Vec::new(); + match &arena[id].kind { + Def::Function { + name, + args, + returns, + body, + .. + } => { + out.push(NodeId::Ident(*name)); + arg_children(args, &mut out); + if let Some(ret) = returns { + out.push(NodeId::Type(*ret)); + } + out.push(NodeId::Block(*body)); + } + Def::ExternFunction { + name, + args, + returns, + .. + } => { + out.push(NodeId::Ident(*name)); + arg_children(args, &mut out); + if let Some(ret) = returns { + out.push(NodeId::Type(*ret)); + } + } + Def::Struct { + name, + fields, + methods, + .. + } => { + out.push(NodeId::Ident(*name)); + for field in fields { + out.push(NodeId::Ident(field.name)); + out.push(NodeId::Type(field.ty)); + } + for &method in methods { + out.push(NodeId::Def(method)); + } + } + Def::Enum { name, variants, .. } => { + out.push(NodeId::Ident(*name)); + for &variant in variants { + out.push(NodeId::Ident(variant)); + } + } + Def::Spec { name, defs, .. } => { + out.push(NodeId::Ident(*name)); + for &nested in defs { + out.push(NodeId::Def(nested)); + } + } + Def::Constant { + name, ty, value, .. + } => { + out.push(NodeId::Ident(*name)); + out.push(NodeId::Type(*ty)); + out.push(NodeId::Expr(*value)); + } + Def::TypeAlias { name, ty, .. } => { + out.push(NodeId::Ident(*name)); + out.push(NodeId::Type(*ty)); + } + } + out +} + +fn arg_children(args: &[ArgData], out: &mut Vec) { + for arg in args { + match &arg.kind { + ArgKind::Named { name, ty, .. } => { + out.push(NodeId::Ident(*name)); + out.push(NodeId::Type(*ty)); + } + ArgKind::Ignored { ty } | ArgKind::TypeOnly(ty) => out.push(NodeId::Type(*ty)), + ArgKind::SelfRef { .. } => {} + } + } +} + +fn stmt_children(arena: &AstArena, id: StmtId) -> Vec { + let mut out = Vec::new(); + match &arena[id].kind { + Stmt::Block(block) => out.push(NodeId::Block(*block)), + Stmt::Expr(expr) | Stmt::Return { expr } | Stmt::Assert { expr } => { + out.push(NodeId::Expr(*expr)); + } + Stmt::Assign { left, right } => { + out.push(NodeId::Expr(*left)); + out.push(NodeId::Expr(*right)); + } + Stmt::Loop { condition, body } => { + if let Some(condition) = condition { + out.push(NodeId::Expr(*condition)); + } + out.push(NodeId::Block(*body)); + } + Stmt::If { + condition, + then_block, + else_block, + } => { + out.push(NodeId::Expr(*condition)); + out.push(NodeId::Block(*then_block)); + if let Some(else_block) = else_block { + out.push(NodeId::Block(*else_block)); + } + } + Stmt::VarDef { + name, ty, value, .. + } => { + out.push(NodeId::Ident(*name)); + out.push(NodeId::Type(*ty)); + if let Some(value) = value { + out.push(NodeId::Expr(*value)); + } + } + Stmt::TypeDef { name, ty } => { + out.push(NodeId::Ident(*name)); + out.push(NodeId::Type(*ty)); + } + Stmt::ConstDef(def) => out.push(NodeId::Def(*def)), + Stmt::Break => {} + } + out +} + +fn expr_children(arena: &AstArena, id: ExprId) -> Vec { + let mut out = Vec::new(); + match &arena[id].kind { + Expr::Binary { left, right, .. } => { + out.push(NodeId::Expr(*left)); + out.push(NodeId::Expr(*right)); + } + Expr::PrefixUnary { expr, .. } | Expr::Parenthesized { expr } => { + out.push(NodeId::Expr(*expr)); + } + Expr::FunctionCall { function, args, .. } => { + out.push(NodeId::Expr(*function)); + for (name, arg) in args { + if let Some(name) = name { + out.push(NodeId::Ident(*name)); + } + out.push(NodeId::Expr(*arg)); + } + } + Expr::ArrayIndexAccess { array, index } => { + out.push(NodeId::Expr(*array)); + out.push(NodeId::Expr(*index)); + } + Expr::MemberAccess { expr, name } | Expr::TypeMemberAccess { expr, name } => { + out.push(NodeId::Expr(*expr)); + out.push(NodeId::Ident(*name)); + } + Expr::StructLiteral { name, fields } => { + out.push(NodeId::Ident(*name)); + for (field, value) in fields { + out.push(NodeId::Ident(*field)); + out.push(NodeId::Expr(*value)); + } + } + Expr::Identifier(ident) => out.push(NodeId::Ident(*ident)), + Expr::ArrayLiteral { elements } => { + for &element in elements { + out.push(NodeId::Expr(element)); + } + } + Expr::Type(ty) => out.push(NodeId::Type(*ty)), + Expr::NumberLiteral { .. } + | Expr::BoolLiteral { .. } + | Expr::StringLiteral { .. } + | Expr::UnitLiteral + | Expr::Uzumaki => {} + } + out +} + +fn type_children(arena: &AstArena, id: TypeId) -> Vec { + let mut out = Vec::new(); + match &arena[id].kind { + TypeNode::Simple(_) => {} + TypeNode::Array { element, size } => { + out.push(NodeId::Type(*element)); + out.push(NodeId::Expr(*size)); + } + TypeNode::Generic { base, params } => { + out.push(NodeId::Ident(*base)); + for ¶m in params { + out.push(NodeId::Ident(param)); + } + } + TypeNode::Function { params, ret } => { + for ¶m in params { + out.push(NodeId::Type(param)); + } + if let Some(ret) = ret { + out.push(NodeId::Type(*ret)); + } + } + TypeNode::QualifiedName { qualifier, name } => { + out.push(NodeId::Ident(*qualifier)); + out.push(NodeId::Ident(*name)); + } + TypeNode::Qualified { qualifier, name } => { + for &segment in qualifier { + out.push(NodeId::Ident(segment)); + } + out.push(NodeId::Ident(*name)); + } + TypeNode::Custom(ident) => out.push(NodeId::Ident(*ident)), + } + out +} + +/// The name identifier of a definition, whatever its kind. +#[must_use] +pub(crate) fn def_name_ident(arena: &AstArena, def: DefId) -> IdentId { + match &arena[def].kind { + Def::Function { name, .. } + | Def::ExternFunction { name, .. } + | Def::Struct { name, .. } + | Def::Enum { name, .. } + | Def::Spec { name, .. } + | Def::Constant { name, .. } + | Def::TypeAlias { name, .. } => *name, + } +} + +/// The first top-level or nested definition in `file` named `name`, or `None`. +/// +/// The search covers struct methods and spec-nested defs (via `file_defs`), so a +/// method or a spec-inner function is found by its bare name. `file_defs` is a +/// pre-order flatten with no scope discriminator, so when a top-level and a +/// spec-inner definition share a name the first in source order wins; goto/hover +/// can then land on the wrong same-named definition. This is an IDE-convenience +/// mis-navigation only — never a compile or codegen path — and is accepted in v1. +#[must_use] +pub(crate) fn find_def_by_name(arena: &AstArena, file: SourceFileId, name: &str) -> Option { + file_defs(arena, file) + .into_iter() + .find(|&def| arena.def_name(def) == name) +} + +/// A method named `name` defined directly on the struct `struct_def`, or `None`. +#[must_use] +pub(crate) fn find_method(arena: &AstArena, struct_def: DefId, name: &str) -> Option { + let Def::Struct { methods, .. } = &arena[struct_def].kind else { + return None; + }; + methods + .iter() + .copied() + .find(|&method| arena.def_name(method) == name) +} + +/// The one-line signature of a definition: its source up to the opening brace (or +/// the whole declaration when it has none), with surrounding whitespace trimmed. +/// +/// `file` must be the definition's own file, because the location's offsets are +/// local to it. +#[must_use] +pub(crate) fn def_signature(arena: &AstArena, file: SourceFileId, def: DefId) -> Option { + let source = arena.node_source_in_file(file, arena[def].location)?; + let head = source.split('{').next().unwrap_or(source); + Some(head.split_whitespace().collect::>().join(" ")) +} + +/// Whether a method takes a `self` receiver (an instance method, reachable via +/// `receiver.method()`), as opposed to an associated function. +#[must_use] +pub(crate) fn method_has_self(arena: &AstArena, method: DefId) -> bool { + let Def::Function { args, .. } = &arena[method].kind else { + return false; + }; + args.iter() + .any(|arg| matches!(arg.kind, ArgKind::SelfRef { .. })) +} + +/// Whether a definition is `pub`, i.e. visible to importing files. +#[must_use] +pub(crate) fn def_is_public(arena: &AstArena, def: DefId) -> bool { + let vis = match &arena[def].kind { + Def::Function { vis, .. } + | Def::ExternFunction { vis, .. } + | Def::Struct { vis, .. } + | Def::Enum { vis, .. } + | Def::Spec { vis, .. } + | Def::Constant { vis, .. } + | Def::TypeAlias { vis, .. } => vis, + }; + matches!(vis, Visibility::Public) +} + +/// The innermost function definition enclosing a hit, or `None` when the hit is +/// not inside any function body (e.g. a top-level type annotation). +#[must_use] +pub(crate) fn enclosing_function(arena: &AstArena, hit: &NodeHit) -> Option { + hit.ancestors.iter().rev().find_map(|&node| match node { + NodeId::Def(def) if matches!(arena[def].kind, Def::Function { .. }) => Some(def), + _ => None, + }) +} + +/// Whether `callee` is the function position of the `FunctionCall` named by +/// `grandparent` — the test that tells a call target apart from a plain value use +/// of the same identifier. +#[must_use] +pub(crate) fn is_call_callee( + arena: &AstArena, + grandparent: Option, + callee: ExprId, +) -> bool { + matches!( + grandparent, + Some(NodeId::Expr(call)) if matches!( + &arena[call].kind, + Expr::FunctionCall { function, .. } if *function == callee + ) + ) +} + +/// The source-root-relative module paths the file `entry` imports with a `use` +/// directive, each as its `::`-split segments. +#[must_use] +pub(crate) fn imported_module_paths(arena: &AstArena, entry: SourceFileId) -> Vec> { + arena[entry] + .directives + .iter() + .map(|directive| { + let Directive::Use(use_directive) = directive; + use_directive + .segments + .iter() + .map(|&segment| arena.ident_name(segment).to_string()) + .collect() + }) + .collect() +} + +/// The `let` bindings in scope at `offset`: every `VarDef` that is a direct +/// statement of a block enclosing the offset — a block on the hit's ancestor +/// chain, or the covering node itself when the offset falls in a block's own gap +/// — and whose name ends at or before the offset. +/// +/// Scoping is lexical: a binding in a sibling block that has already closed is +/// not in scope (its block is absent from the ancestor chain), and one declared +/// later in an enclosing block is not yet visible (its name ends after the +/// offset). Inference forbids shadowing, so a name resolves to at most one +/// binding here. Sharing this walk keeps goto/hover and completions in agreement +/// on what is in scope. +#[must_use] +pub(crate) fn in_scope_locals(arena: &AstArena, hit: &NodeHit, offset: u32) -> Vec { + let mut locals = Vec::new(); + for &node in hit.ancestors.iter().chain(std::iter::once(&hit.node)) { + let NodeId::Block(block) = node else { + continue; + }; + for &stmt in &arena[block].stmts { + if let Stmt::VarDef { name, .. } = &arena[stmt].kind + && arena[*name].location.offset_end <= offset + { + locals.push(stmt); + } + } + } + locals +} + +/// Resolves the `::`-qualifier segments of a cross-module reference (the leading +/// `lib` of `lib::T`, or `lib::geom` of `lib::geom::Point`) to the +/// [`SourceFileId`] of the module they name, as imported by `entry`. +/// +/// A qualifier's head names an imported module by its binding — the last segment +/// of its `use` path (`use lib::geom;` binds `geom`) — and any further segments +/// descend into submodules. A qualifier that is already a full +/// source-root-relative path resolves directly as a fallback. +#[must_use] +pub(crate) fn resolve_qualified_module( + file: &FileAnalysis, + entry: SourceFileId, + qualifier: &[IdentId], +) -> Option { + let arena = file.arena(); + let segments: Vec = qualifier + .iter() + .map(|&id| arena.ident_name(id).to_string()) + .collect(); + let (head, rest) = segments.split_first()?; + for import in imported_module_paths(arena, entry) { + if import.last().map(String::as_str) == Some(head.as_str()) { + let mut full = import.clone(); + full.extend(rest.iter().cloned()); + if let Some(sfid) = file.source_file_id(&full) { + return Some(sfid); + } + } + } + file.source_file_id(&segments) +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use inference_ast::arena::AstArena; + use inference_ast::ids::{IdentId, NodeId, SourceFileId}; + use inference_ast::nodes::{Ident, Location, SimpleTypeKind, TypeData, TypeNode}; + use inference_ide_db::{FileAnalysis, RootDatabase}; + + use super::{ + children_of, def_is_public, def_name_ident, find_def_by_name, find_method, method_has_self, + resolve_qualified_module, type_children, walk_file, + }; + use crate::test_utils::module_path; + + /// Analyzes `source` as a single entry document and hands back an owned clone + /// of the merged arena plus its entry file id. Type checking never mutates the + /// arena, so what the syntax helpers read here is exactly the parser's output. + fn analyze(source: &str) -> (AstArena, SourceFileId) { + let mut db = RootDatabase::default(); + let path = module_path("main"); + db.open_document(&path, source); + let arena = db.analysis(&path).arena().clone(); + let entry = arena + .source_file_ids() + .next() + .expect("the entry produces one source file"); + (arena, entry) + } + + /// The absolute path of a nested module file: the last segment names the file + /// (`.inf`), the earlier segments its parent directories under the test + /// root, so `["lib", "geom"]` is `/lib/geom.inf`. + fn nested_module_path(segments: &[&str]) -> PathBuf { + let (leaf, dirs) = segments.split_last().expect("at least one segment"); + let mut path = module_path("main"); + path.pop(); + for dir in dirs { + path.push(dir); + } + path.push(format!("{leaf}.inf")); + path + } + + /// The name of every identifier node a full pre-order walk of `file` visits. + /// A descent arm that fails to push one of its children drops that child's + /// name from this list, so asserting a name is present proves the arm reached + /// it. + fn walked_idents(arena: &AstArena, file: SourceFileId) -> Vec { + let mut names = Vec::new(); + walk_file(arena, file, &mut |node| { + if let NodeId::Ident(id) = node { + names.push(arena.ident_name(id).to_string()); + } + }); + names + } + + fn assert_visits(visited: &[String], expected: &[&str]) { + for want in expected { + assert!( + visited.iter().any(|name| name == want), + "the walk did not visit `{want}`; visited: {visited:?}" + ); + } + } + + /// The qualifier segments of the first `TypeNode::Qualified` reachable in the + /// entry file — the shape `resolve_qualified_module` consumes. + fn first_qualifier(file: &FileAnalysis, entry: SourceFileId) -> Vec { + let arena = file.arena(); + let mut found: Option> = None; + walk_file(arena, entry, &mut |node| { + if let NodeId::Type(ty) = node + && let TypeNode::Qualified { qualifier, .. } = &arena[ty].kind + && found.is_none() + { + found = Some(qualifier.clone()); + } + }); + found.expect("a qualified type in the entry file") + } + + // walk_file / children_of descent + + #[test] + fn walk_reaches_every_definition_kind_and_argument_form() { + // One file exercising each `Def` arm plus the argument forms: a type-only + // extern argument, an ignored argument, a `self` receiver, and named + // arguments throughout. + let source = "external fn ext_probe(WidgetArg) -> GadgetRet;\n\ +struct StructProbe { field_p: i32; fn method_p(self) -> i32 { return self.field_p; } }\n\ +enum ColorProbe { RedV, GreenV, BlueV }\n\ +spec RulesProbe { fn law_probe() -> i32 { return 1; } }\n\ +const LIMIT_PROBE: GaugeTy = REF_PROBE;\n\ +type AliasProbe = TargetTy;\n\ +fn with_ignored(_: IgnoredTy) -> i32 { return 1; }"; + let (arena, entry) = analyze(source); + let idents = walked_idents(&arena, entry); + assert_visits( + &idents, + &[ + "ext_probe", + "WidgetArg", + "GadgetRet", // extern fn: name, type-only arg, return + "StructProbe", + "field_p", + "method_p", // struct: name, field, self-method + "ColorProbe", + "RedV", + "GreenV", + "BlueV", // enum: name + variants + "RulesProbe", + "law_probe", // spec: name + nested def + "LIMIT_PROBE", + "GaugeTy", + "REF_PROBE", // constant: name, type, value + "AliasProbe", + "TargetTy", // type alias: name + aliased type + "IgnoredTy", // ignored-argument type + ], + ); + } + + #[test] + fn walk_descends_into_assign_loop_if_typedef_and_constdef_statements() { + // Each probe identifier appears in exactly one syntactic position, so its + // presence pins the arm that had to descend to reach it. + let source = "fn stmt_probes() -> i32 {\n\ +assign_l = assign_r;\n\ +loop loop_cond() { loop_body(); }\n\ +loop { plain_loop_body(); break; }\n\ +if if_cond() { then_probe(); } else { else_probe(); }\n\ +if bare_cond() { bare_then(); }\n\ +type LocalAlias = LocalTarget;\n\ +const LOCAL_K: i32 = local_const_val;\n\ +return 1;\n\ +}"; + let (arena, entry) = analyze(source); + let idents = walked_idents(&arena, entry); + assert_visits( + &idents, + &[ + "assign_l", + "assign_r", // assign: left + right + "loop_cond", + "loop_body", // loop with condition + body + "plain_loop_body", // loop without condition: body only + "if_cond", + "then_probe", + "else_probe", // if/else: condition, then, else + "bare_cond", + "bare_then", // if without an else block + "LocalAlias", + "LocalTarget", // local type def: name + aliased type + "LOCAL_K", + "local_const_val", // local const def: name + value + ], + ); + } + + #[test] + fn walk_descends_into_call_index_struct_array_and_type_expressions() { + let source = "fn expr_probes() -> i32 {\n\ +call_probe(arg_name: arg_value);\n\ +idx_array[idx_index];\n\ +let s: StructTy = StructTy { field_probe: field_value };\n\ +let arr: [i32; 2] = [elem_a, elem_b];\n\ +type_expr_probe i32';\n\ +return 1;\n\ +}"; + let (arena, entry) = analyze(source); + let idents = walked_idents(&arena, entry); + assert_visits( + &idents, + &[ + "call_probe", + "arg_name", + "arg_value", // call: callee, named-arg name, arg value + "idx_array", + "idx_index", // array index: array + index + "StructTy", + "field_probe", + "field_value", // struct literal: name, field, value + "elem_a", + "elem_b", // array literal elements + "type_expr_probe", + "i32", // generic name in expr position (Expr::Type + generic) + ], + ); + } + + #[test] + fn walk_descends_into_array_generic_function_qualified_and_custom_types() { + // A function type appears both with a return (`fn() -> FnRetTy`) and + // without (`fn()`), exercising the return arm's `Some` and `None` sides. + let source = "fn type_probes(\n\ +arr_p: [WidgetElem; 4],\n\ +gen_p: GenBase i32',\n\ +fn_ret_p: fn() -> FnRetTy,\n\ +fn_noret_p: fn(),\n\ +qual_p: qmod::qsub::QLeaf,\n\ +custom_p: CustomTy,\n\ +) -> i32 { return 1; }"; + let (arena, entry) = analyze(source); + let idents = walked_idents(&arena, entry); + assert_visits( + &idents, + &[ + "WidgetElem", // array type: element (its literal size has no ident) + "GenBase", + "i32", // generic type: base + parameter + "FnRetTy", // function type: return type + "qmod", + "qsub", + "QLeaf", // qualified type: qualifier segments + leaf + "CustomTy", // custom (bare) type + ], + ); + + // The array size is a bare literal with no identifier, so confirm the + // Array arm pushed both the element type and the size expression by + // inspecting the node's children directly. + let array = arena + .types + .iter() + .find_map(|(id, data)| matches!(data.kind, TypeNode::Array { .. }).then_some(id)) + .expect("an array type node"); + assert!(matches!( + type_children(&arena, array).as_slice(), + [NodeId::Type(_), NodeId::Expr(_)] + )); + } + + #[test] + fn children_of_a_source_file_or_identifier_are_empty() { + let (arena, entry) = analyze("fn f() -> i32 { return 1; }"); + assert!(children_of(&arena, NodeId::SourceFile(entry)).is_empty()); + let name = def_name_ident(&arena, arena[entry].defs[0]); + assert!(children_of(&arena, NodeId::Ident(name)).is_empty()); + } + + #[test] + fn type_children_of_a_qualified_name_yields_qualifier_then_name() { + // The parser lowers `a::B` to `TypeNode::Qualified`, never + // `TypeNode::QualifiedName`, so this arm is reachable only by building the + // node directly. + let mut arena = AstArena::default(); + let loc = Location::default(); + let qualifier = arena.idents.alloc(Ident { + location: loc, + name: "modx".to_string(), + }); + let name = arena.idents.alloc(Ident { + location: loc, + name: "Leaf".to_string(), + }); + let ty = arena.types.alloc(TypeData { + location: loc, + kind: TypeNode::QualifiedName { qualifier, name }, + }); + assert_eq!( + type_children(&arena, ty), + vec![NodeId::Ident(qualifier), NodeId::Ident(name)] + ); + } + + #[test] + fn type_children_of_a_function_type_yields_params_then_return() { + // `fn(...)` always lowers to empty parameters (a parity quirk), so the + // parameter-descent arm is reachable only by building the node directly. + let mut arena = AstArena::default(); + let loc = Location::default(); + let p0 = arena.types.alloc(TypeData { + location: loc, + kind: TypeNode::Simple(SimpleTypeKind::I32), + }); + let p1 = arena.types.alloc(TypeData { + location: loc, + kind: TypeNode::Simple(SimpleTypeKind::Bool), + }); + let ret = arena.types.alloc(TypeData { + location: loc, + kind: TypeNode::Simple(SimpleTypeKind::U8), + }); + let ty = arena.types.alloc(TypeData { + location: loc, + kind: TypeNode::Function { + params: vec![p0, p1], + ret: Some(ret), + }, + }); + assert_eq!( + type_children(&arena, ty), + vec![NodeId::Type(p0), NodeId::Type(p1), NodeId::Type(ret)] + ); + } + + // Small definition helpers + + #[test] + fn def_name_ident_names_every_definition_kind() { + let source = "fn fn_def() -> i32 { return 1; }\n\ +external fn extern_def(i32) -> i32;\n\ +struct struct_def { f: i32; }\n\ +enum enum_def { Va }\n\ +spec spec_def { fn nested_def() -> i32 { return 1; } }\n\ +const const_def: i32 = 1;\n\ +type type_def = i32;"; + let (arena, entry) = analyze(source); + let names: Vec<&str> = arena[entry] + .defs + .iter() + .map(|&def| arena.ident_name(def_name_ident(&arena, def))) + .collect(); + assert_eq!( + names, + vec![ + "fn_def", + "extern_def", + "struct_def", + "enum_def", + "spec_def", + "const_def", + "type_def", + ] + ); + } + + #[test] + fn def_is_public_reflects_visibility_across_definition_kinds() { + let source = "pub fn pub_fn() -> i32 { return 1; }\n\ +fn priv_fn() -> i32 { return 1; }\n\ +pub struct PubStruct { f: i32; }\n\ +struct PrivStruct { f: i32; }\n\ +pub enum PubEnum { Va }\n\ +enum PrivEnum { Vb }\n\ +pub const PUB_C: i32 = 1;\n\ +const PRIV_C: i32 = 1;\n\ +pub type PubT = i32;\n\ +type PrivT = i32;\n\ +external fn extern_priv(i32) -> i32;\n\ +spec spec_priv { fn spec_fn() -> i32 { return 1; } }"; + let (arena, entry) = analyze(source); + let is_public = |name: &str| { + let def = + find_def_by_name(&arena, entry, name).unwrap_or_else(|| panic!("no def `{name}`")); + def_is_public(&arena, def) + }; + for name in ["pub_fn", "PubStruct", "PubEnum", "PUB_C", "PubT"] { + assert!(is_public(name), "`{name}` is declared pub"); + } + for name in [ + "priv_fn", + "PrivStruct", + "PrivEnum", + "PRIV_C", + "PrivT", + "extern_priv", + "spec_priv", + ] { + assert!(!is_public(name), "`{name}` is not pub"); + } + } + + #[test] + fn find_method_finds_struct_methods_and_declines_non_structs() { + let source = "struct MethHost { fx: i32; fn get_fx(self) -> i32 { return self.fx; } }\n\ +fn free_fn() -> i32 { return 1; }"; + let (arena, entry) = analyze(source); + let host = find_def_by_name(&arena, entry, "MethHost").expect("struct present"); + let free = find_def_by_name(&arena, entry, "free_fn").expect("function present"); + assert!( + find_method(&arena, host, "get_fx").is_some(), + "the declared method resolves" + ); + assert!( + find_method(&arena, host, "absent").is_none(), + "an unknown method name does not resolve" + ); + assert!( + find_method(&arena, free, "get_fx").is_none(), + "a non-struct definition has no methods" + ); + } + + #[test] + fn method_has_self_distinguishes_instance_methods_from_the_rest() { + let source = "struct SelfHost { fn inst_method(self) -> i32 { return 1; } fn assoc_method() -> i32 { return 2; } }"; + let (arena, entry) = analyze(source); + let inst = find_def_by_name(&arena, entry, "inst_method").expect("instance method present"); + let assoc = find_def_by_name(&arena, entry, "assoc_method").expect("associated fn present"); + let host = find_def_by_name(&arena, entry, "SelfHost").expect("struct present"); + assert!( + method_has_self(&arena, inst), + "an instance method takes self" + ); + assert!( + !method_has_self(&arena, assoc), + "an associated fn does not take self" + ); + assert!( + !method_has_self(&arena, host), + "a non-function definition is not a self-method" + ); + } + + // resolve_qualified_module + + #[test] + fn resolve_qualified_module_follows_an_import_binding() { + // `lib::T`: the head `lib` matches the `use lib;` binding and the full path + // resolves — the common in-loop success. + let mut db = RootDatabase::default(); + let lib = module_path("lib"); + let main = module_path("main"); + db.open_document(&lib, "pub struct T { pub v: i32; }"); + db.open_document(&main, "use lib;\nfn f(x: lib::T) -> i32 { return 0; }"); + let file = db.analysis(&main); + let entry = file.source_file_id(&[]).expect("entry file"); + let qualifier = first_qualifier(file, entry); + assert_eq!( + resolve_qualified_module(file, entry, &qualifier), + file.source_file_id(&["lib".to_string()]) + ); + } + + #[test] + fn resolve_qualified_module_returns_none_when_an_extended_path_names_no_module() { + // `lib::missing::T`: the head `lib` matches the import, but the extended + // path names no file, so the in-loop lookup fails and the whole-path + // fallback fails too. + let mut db = RootDatabase::default(); + let lib = module_path("lib"); + let main = module_path("main"); + db.open_document(&lib, "pub struct T { pub v: i32; }"); + db.open_document( + &main, + "use lib;\nfn f(x: lib::missing::T) -> i32 { return 0; }", + ); + let file = db.analysis(&main); + let entry = file.source_file_id(&[]).expect("entry file"); + let qualifier = first_qualifier(file, entry); + assert!(resolve_qualified_module(file, entry, &qualifier).is_none()); + } + + #[test] + fn resolve_qualified_module_falls_back_to_a_full_source_root_path() { + // `lib::geom::Point` written while only `use lib::geom;` is imported: the + // import binds `geom`, so the head `lib` matches no binding, yet the whole + // qualifier is a real module path — the fallback resolves it. + let mut db = RootDatabase::default(); + let geom = nested_module_path(&["lib", "geom"]); + let main = module_path("main"); + db.open_document(&geom, "pub struct Point { pub v: i32; }"); + db.open_document( + &main, + "use lib::geom;\nfn f(x: lib::geom::Point) -> i32 { return 0; }", + ); + let file = db.analysis(&main); + let entry = file.source_file_id(&[]).expect("entry file"); + let qualifier = first_qualifier(file, entry); + assert_eq!( + resolve_qualified_module(file, entry, &qualifier), + file.source_file_id(&["lib".to_string(), "geom".to_string()]) + ); + } + + #[test] + fn resolve_qualified_module_returns_none_for_an_unknown_qualifier() { + // No import matches the head and the qualifier names no file: the import + // loop never runs and the fallback declines. + let mut db = RootDatabase::default(); + let main = module_path("main"); + db.open_document(&main, "fn f(x: ghost::T) -> i32 { return 0; }"); + let file = db.analysis(&main); + let entry = file.source_file_id(&[]).expect("entry file"); + let qualifier = first_qualifier(file, entry); + assert!(resolve_qualified_module(file, entry, &qualifier).is_none()); + } + + #[test] + fn resolve_qualified_module_rejects_an_empty_qualifier() { + // An empty qualifier has no head segment, so resolution declines at once. + let mut db = RootDatabase::default(); + let main = module_path("main"); + db.open_document(&main, "fn f() -> i32 { return 0; }"); + let file = db.analysis(&main); + let entry = file.source_file_id(&[]).expect("entry file"); + assert!(resolve_qualified_module(file, entry, &[]).is_none()); + } +} diff --git a/ide/ide/src/test_utils.rs b/ide/ide/src/test_utils.rs new file mode 100644 index 00000000..1c1e7be8 --- /dev/null +++ b/ide/ide/src/test_utils.rs @@ -0,0 +1,62 @@ +//! Shared helpers for the feature tests: build an [`AnalysisHost`] over in-memory +//! documents and compute byte offsets from the source text (never hardcoded). + +#![allow(clippy::cast_possible_truncation)] + +use std::path::PathBuf; + +use crate::AnalysisHost; + +/// The synthetic source root every test document lives under. A real path is +/// needed so import resolution has a directory to resolve siblings against; the +/// overlay shadows disk, so nothing is ever read from the filesystem. +const ROOT: &str = "/inf-test"; + +/// The absolute path a module lives at: the entry is `main.inf`, an imported +/// module `lib` is `lib.inf`, both under [`ROOT`]. +#[must_use] +pub(crate) fn module_path(name: &str) -> PathBuf { + PathBuf::from(format!("{ROOT}/{name}.inf")) +} + +/// A host with a single open entry document, plus that document's path. +#[must_use] +pub(crate) fn single(source: &str) -> (AnalysisHost, PathBuf) { + let mut host = AnalysisHost::default(); + let path = module_path("main"); + host.open_document(&path, source); + (host, path) +} + +/// A host with an open entry document plus one open imported sibling `lib.inf`, +/// and the entry's path. The entry should `use lib;` to pull the sibling in. +#[must_use] +pub(crate) fn with_lib(entry: &str, lib: &str) -> (AnalysisHost, PathBuf) { + let mut host = AnalysisHost::default(); + let entry_path = module_path("main"); + host.open_document(&module_path("lib"), lib); + host.open_document(&entry_path, entry); + (host, entry_path) +} + +/// The byte offset of the first occurrence of `needle` in `source`. +#[must_use] +pub(crate) fn at(source: &str, needle: &str) -> u32 { + source.find(needle).expect("needle present in source") as u32 +} + +/// The byte offset just past the first occurrence of `needle` in `source`. +#[must_use] +pub(crate) fn after(source: &str, needle: &str) -> u32 { + at(source, needle) + needle.len() as u32 +} + +/// The byte offset of the `n`-th (0-based) occurrence of `needle` in `source`. +#[must_use] +pub(crate) fn nth(source: &str, needle: &str, n: usize) -> u32 { + source + .match_indices(needle) + .nth(n) + .expect("nth needle present in source") + .0 as u32 +} diff --git a/ide/ide/src/type_render.rs b/ide/ide/src/type_render.rs new file mode 100644 index 00000000..37b55221 --- /dev/null +++ b/ide/ide/src/type_render.rs @@ -0,0 +1,192 @@ +//! Editor-facing rendering of a checked type to a source-like string. + +use inference_type_checker::type_info::{TypeInfo, TypeInfoKind}; + +/// Renders `ty` as the source-like type spelling shown in hovers and inlays. +/// +/// It differs from the compiler's own `Display` in two ways chosen for a reader: +/// - the built-in scalars use their lowercase source spellings (`unit` / `bool` / +/// `string`), not the capitalized debug forms the checker prints; +/// - a struct or enum is named by its canonical key, which is the bare type name +/// for a same-file type and the `::`-qualified module path for a cross-module +/// one (`lib::geom::Point`). The key is exactly the module-qualified bare name, +/// never an internal mangled form, so it reads as source. +#[must_use] +pub(crate) fn render_type(ty: &TypeInfo) -> String { + let mut out = render_kind(&ty.kind); + // A bare generic reference is a type parameter, spelled with a trailing prime + // (`T'`). A generic *application* names its base unprimed and primes each + // argument instead (`Array u32'`); the checker lowers both to + // `Generic`, distinguished only by whether type params are present. + if matches!(ty.kind, TypeInfoKind::Generic(_)) && ty.type_params.is_empty() { + out.push('\''); + } + for type_param in &ty.type_params { + out.push(' '); + out.push_str(type_param); + out.push('\''); + } + out +} + +fn render_kind(kind: &TypeInfoKind) -> String { + match kind { + TypeInfoKind::Unit => "unit".to_string(), + TypeInfoKind::Bool => "bool".to_string(), + TypeInfoKind::String => "string".to_string(), + TypeInfoKind::Number(number) => number.as_str().to_string(), + TypeInfoKind::Array(element, length) => format!("[{}; {}]", render_type(element), length), + // The canonical key is the bare name for an entry-file type and the + // `::`-joined module path otherwise, so it is already the module-qualified + // bare name the editor wants. + TypeInfoKind::Struct(_, key) | TypeInfoKind::Enum(_, key) => key.clone(), + // `Generic` renders as its bare name here; the prime that tells a + // reference (`T'`) apart from an application base (`Array u32'`) is added + // in `render_type`, where the type params needed to decide it are known. + TypeInfoKind::Custom(name) + | TypeInfoKind::Qualified(name) + | TypeInfoKind::QualifiedName(name) + | TypeInfoKind::Function(name) + | TypeInfoKind::Spec(name) + | TypeInfoKind::Generic(name) => name.clone(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use inference_type_checker::type_info::NumberType; + + fn number(n: NumberType) -> TypeInfo { + TypeInfo { + kind: TypeInfoKind::Number(n), + type_params: vec![], + } + } + + #[test] + fn scalars_use_lowercase_source_spellings() { + assert_eq!( + render_type(&TypeInfo { + kind: TypeInfoKind::Bool, + type_params: vec![] + }), + "bool" + ); + assert_eq!( + render_type(&TypeInfo { + kind: TypeInfoKind::Unit, + type_params: vec![] + }), + "unit" + ); + assert_eq!(render_type(&number(NumberType::I32)), "i32"); + assert_eq!(render_type(&number(NumberType::U64)), "u64"); + } + + #[test] + fn struct_renders_by_canonical_key() { + // Entry-file struct: key equals the bare name. + assert_eq!( + render_type(&TypeInfo { + kind: TypeInfoKind::Struct("Point".into(), "Point".into()), + type_params: vec![], + }), + "Point" + ); + // Cross-module struct: key is the `::`-qualified module path. + assert_eq!( + render_type(&TypeInfo { + kind: TypeInfoKind::Struct("Point".into(), "lib::geom::Point".into()), + type_params: vec![], + }), + "lib::geom::Point" + ); + } + + #[test] + fn array_renders_element_and_length() { + let ty = TypeInfo { + kind: TypeInfoKind::Array(Box::new(number(NumberType::I32)), 4), + type_params: vec![], + }; + assert_eq!(render_type(&ty), "[i32; 4]"); + } + + #[test] + fn string_and_enum_render_by_source_and_key() { + assert_eq!( + render_type(&TypeInfo { + kind: TypeInfoKind::String, + type_params: vec![], + }), + "string" + ); + assert_eq!( + render_type(&TypeInfo { + kind: TypeInfoKind::Enum("Color".into(), "lib::Color".into()), + type_params: vec![], + }), + "lib::Color" + ); + } + + #[test] + fn opaque_string_kinds_render_verbatim() { + let cases = [ + (TypeInfoKind::Custom("Widget".into()), "Widget"), + ( + TypeInfoKind::Qualified("lib::geom::Point".into()), + "lib::geom::Point", + ), + ( + TypeInfoKind::QualifiedName("geo::Level".into()), + "geo::Level", + ), + (TypeInfoKind::Function("adder".into()), "adder"), + (TypeInfoKind::Spec("Laws".into()), "Laws"), + ]; + for (kind, expected) in cases { + assert_eq!( + render_type(&TypeInfo { + kind, + type_params: vec![], + }), + expected + ); + } + } + + #[test] + fn generic_gets_a_prime_and_type_params_are_appended() { + assert_eq!( + render_type(&TypeInfo { + kind: TypeInfoKind::Generic("T".into()), + type_params: vec![], + }), + "T'" + ); + assert_eq!( + render_type(&TypeInfo { + kind: TypeInfoKind::Custom("Vec".into()), + type_params: vec!["T".into()], + }), + "Vec T'" + ); + } + + #[test] + fn generic_application_base_is_not_primed() { + // `TypeInfo::from_type_id` lowers a generic application (`Array u32'`) to + // Generic("Array") with type params ["u32"]. The prime belongs on the + // argument, not the base: the source spelling is `Array u32'`, never + // `Array' u32'`. + assert_eq!( + render_type(&TypeInfo { + kind: TypeInfoKind::Generic("Array".into()), + type_params: vec!["u32".into()], + }), + "Array u32'" + ); + } +} diff --git a/ide/vfs/Cargo.toml b/ide/vfs/Cargo.toml index 27fd3efb..d7e6b0ea 100644 --- a/ide/vfs/Cargo.toml +++ b/ide/vfs/Cargo.toml @@ -6,3 +6,6 @@ license = { workspace = true } homepage = { workspace = true } repository = { workspace = true } description = "Virtual File System for Inference IDE support" + +[dependencies] +rustc-hash.workspace = true diff --git a/ide/vfs/README.md b/ide/vfs/README.md index 46af9c53..6ac064d6 100644 --- a/ide/vfs/README.md +++ b/ide/vfs/README.md @@ -1,50 +1,112 @@ -# inference-vfs - Virtual File System +# inference-vfs -Virtual file system for Inference IDE support. Provides file identity and change tracking without performing disk I/O. +In-memory file identity and an open-document content overlay for the Inference +IDE stack. This is the lowest layer of the `ide/` crates: it gives every other +IDE component a small, `Copy` [`FileId`] to key maps and diagnostics on instead +of passing `PathBuf`s around, and it holds the in-memory text of whatever files +the editor currently has open. -## Status +## Where It Sits -Skeleton implementation. See the LSP plan for the full feature roadmap. - -## Design Principles - -1. **No Disk I/O** - VFS only tracks state; actual file reading is done by clients -2. **Integer File IDs** - Files identified by `FileId(u32)`, not paths -3. **Change-Based Updates** - Tracks modifications via `ChangeSet` -4. **Path Abstraction** - `VfsPath` normalizes real and virtual paths +``` +apps/lsp + | +ide/ide -> ide/ide-db -> ide/base-db -> ide/vfs +``` -## Planned Types +`vfs` depends on nothing but `rustc-hash` (for `FxHashMap`). Every other `ide/` +crate depends on it, directly or transitively, for `FileId`. + +## What It Owns + +- **Identity** — [`Vfs::intern`] maps a `Path` to a stable `FileId`. Interning is + idempotent: interning the same path twice returns the same id, and ids are + dense, zero-based, and allocation-ordered, so a downstream crate can use one + as a vector index if it wants to. +- **Overlay** — while a document is open in the editor, its authoritative text + lives in the editor's buffer, not on disk. [`Vfs::set_contents`] stores that + text as an `Arc`; [`Vfs::contents`] and [`Vfs::contents_of_path`] read it + back. A file with no overlay entry means "not open" — the caller is expected + to fall back to disk one layer up. + +## Why No File I/O Happens Here + +This crate never touches `std::fs`. It only remembers paths and buffers callers +hand it. The LSP layer feeds it absolute paths derived from client URIs and the +current editor text on `didOpen`/`didChange`; the disk-fallback read for an +import the editor has never opened lives in `ide-db`'s `VfsLoader`, which +consults the overlay first and falls back to `std::fs::read_to_string`. Keeping +I/O out of this crate makes it trivially deterministic and testable — every test +in `src/lib.rs` runs against `PathBuf`s that were never expected to exist on +disk. + +## Why Paths Are Stored, Not Canonicalized + +Paths are interned exactly as given. This crate never calls +`std::fs::canonicalize`, so it never resolves symlinks or `..` components and +never touches the disk to do so. Identity is `std::path::Path` identity, which +compares by path component: it already ignores redundant `.` segments and +separator noise, but leaves `..` unresolved, so `/src/../src/a.inf` and +`/src/a.inf` intern as two distinct files. + +A caller that needs canonical identity — so that one file is never +accidentally interned twice under two spellings — must normalize before +calling `intern`. The LSP layer does this: it derives one canonical absolute +path per `file://` URI and interns every file under that single spelling, so +`FileId` equality is reliable for every consumer built on top of this crate. + +## Public API ```rust -/// Opaque file identifier -#[derive(Copy, Clone, Eq, PartialEq, Hash)] -pub struct FileId(u32); - -/// Abstraction over file paths (real or virtual) -pub struct VfsPath { /* ... */ } +use std::path::PathBuf; +use std::sync::Arc; +use inference_vfs::Vfs; -/// Stable path-to-FileId mapping -pub struct PathInterner { /* ... */ } +let mut vfs = Vfs::default(); -/// Batched file modifications -pub struct ChangeSet { /* ... */ } +// Interning is idempotent and returns dense, allocation-ordered ids. +let main = vfs.intern(&PathBuf::from("/project/src/main.inf")); +assert_eq!(vfs.intern(&PathBuf::from("/project/src/main.inf")), main); -/// VFS coordinator -pub struct Vfs { /* ... */ } -``` - -## Architecture +// A file is "closed" (read from disk elsewhere) until it gets overlay text. +assert!(vfs.contents(main).is_none()); -This crate is the foundation of the IDE infrastructure layer: +// An editor `didOpen` installs the buffer's current text. +vfs.set_contents(main, Arc::from("fn main() -> i32 { return 0; }")); +assert!(vfs.contents(main).is_some()); -``` -apps/lsp - | -ide/ide -> ide/ide-db -> ide/base-db -> ide/vfs +// An editor `didClose` drops the overlay; the path stays interned. +vfs.remove_contents(main); +assert_eq!(vfs.path(main), PathBuf::from("/project/src/main.inf")); ``` -## Building - -```bash -cargo build -p inference-vfs -``` +| Type / Method | Role | +|---|---| +| `FileId` | Opaque, `Copy` handle to an interned path; `.index()` exposes the dense `u32` backing it | +| `Vfs::intern(&Path) -> FileId` | Interns a path (idempotent) | +| `Vfs::file_id(&Path) -> Option` | Looks up an already-interned path without allocating a new id | +| `Vfs::path(FileId) -> &Path` | Resolves an id back to its path | +| `Vfs::set_contents(FileId, impl Into>)` | Installs or replaces overlay text (`didOpen` / `didChange`) | +| `Vfs::remove_contents(FileId)` | Drops overlay text, a no-op if absent (`didClose`) | +| `Vfs::contents(FileId) -> Option>` | Reads current overlay text, if the document is open | +| `Vfs::contents_of_path(&Path) -> Option>` | Same, addressed by path instead of id | +| `Vfs::overlays() -> impl Iterator` | Every currently-open file, order unspecified | + +A `FileId` is only meaningful to the `Vfs` that minted it — mixing ids from two +different `Vfs` instances is a caller error the type system does not catch. + +## Testing + +The crate's tests live inline in `src/lib.rs` and cover: idempotent interning, +distinct paths receiving distinct dense ids, path round-tripping, the +`..`-is-never-resolved guarantee, and every overlay transition (absent → set → +replaced → removed → absent), including that closing a document keeps the path +interned so a later `didOpen` of the same path returns the same `FileId`. + +## Related Resources + +- [`ide/base-db`](../base-db/README.md) — position primitives (`LineIndex`, + `TextRange`, `FilePosition`, `FileRange`) built on top of this crate's `FileId` +- [`ide/ide-db`](../ide-db/README.md) — `RootDatabase`, which owns a `Vfs` and + drives the overlay-then-disk `FileLoader` used for import resolution +- [Language Server Protocol Specification](https://microsoft.github.io/language-server-protocol/) — `textDocument/didOpen` / `didChange` / `didClose`, the editor lifecycle this crate's overlay mirrors diff --git a/ide/vfs/src/lib.rs b/ide/vfs/src/lib.rs index 8b137891..a88f7ca3 100644 --- a/ide/vfs/src/lib.rs +++ b/ide/vfs/src/lib.rs @@ -1 +1,310 @@ +//! In-memory file identity and an open-document content overlay for the +//! Inference IDE stack. +//! +//! The [`Vfs`] serves two jobs that together decouple the rest of the IDE stack +//! from the operating system: +//! +//! * **Identity** — every path the IDE touches is interned to a small, `Copy` +//! [`FileId`]. Downstream crates key their maps and diagnostics on `FileId` +//! instead of passing paths around, and comparisons become integer +//! comparisons. +//! * **Overlay** — while a document is open in the editor its authoritative text +//! lives in the editor's buffer, not on disk. The overlay stores that +//! in-memory text as an [`Arc`] so an editor edit is reflected before (or +//! instead of) any file write. +//! +//! # No file I/O +//! +//! This crate never touches `std::fs`. It only remembers paths and buffers that +//! callers hand to it. The LSP layer feeds absolute paths derived from client +//! URIs and the current editor text; the disk-fallback read for unopened +//! imports lives one layer up (in `ide-db`), where the VFS overlay is always +//! consulted first. Keeping I/O out of here makes the store trivially +//! deterministic and testable. +//! +//! # Paths are stored, not canonicalized +//! +//! Paths are interned exactly as given: this crate never calls +//! `std::fs::canonicalize`, so it never resolves symlinks or `..` components and +//! never touches the disk. Identity is std [`Path`] identity, which compares by +//! path component — it already ignores redundant `.` and separator noise but +//! leaves `..` unresolved, so `/src/../src/a.inf` and `/src/a.inf` are distinct +//! files here. Callers that need canonical identity must normalize before +//! interning; the LSP layer derives one canonical absolute path per URI and +//! interns each file under that single spelling. +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use rustc_hash::FxHashMap; + +/// An opaque handle identifying a file interned in a [`Vfs`]. +/// +/// `FileId`s are only ever minted by [`Vfs::intern`] and are dense and +/// allocation-ordered starting at zero, which lets downstream crates use them +/// as vector indices. A `FileId` is only meaningful to the `Vfs` that produced +/// it; mixing ids from different `Vfs` instances is a caller error. +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] +pub struct FileId(u32); + +impl FileId { + /// The dense zero-based index backing this id. + /// + /// Useful for indexing side tables keyed by file. Only ids minted by the + /// same [`Vfs`] index that `Vfs`'s tables in bounds. + #[must_use = "reading the index is pointless if the value is discarded"] + pub fn index(self) -> u32 { + self.0 + } +} + +/// Path interner plus open-document content overlay. +/// +/// Construct with [`Vfs::default`]. Interning is idempotent, so the same path +/// always maps to the same [`FileId`]; the overlay maps ids to their current +/// in-memory text and is edited independently of interning (a path can be +/// interned long before — or without ever — receiving overlay text). +#[derive(Debug, Default)] +pub struct Vfs { + /// `FileId` (as index) → interned path. Never removed, so ids stay valid + /// for the lifetime of the `Vfs`. + paths: Vec, + /// Interned path → its `FileId`, the inverse of `paths`. + ids: FxHashMap, + /// `FileId` → current in-memory document text. Present only while a document + /// is open; absence means "not open" (read from disk one layer up). + overlay: FxHashMap>, +} + +impl Vfs { + /// Interns `path`, returning its stable [`FileId`]. + /// + /// Idempotent: interning a path already known returns the existing id + /// without allocating a new one. Distinct paths receive distinct ids. + #[must_use = "the returned FileId is the only handle to the interned path"] + pub fn intern(&mut self, path: &Path) -> FileId { + if let Some(&id) = self.ids.get(path) { + return id; + } + let id = FileId(self.paths.len() as u32); + let owned = path.to_path_buf(); + self.paths.push(owned.clone()); + self.ids.insert(owned, id); + id + } + + /// Looks up the [`FileId`] a path was interned under, if any. + #[must_use = "the lookup result must be inspected to be useful"] + pub fn file_id(&self, path: &Path) -> Option { + self.ids.get(path).copied() + } + + /// The path `file_id` was interned under. + /// + /// `file_id` must have been minted by this `Vfs`; ids are never invalidated, + /// so any id this `Vfs` produced resolves here. + #[must_use = "the resolved path is the reason to call this"] + pub fn path(&self, file_id: FileId) -> &Path { + &self.paths[file_id.0 as usize] + } + + /// Sets or replaces the overlay text for `file_id` (an editor open or edit). + pub fn set_contents(&mut self, file_id: FileId, contents: Arc) { + self.overlay.insert(file_id, contents); + } + + /// Removes the overlay text for `file_id` (an editor close). + /// + /// A no-op if the file has no overlay text. The path stays interned; only + /// the in-memory document is dropped. + pub fn remove_contents(&mut self, file_id: FileId) { + self.overlay.remove(&file_id); + } + + /// The current overlay text for `file_id`, if the document is open. + /// + /// The returned [`Arc`] is a cheap handle to the shared buffer. + #[must_use = "the overlay text is the reason to call this"] + pub fn contents(&self, file_id: FileId) -> Option> { + self.overlay.get(&file_id).cloned() + } + + /// The current overlay text for `path`, if it is interned and open. + #[must_use = "the overlay text is the reason to call this"] + pub fn contents_of_path(&self, path: &Path) -> Option> { + self.contents(self.file_id(path)?) + } + + /// Iterates every file that currently holds overlay text. + /// + /// Iteration order is unspecified (the overlay is a hash map). Yields each + /// open file's id alongside a borrow of its text. + #[must_use = "the iterator is lazy and does nothing unless consumed"] + pub fn overlays(&self) -> impl Iterator { + self.overlay.iter().map(|(&id, text)| (id, text.as_ref())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p(s: &str) -> PathBuf { + PathBuf::from(s) + } + + #[test] + fn intern_is_idempotent() { + let mut vfs = Vfs::default(); + let a1 = vfs.intern(&p("/src/main.inf")); + let a2 = vfs.intern(&p("/src/main.inf")); + assert_eq!(a1, a2); + } + + #[test] + fn distinct_paths_get_distinct_ids() { + let mut vfs = Vfs::default(); + let a = vfs.intern(&p("/src/a.inf")); + let b = vfs.intern(&p("/src/b.inf")); + let c = vfs.intern(&p("/src/c.inf")); + assert_ne!(a, b); + assert_ne!(b, c); + assert_ne!(a, c); + } + + #[test] + fn ids_are_dense_and_allocation_ordered() { + let mut vfs = Vfs::default(); + let a = vfs.intern(&p("/a")); + let b = vfs.intern(&p("/b")); + let c = vfs.intern(&p("/c")); + assert_eq!(a.index(), 0); + assert_eq!(b.index(), 1); + assert_eq!(c.index(), 2); + // Re-interning does not advance the counter. + let a_again = vfs.intern(&p("/a")); + assert_eq!(a_again.index(), 0); + let d = vfs.intern(&p("/d")); + assert_eq!(d.index(), 3); + } + + #[test] + fn file_id_lookup_hits_and_misses() { + let mut vfs = Vfs::default(); + let a = vfs.intern(&p("/src/a.inf")); + assert_eq!(vfs.file_id(&p("/src/a.inf")), Some(a)); + assert_eq!(vfs.file_id(&p("/src/missing.inf")), None); + } + + #[test] + fn path_round_trips_from_id() { + let mut vfs = Vfs::default(); + let a = vfs.intern(&p("/src/a.inf")); + let b = vfs.intern(&p("/nested/dir/b.inf")); + assert_eq!(vfs.path(a), p("/src/a.inf").as_path()); + assert_eq!(vfs.path(b), p("/nested/dir/b.inf").as_path()); + } + + #[test] + fn paths_are_not_canonicalized() { + let mut vfs = Vfs::default(); + let direct = vfs.intern(&p("/src/a.inf")); + // `..` is never resolved (no fs::canonicalize), so this stays a + // distinct file rather than collapsing onto "/src/a.inf". + let indirect = vfs.intern(&p("/src/../src/a.inf")); + assert_ne!(direct, indirect); + assert_eq!(vfs.path(indirect), p("/src/../src/a.inf").as_path()); + } + + #[test] + fn overlay_absent_until_set() { + let mut vfs = Vfs::default(); + let a = vfs.intern(&p("/a.inf")); + assert!(vfs.contents(a).is_none()); + } + + #[test] + fn overlay_set_then_read() { + let mut vfs = Vfs::default(); + let a = vfs.intern(&p("/a.inf")); + vfs.set_contents(a, Arc::from("fn main() {}")); + match vfs.contents(a) { + Some(text) => assert_eq!(&*text, "fn main() {}"), + None => panic!("overlay text should be present after set"), + } + } + + #[test] + fn overlay_replace_overwrites() { + let mut vfs = Vfs::default(); + let a = vfs.intern(&p("/a.inf")); + vfs.set_contents(a, Arc::from("first")); + vfs.set_contents(a, Arc::from("second")); + match vfs.contents(a) { + Some(text) => assert_eq!(&*text, "second"), + None => panic!("overlay text should be present after replace"), + } + } + + #[test] + fn overlay_remove_drops_document() { + let mut vfs = Vfs::default(); + let a = vfs.intern(&p("/a.inf")); + vfs.set_contents(a, Arc::from("body")); + vfs.remove_contents(a); + assert!(vfs.contents(a).is_none()); + // The path stays interned after the document is closed. + assert_eq!(vfs.file_id(&p("/a.inf")), Some(a)); + } + + #[test] + fn overlay_remove_is_a_noop_when_absent() { + let mut vfs = Vfs::default(); + let a = vfs.intern(&p("/a.inf")); + vfs.remove_contents(a); + assert!(vfs.contents(a).is_none()); + } + + #[test] + fn contents_of_path_reads_through_the_overlay() { + let mut vfs = Vfs::default(); + let a = vfs.intern(&p("/a.inf")); + vfs.set_contents(a, Arc::from("hello")); + match vfs.contents_of_path(&p("/a.inf")) { + Some(text) => assert_eq!(&*text, "hello"), + None => panic!("overlay text should resolve through the path"), + } + // Interned but closed. + vfs.remove_contents(a); + assert!(vfs.contents_of_path(&p("/a.inf")).is_none()); + // Never interned. + assert!(vfs.contents_of_path(&p("/never.inf")).is_none()); + } + + #[test] + fn overlays_iterates_only_open_files() { + let mut vfs = Vfs::default(); + let a = vfs.intern(&p("/a.inf")); + let b = vfs.intern(&p("/b.inf")); + let _c = vfs.intern(&p("/c.inf")); // interned but never opened + vfs.set_contents(a, Arc::from("aaa")); + vfs.set_contents(b, Arc::from("bbb")); + + let mut seen: Vec<(u32, String)> = vfs + .overlays() + .map(|(id, text)| (id.index(), text.to_owned())) + .collect(); + seen.sort(); + assert_eq!( + seen, + vec![(a.index(), "aaa".to_owned()), (b.index(), "bbb".to_owned())] + ); + } + + #[test] + fn overlays_is_empty_before_any_open() { + let mut vfs = Vfs::default(); + let _a = vfs.intern(&p("/a.inf")); + assert_eq!(vfs.overlays().count(), 0); + } +}