lsp-server-0.7.9/.cargo_vcs_info.json0000644000000001770000000000100131600ustar { "git": { "sha1": "8d75311400a108d7ffe17dc9c38182c566952e6e", "dirty": true }, "path_in_vcs": "lib/lsp-server" }lsp-server-0.7.9/Cargo.lock0000644000000346020000000000100111330ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "anyhow" version = "1.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" [[package]] name = "cfg-if" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" [[package]] name = "cfg_aliases" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "crossbeam-channel" version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "ctrlc" version = "3.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46f93780a459b7d656ef7f071fe699c4d3d2cb201c4b24d085b6ddc505276e73" dependencies = [ "nix", "windows-sys", ] [[package]] name = "displaydoc" version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "form_urlencoded" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" dependencies = [ "percent-encoding", ] [[package]] name = "icu_collections" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47" dependencies = [ "displaydoc", "potential_utf", "yoke", "zerofrom", "zerovec", ] [[package]] name = "icu_locale_core" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cde2700ccaed3872079a65fb1a78f6c0a36c91570f28755dda67bc8f7d9f00a" dependencies = [ "displaydoc", "litemap", "tinystr", "writeable", "zerovec", ] [[package]] name = "icu_normalizer" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "436880e8e18df4d7bbc06d58432329d6458cc84531f7ac5f024e93deadb37979" dependencies = [ "displaydoc", "icu_collections", "icu_normalizer_data", "icu_properties", "icu_provider", "smallvec", "zerovec", ] [[package]] name = "icu_normalizer_data" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" [[package]] name = "icu_properties" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "016c619c1eeb94efb86809b015c58f479963de65bdb6253345c1a1276f22e32b" dependencies = [ "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", "icu_provider", "potential_utf", "zerotrie", "zerovec", ] [[package]] name = "icu_properties_data" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632" [[package]] name = "icu_provider" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03c80da27b5f4187909049ee2d72f276f0d9f99a42c306bd0131ecfe04d8e5af" dependencies = [ "displaydoc", "icu_locale_core", "stable_deref_trait", "tinystr", "writeable", "yoke", "zerofrom", "zerotrie", "zerovec", ] [[package]] name = "idna" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" dependencies = [ "idna_adapter", "smallvec", "utf8_iter", ] [[package]] name = "idna_adapter" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" dependencies = [ "icu_normalizer", "icu_properties", ] [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "libc" version = "0.2.172" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "litemap" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956" [[package]] name = "log" version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" [[package]] name = "lsp-server" version = "0.7.9" dependencies = [ "anyhow", "crossbeam-channel", "ctrlc", "log", "lsp-types", "rustc-hash", "serde", "serde_derive", "serde_json", ] [[package]] name = "lsp-types" version = "0.95.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "158c1911354ef73e8fe42da6b10c0484cb65c7f1007f28022e847706c1ab6984" dependencies = [ "bitflags 1.3.2", "serde", "serde_json", "serde_repr", "url", ] [[package]] name = "memchr" version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" [[package]] name = "nix" version = "0.30.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6" dependencies = [ "bitflags 2.9.1", "cfg-if", "cfg_aliases", "libc", ] [[package]] name = "percent-encoding" version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "potential_utf" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5a7c30837279ca13e7c867e9e40053bc68740f988cb07f7ca6df43cc734b585" dependencies = [ "zerovec", ] [[package]] name = "proc-macro2" version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "rustc-hash" version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "serde" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" dependencies = [ "itoa", "memchr", "ryu", "serde", ] [[package]] name = "serde_repr" version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "smallvec" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] name = "stable_deref_trait" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" [[package]] name = "syn" version = "2.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4307e30089d6fd6aff212f2da3a1f9e32f3223b1f010fb09b7c95f90f3ca1e8" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "synstructure" version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "tinystr" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b" dependencies = [ "displaydoc", "zerovec", ] [[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "url" version = "2.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" dependencies = [ "form_urlencoded", "idna", "percent-encoding", "serde", ] [[package]] name = "utf8_iter" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "writeable" version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb" [[package]] name = "yoke" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f41bb01b8226ef4bfd589436a297c53d118f65921786300e427be8d487695cc" dependencies = [ "serde", "stable_deref_trait", "yoke-derive", "zerofrom", ] [[package]] name = "yoke-derive" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38da3c9736e16c5d3c8c597a9aaa5d1fa565d0532ae05e27c24aa62fb32c0ab6" dependencies = [ "proc-macro2", "quote", "syn", "synstructure", ] [[package]] name = "zerofrom" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", "syn", "synstructure", ] [[package]] name = "zerotrie" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36f0bbd478583f79edad978b407914f61b2972f5af6fa089686016be8f9af595" dependencies = [ "displaydoc", "yoke", "zerofrom", ] [[package]] name = "zerovec" version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a05eb080e015ba39cc9e23bbe5e7fb04d5fb040350f99f34e338d5fdd294428" dependencies = [ "yoke", "zerofrom", "zerovec-derive", ] [[package]] name = "zerovec-derive" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f" dependencies = [ "proc-macro2", "quote", "syn", ] lsp-server-0.7.9/Cargo.toml0000644000000047410000000000100111570ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2024" name = "lsp-server" version = "0.7.9" build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Generic LSP server scaffold." readme = false license = "MIT OR Apache-2.0" repository = "https://github.com/rust-lang/rust-analyzer/tree/master/lib/lsp-server" resolver = "2" [lib] name = "lsp_server" path = "src/lib.rs" [[example]] name = "minimal_lsp" path = "examples/minimal_lsp.rs" [dependencies.crossbeam-channel] version = "0.5.15" [dependencies.log] version = "0.4.27" [dependencies.serde] version = "1.0.219" [dependencies.serde_derive] version = "1.0.219" [dependencies.serde_json] version = "1.0.140" [dev-dependencies.anyhow] version = "1.0.98" [dev-dependencies.ctrlc] version = "3.4.7" [dev-dependencies.lsp-types] version = "=0.95" [dev-dependencies.rustc-hash] version = "2.1.1" [lints.clippy] assigning_clones = "allow" dbg_macro = "warn" enum_variant_names = "allow" len_without_is_empty = "allow" literal_string_with_formatting_args = "allow" new_ret_no_self = "allow" print_stderr = "warn" print_stdout = "warn" rc_buffer = "warn" result_unit_err = "allow" single_match = "allow" str_to_string = "warn" todo = "warn" too_long_first_doc_paragraph = "allow" too_many_arguments = "allow" type_complexity = "allow" unnecessary_map_or = "allow" useless_asref = "allow" vec_init_then_push = "allow" wrong_self_convention = "allow" [lints.clippy.complexity] level = "warn" priority = -1 [lints.clippy.correctness] level = "deny" priority = -1 [lints.clippy.perf] level = "deny" priority = -1 [lints.clippy.restriction] level = "allow" priority = -1 [lints.clippy.style] level = "warn" priority = -1 [lints.clippy.suspicious] level = "warn" priority = -1 [lints.rust] elided_lifetimes_in_paths = "warn" explicit_outlives_requirements = "warn" unreachable_pub = "warn" unsafe_op_in_unsafe_fn = "warn" unused_extern_crates = "warn" unused_lifetimes = "warn" [lints.rust.unexpected_cfgs] level = "warn" priority = 0 check-cfg = ["cfg(bootstrap)"] lsp-server-0.7.9/Cargo.toml.orig000064400000000000000000000010441046102023000146310ustar 00000000000000[package] name = "lsp-server" version = "0.7.9" description = "Generic LSP server scaffold." license = "MIT OR Apache-2.0" repository = "https://github.com/rust-lang/rust-analyzer/tree/master/lib/lsp-server" edition = "2024" [dependencies] log = "0.4.27" serde_json = "1.0.140" serde = { version = "1.0.219" } serde_derive = { version = "1.0.219" } crossbeam-channel.workspace = true [dev-dependencies] lsp-types = "=0.95" ctrlc = "3.4.7" anyhow.workspace = true rustc-hash.workspace = true # toolchain.workspace = true [lints] workspace = true lsp-server-0.7.9/LICENSE-APACHE000064400000000000000000000227731046102023000137020ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS lsp-server-0.7.9/LICENSE-MIT000064400000000000000000000017771046102023000134130ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. lsp-server-0.7.9/examples/manual_test.sh000075500000000000000000000044421046102023000164400ustar 00000000000000#!/usr/bin/env bash # Simple nine-packet LSP test for examples/minimal_lsp.rs # Usage (two tabs): # # mkfifo /tmp/lsp_pipe # one-time setup # # tab 1 – run the server # cat /tmp/lsp_pipe | cargo run --example minimal_lsp # # # tab 2 – fire the packets (this script) # bash examples/manual_test.sh # blocks until server exits # # If you don’t use a second tab, run the script in the background: # # bash examples/manual_test.sh & # writer in background # cat /tmp/lsp_pipe | cargo run --example minimal_lsp # # The script opens /tmp/lsp_pipe for writing (exec 3>) and sends each JSON # packet with a correct Content-Length header. # # One-liner alternative (single terminal, no FIFO): # # cargo run --example minimal_lsp <<'EOF' # … nine packets … # EOF # # Both approaches feed identical bytes to minimal_lsp via stdin. set -eu PIPE=${1:-/tmp/lsp_pipe} mkfifo -m 600 "$PIPE" 2>/dev/null || true # create once, ignore if exists # open write end so the fifo stays open exec 3> "$PIPE" send() { local body=$1 local len=$(printf '%s' "$body" | wc -c) printf 'Content-Length: %d\r\n\r\n%s' "$len" "$body" >&3 } send '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{}}}' send '{"jsonrpc":"2.0","method":"initialized","params":{}}' send '{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///tmp/foo.rs","languageId":"rust","version":1,"text":"fn main( ){println!(\"hi\") }"}}}' send '{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:///tmp/foo.rs"},"position":{"line":0,"character":0}}}' send '{"jsonrpc":"2.0","id":3,"method":"textDocument/hover","params":{"textDocument":{"uri":"file:///tmp/foo.rs"},"position":{"line":0,"character":0}}}' send '{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///tmp/foo.rs"},"position":{"line":0,"character":0}}}' send '{"jsonrpc":"2.0","id":5,"method":"textDocument/formatting","params":{"textDocument":{"uri":"file:///tmp/foo.rs"},"options":{"tabSize":4,"insertSpaces":true}}}' send '{"jsonrpc":"2.0","id":6,"method":"shutdown","params":null}' send '{"jsonrpc":"2.0","method":"exit","params":null}' exec 3>&- echo "Packets sent – watch the other terminal for responses." lsp-server-0.7.9/examples/minimal_lsp.rs000064400000000000000000000271721046102023000164440ustar 00000000000000//! Minimal Language‑Server‑Protocol example: **`minimal_lsp.rs`** //! ============================================================= //! //! | ↔ / ← | LSP method | What the implementation does | //! |-------|------------|------------------------------| //! | ↔ | `initialize` / `initialized` | capability handshake | //! | ← | `textDocument/publishDiagnostics` | pushes a dummy info diagnostic whenever the buffer changes | //! | ← | `textDocument/definition` | echoes an empty location array so the jump works | //! | ← | `textDocument/completion` | offers one hard‑coded item `HelloFromLSP` | //! | ← | `textDocument/hover` | shows *Hello from minimal_lsp* markdown | //! | ← | `textDocument/formatting` | pipes the doc through **rustfmt** and returns a full‑file edit | //! //! ### Quick start //! ```bash //! cd rust-analyzer/lib/lsp-server //! cargo run --example minimal_lsp //! ``` //! //! ### Minimal manual session (all nine packets) //! ```no_run //! # 1. initialize - server replies with capabilities //! Content-Length: 85 //! {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{}}} //! //! # 2. initialized - no response expected //! Content-Length: 59 //! {"jsonrpc":"2.0","method":"initialized","params":{}} //! //! # 3. didOpen - provide initial buffer text //! Content-Length: 173 //! {"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///tmp/foo.rs","languageId":"rust","version":1,"text":"fn main( ){println!(\"hi\") }"}}} //! //! # 4. completion - expect HelloFromLSP //! Content-Length: 139 //! {"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:///tmp/foo.rs"},"position":{"line":0,"character":0}}} //! //! # 5. hover - expect markdown greeting //! Content-Length: 135 //! {"jsonrpc":"2.0","id":3,"method":"textDocument/hover","params":{"textDocument":{"uri":"file:///tmp/foo.rs"},"position":{"line":0,"character":0}}} //! //! # 6. goto-definition - dummy empty array //! Content-Length: 139 //! {"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///tmp/foo.rs"},"position":{"line":0,"character":0}}} //! //! # 7. formatting - rustfmt full document //! Content-Length: 157 //! {"jsonrpc":"2.0","id":5,"method":"textDocument/formatting","params":{"textDocument":{"uri":"file:///tmp/foo.rs"},"options":{"tabSize":4,"insertSpaces":true}}} //! //! # 8. shutdown request - server acks and prepares to exit //! Content-Length: 67 //! {"jsonrpc":"2.0","id":6,"method":"shutdown","params":null} //! //! # 9. exit notification - terminates the server //! Content-Length: 54 //! {"jsonrpc":"2.0","method":"exit","params":null} //! ``` //! use std::{error::Error, io::Write}; use rustc_hash::FxHashMap; // fast hash map use std::process::Stdio; use toolchain::command; // clippy-approved wrapper #[allow(clippy::print_stderr, clippy::disallowed_types, clippy::disallowed_methods)] use anyhow::{Context, Result, anyhow, bail}; use lsp_server::{Connection, Message, Request as ServerRequest, RequestId, Response}; use lsp_types::notification::Notification as _; // for METHOD consts use lsp_types::request::Request as _; use lsp_types::{ CompletionItem, CompletionItemKind, // capability helpers CompletionOptions, CompletionResponse, Diagnostic, DiagnosticSeverity, DidChangeTextDocumentParams, DidOpenTextDocumentParams, DocumentFormattingParams, Hover, HoverContents, HoverProviderCapability, // core InitializeParams, MarkedString, OneOf, Position, PublishDiagnosticsParams, Range, ServerCapabilities, TextDocumentSyncCapability, TextDocumentSyncKind, TextEdit, Url, // notifications notification::{DidChangeTextDocument, DidOpenTextDocument, PublishDiagnostics}, // requests request::{Completion, Formatting, GotoDefinition, HoverRequest}, }; // for METHOD consts // ===================================================================== // main // ===================================================================== #[allow(clippy::print_stderr)] fn main() -> std::result::Result<(), Box> { log::error!("starting minimal_lsp"); // transport let (connection, io_thread) = Connection::stdio(); // advertised capabilities let caps = ServerCapabilities { text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)), completion_provider: Some(CompletionOptions::default()), definition_provider: Some(OneOf::Left(true)), hover_provider: Some(HoverProviderCapability::Simple(true)), document_formatting_provider: Some(OneOf::Left(true)), ..Default::default() }; let init_value = serde_json::json!({ "capabilities": caps, "offsetEncoding": ["utf-8"], }); let init_params = connection.initialize(init_value)?; main_loop(connection, init_params)?; io_thread.join()?; log::error!("shutting down server"); Ok(()) } // ===================================================================== // event loop // ===================================================================== fn main_loop( connection: Connection, params: serde_json::Value, ) -> std::result::Result<(), Box> { let _init: InitializeParams = serde_json::from_value(params)?; let mut docs: FxHashMap = FxHashMap::default(); for msg in &connection.receiver { match msg { Message::Request(req) => { if connection.handle_shutdown(&req)? { break; } if let Err(err) = handle_request(&connection, &req, &mut docs) { log::error!("[lsp] request {} failed: {err}", &req.method); } } Message::Notification(note) => { if let Err(err) = handle_notification(&connection, ¬e, &mut docs) { log::error!("[lsp] notification {} failed: {err}", note.method); } } Message::Response(resp) => log::error!("[lsp] response: {resp:?}"), } } Ok(()) } // ===================================================================== // notifications // ===================================================================== fn handle_notification( conn: &Connection, note: &lsp_server::Notification, docs: &mut FxHashMap, ) -> Result<()> { match note.method.as_str() { DidOpenTextDocument::METHOD => { let p: DidOpenTextDocumentParams = serde_json::from_value(note.params.clone())?; let uri = p.text_document.uri; docs.insert(uri.clone(), p.text_document.text); publish_dummy_diag(conn, &uri)?; } DidChangeTextDocument::METHOD => { let p: DidChangeTextDocumentParams = serde_json::from_value(note.params.clone())?; if let Some(change) = p.content_changes.into_iter().next() { let uri = p.text_document.uri; docs.insert(uri.clone(), change.text); publish_dummy_diag(conn, &uri)?; } } _ => {} } Ok(()) } // ===================================================================== // requests // ===================================================================== fn handle_request( conn: &Connection, req: &ServerRequest, docs: &mut FxHashMap, ) -> Result<()> { match req.method.as_str() { GotoDefinition::METHOD => { send_ok(conn, req.id.clone(), &lsp_types::GotoDefinitionResponse::Array(Vec::new()))?; } Completion::METHOD => { let item = CompletionItem { label: "HelloFromLSP".into(), kind: Some(CompletionItemKind::FUNCTION), detail: Some("dummy completion".into()), ..Default::default() }; send_ok(conn, req.id.clone(), &CompletionResponse::Array(vec![item]))?; } HoverRequest::METHOD => { let hover = Hover { contents: HoverContents::Scalar(MarkedString::String( "Hello from *minimal_lsp*".into(), )), range: None, }; send_ok(conn, req.id.clone(), &hover)?; } Formatting::METHOD => { let p: DocumentFormattingParams = serde_json::from_value(req.params.clone())?; let uri = p.text_document.uri; let text = docs .get(&uri) .ok_or_else(|| anyhow!("document not in cache – did you send DidOpen?"))?; let formatted = run_rustfmt(text)?; let edit = TextEdit { range: full_range(text), new_text: formatted }; send_ok(conn, req.id.clone(), &vec![edit])?; } _ => send_err( conn, req.id.clone(), lsp_server::ErrorCode::MethodNotFound, "unhandled method", )?, } Ok(()) } // ===================================================================== // diagnostics // ===================================================================== fn publish_dummy_diag(conn: &Connection, uri: &Url) -> Result<()> { let diag = Diagnostic { range: Range::new(Position::new(0, 0), Position::new(0, 1)), severity: Some(DiagnosticSeverity::INFORMATION), code: None, code_description: None, source: Some("minimal_lsp".into()), message: "dummy diagnostic".into(), related_information: None, tags: None, data: None, }; let params = PublishDiagnosticsParams { uri: uri.clone(), diagnostics: vec![diag], version: None }; conn.sender.send(Message::Notification(lsp_server::Notification::new( PublishDiagnostics::METHOD.to_owned(), params, )))?; Ok(()) } // ===================================================================== // helpers // ===================================================================== fn run_rustfmt(input: &str) -> Result { let cwd = std::env::current_dir().expect("can't determine CWD"); let mut child = command("rustfmt", &cwd, &FxHashMap::default()) .arg("--emit") .arg("stdout") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .context("failed to spawn rustfmt – is it installed?")?; let Some(stdin) = child.stdin.as_mut() else { bail!("stdin unavailable"); }; stdin.write_all(input.as_bytes())?; let output = child.wait_with_output()?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); bail!("rustfmt failed: {stderr}"); } Ok(String::from_utf8(output.stdout)?) } fn full_range(text: &str) -> Range { let last_line_idx = text.lines().count().saturating_sub(1) as u32; let last_col = text.lines().last().map_or(0, |l| l.chars().count()) as u32; Range::new(Position::new(0, 0), Position::new(last_line_idx, last_col)) } fn send_ok(conn: &Connection, id: RequestId, result: &T) -> Result<()> { let resp = Response { id, result: Some(serde_json::to_value(result)?), error: None }; conn.sender.send(Message::Response(resp))?; Ok(()) } fn send_err( conn: &Connection, id: RequestId, code: lsp_server::ErrorCode, msg: &str, ) -> Result<()> { let resp = Response { id, result: None, error: Some(lsp_server::ResponseError { code: code as i32, message: msg.into(), data: None, }), }; conn.sender.send(Message::Response(resp))?; Ok(()) } lsp-server-0.7.9/src/error.rs000064400000000000000000000036451046102023000142410ustar 00000000000000use std::fmt; use crate::{Notification, Request}; #[derive(Debug, Clone, PartialEq)] pub struct ProtocolError(String, bool); impl ProtocolError { pub(crate) fn new(msg: impl Into) -> Self { ProtocolError(msg.into(), false) } pub(crate) fn disconnected() -> ProtocolError { ProtocolError("disconnected channel".into(), true) } /// Whether this error occurred due to a disconnected channel. pub fn channel_is_disconnected(&self) -> bool { self.1 } } impl std::error::Error for ProtocolError {} impl fmt::Display for ProtocolError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } #[derive(Debug)] pub enum ExtractError { /// The extracted message was of a different method than expected. MethodMismatch(T), /// Failed to deserialize the message. JsonError { method: String, error: serde_json::Error }, } impl std::error::Error for ExtractError {} impl fmt::Display for ExtractError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ExtractError::MethodMismatch(req) => { write!(f, "Method mismatch for request '{}'", req.method) } ExtractError::JsonError { method, error } => { write!(f, "Invalid request\nMethod: {method}\n error: {error}",) } } } } impl std::error::Error for ExtractError {} impl fmt::Display for ExtractError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ExtractError::MethodMismatch(req) => { write!(f, "Method mismatch for notification '{}'", req.method) } ExtractError::JsonError { method, error } => { write!(f, "Invalid notification\nMethod: {method}\n error: {error}") } } } } lsp-server-0.7.9/src/lib.rs000064400000000000000000000367371046102023000136660ustar 00000000000000//! A language server scaffold, exposing a synchronous crossbeam-channel based API. //! This crate handles protocol handshaking and parsing messages, while you //! control the message dispatch loop yourself. //! //! Run with `RUST_LOG=lsp_server=debug` to see all the messages. #![warn(rust_2018_idioms, unused_lifetimes)] #![allow(clippy::print_stdout, clippy::disallowed_types)] mod error; mod msg; mod req_queue; mod socket; mod stdio; use std::{ io, net::{TcpListener, TcpStream, ToSocketAddrs}, }; use crossbeam_channel::{Receiver, RecvError, RecvTimeoutError, Sender}; pub use crate::{ error::{ExtractError, ProtocolError}, msg::{ErrorCode, Message, Notification, Request, RequestId, Response, ResponseError}, req_queue::{Incoming, Outgoing, ReqQueue}, stdio::IoThreads, }; /// Connection is just a pair of channels of LSP messages. pub struct Connection { pub sender: Sender, pub receiver: Receiver, } impl Connection { /// Create connection over standard in/standard out. /// /// Use this to create a real language server. pub fn stdio() -> (Connection, IoThreads) { let (sender, receiver, io_threads) = stdio::stdio_transport(); (Connection { sender, receiver }, io_threads) } /// Open a connection over tcp. /// This call blocks until a connection is established. /// /// Use this to create a real language server. pub fn connect(addr: A) -> io::Result<(Connection, IoThreads)> { let stream = TcpStream::connect(addr)?; let (sender, receiver, io_threads) = socket::socket_transport(stream); Ok((Connection { sender, receiver }, io_threads)) } /// Listen for a connection over tcp. /// This call blocks until a connection is established. /// /// Use this to create a real language server. pub fn listen(addr: A) -> io::Result<(Connection, IoThreads)> { let listener = TcpListener::bind(addr)?; let (stream, _) = listener.accept()?; let (sender, receiver, io_threads) = socket::socket_transport(stream); Ok((Connection { sender, receiver }, io_threads)) } /// Creates a pair of connected connections. /// /// Use this for testing. pub fn memory() -> (Connection, Connection) { let (s1, r1) = crossbeam_channel::unbounded(); let (s2, r2) = crossbeam_channel::unbounded(); (Connection { sender: s1, receiver: r2 }, Connection { sender: s2, receiver: r1 }) } /// Starts the initialization process by waiting for an initialize /// request from the client. Use this for more advanced customization than /// `initialize` can provide. /// /// Returns the request id and serialized `InitializeParams` from the client. /// /// # Example /// /// ```no_run /// use std::error::Error; /// use lsp_types::{ClientCapabilities, InitializeParams, ServerCapabilities}; /// /// use lsp_server::{Connection, Message, Request, RequestId, Response}; /// /// fn main() -> Result<(), Box> { /// // Create the transport. Includes the stdio (stdin and stdout) versions but this could /// // also be implemented to use sockets or HTTP. /// let (connection, io_threads) = Connection::stdio(); /// /// // Run the server /// let (id, params) = connection.initialize_start()?; /// /// let init_params: InitializeParams = serde_json::from_value(params).unwrap(); /// let client_capabilities: ClientCapabilities = init_params.capabilities; /// let server_capabilities = ServerCapabilities::default(); /// /// let initialize_data = serde_json::json!({ /// "capabilities": server_capabilities, /// "serverInfo": { /// "name": "lsp-server-test", /// "version": "0.1" /// } /// }); /// /// connection.initialize_finish(id, initialize_data)?; /// /// // ... Run main loop ... /// /// Ok(()) /// } /// ``` pub fn initialize_start(&self) -> Result<(RequestId, serde_json::Value), ProtocolError> { self.initialize_start_while(|| true) } /// Starts the initialization process by waiting for an initialize as described in /// [`Self::initialize_start`] as long as `running` returns /// `true` while the return value can be changed through a sig handler such as `CTRL + C`. /// /// # Example /// /// ```rust /// use std::sync::atomic::{AtomicBool, Ordering}; /// use std::sync::Arc; /// # use std::error::Error; /// # use lsp_types::{ClientCapabilities, InitializeParams, ServerCapabilities}; /// # use lsp_server::{Connection, Message, Request, RequestId, Response}; /// # fn main() -> Result<(), Box> { /// let running = Arc::new(AtomicBool::new(true)); /// # running.store(true, Ordering::SeqCst); /// let r = running.clone(); /// /// ctrlc::set_handler(move || { /// r.store(false, Ordering::SeqCst); /// }).expect("Error setting Ctrl-C handler"); /// /// let (connection, io_threads) = Connection::stdio(); /// /// let res = connection.initialize_start_while(|| running.load(Ordering::SeqCst)); /// # assert!(res.is_err()); /// /// # Ok(()) /// # } /// ``` pub fn initialize_start_while( &self, running: C, ) -> Result<(RequestId, serde_json::Value), ProtocolError> where C: Fn() -> bool, { while running() { let msg = match self.receiver.recv_timeout(std::time::Duration::from_secs(1)) { Ok(msg) => msg, Err(RecvTimeoutError::Timeout) => { continue; } Err(RecvTimeoutError::Disconnected) => return Err(ProtocolError::disconnected()), }; match msg { Message::Request(req) if req.is_initialize() => return Ok((req.id, req.params)), // Respond to non-initialize requests with ServerNotInitialized Message::Request(req) => { let resp = Response::new_err( req.id.clone(), ErrorCode::ServerNotInitialized as i32, format!("expected initialize request, got {req:?}"), ); self.sender.send(resp.into()).unwrap(); continue; } Message::Notification(n) if !n.is_exit() => { continue; } msg => { return Err(ProtocolError::new(format!( "expected initialize request, got {msg:?}" ))); } }; } Err(ProtocolError::new(String::from( "Initialization has been aborted during initialization", ))) } /// Finishes the initialization process by sending an `InitializeResult` to the client pub fn initialize_finish( &self, initialize_id: RequestId, initialize_result: serde_json::Value, ) -> Result<(), ProtocolError> { let resp = Response::new_ok(initialize_id, initialize_result); self.sender.send(resp.into()).unwrap(); match &self.receiver.recv() { Ok(Message::Notification(n)) if n.is_initialized() => Ok(()), Ok(msg) => Err(ProtocolError::new(format!( r#"expected initialized notification, got: {msg:?}"# ))), Err(RecvError) => Err(ProtocolError::disconnected()), } } /// Finishes the initialization process as described in [`Self::initialize_finish`] as /// long as `running` returns `true` while the return value can be changed through a sig /// handler such as `CTRL + C`. pub fn initialize_finish_while( &self, initialize_id: RequestId, initialize_result: serde_json::Value, running: C, ) -> Result<(), ProtocolError> where C: Fn() -> bool, { let resp = Response::new_ok(initialize_id, initialize_result); self.sender.send(resp.into()).unwrap(); while running() { let msg = match self.receiver.recv_timeout(std::time::Duration::from_secs(1)) { Ok(msg) => msg, Err(RecvTimeoutError::Timeout) => { continue; } Err(RecvTimeoutError::Disconnected) => { return Err(ProtocolError::disconnected()); } }; match msg { Message::Notification(n) if n.is_initialized() => { return Ok(()); } msg => { return Err(ProtocolError::new(format!( r#"expected initialized notification, got: {msg:?}"# ))); } } } Err(ProtocolError::new(String::from( "Initialization has been aborted during initialization", ))) } /// Initialize the connection. Sends the server capabilities /// to the client and returns the serialized client capabilities /// on success. If more fine-grained initialization is required use /// `initialize_start`/`initialize_finish`. /// /// # Example /// /// ```no_run /// use std::error::Error; /// use lsp_types::ServerCapabilities; /// /// use lsp_server::{Connection, Message, Request, RequestId, Response}; /// /// fn main() -> Result<(), Box> { /// // Create the transport. Includes the stdio (stdin and stdout) versions but this could /// // also be implemented to use sockets or HTTP. /// let (connection, io_threads) = Connection::stdio(); /// /// // Run the server /// let server_capabilities = serde_json::to_value(&ServerCapabilities::default()).unwrap(); /// let initialization_params = connection.initialize(server_capabilities)?; /// /// // ... Run main loop ... /// /// Ok(()) /// } /// ``` pub fn initialize( &self, server_capabilities: serde_json::Value, ) -> Result { let (id, params) = self.initialize_start()?; let initialize_data = serde_json::json!({ "capabilities": server_capabilities, }); self.initialize_finish(id, initialize_data)?; Ok(params) } /// Initialize the connection as described in [`Self::initialize`] as long as `running` returns /// `true` while the return value can be changed through a sig handler such as `CTRL + C`. /// /// # Example /// /// ```rust /// use std::sync::atomic::{AtomicBool, Ordering}; /// use std::sync::Arc; /// # use std::error::Error; /// # use lsp_types::ServerCapabilities; /// # use lsp_server::{Connection, Message, Request, RequestId, Response}; /// /// # fn main() -> Result<(), Box> { /// let running = Arc::new(AtomicBool::new(true)); /// # running.store(true, Ordering::SeqCst); /// let r = running.clone(); /// /// ctrlc::set_handler(move || { /// r.store(false, Ordering::SeqCst); /// }).expect("Error setting Ctrl-C handler"); /// /// let (connection, io_threads) = Connection::stdio(); /// /// let server_capabilities = serde_json::to_value(&ServerCapabilities::default()).unwrap(); /// let initialization_params = connection.initialize_while( /// server_capabilities, /// || running.load(Ordering::SeqCst) /// ); /// /// # assert!(initialization_params.is_err()); /// # Ok(()) /// # } /// ``` pub fn initialize_while( &self, server_capabilities: serde_json::Value, running: C, ) -> Result where C: Fn() -> bool, { let (id, params) = self.initialize_start_while(&running)?; let initialize_data = serde_json::json!({ "capabilities": server_capabilities, }); self.initialize_finish_while(id, initialize_data, running)?; Ok(params) } /// If `req` is `Shutdown`, respond to it and return `true`, otherwise return `false` pub fn handle_shutdown(&self, req: &Request) -> Result { if !req.is_shutdown() { return Ok(false); } let resp = Response::new_ok(req.id.clone(), ()); let _ = self.sender.send(resp.into()); match &self.receiver.recv_timeout(std::time::Duration::from_secs(30)) { Ok(Message::Notification(n)) if n.is_exit() => (), Ok(msg) => { return Err(ProtocolError::new(format!( "unexpected message during shutdown: {msg:?}" ))); } Err(RecvTimeoutError::Timeout) => { return Err(ProtocolError::new( "timed out waiting for exit notification".to_owned(), )); } Err(RecvTimeoutError::Disconnected) => { return Err(ProtocolError::new( "channel disconnected waiting for exit notification".to_owned(), )); } } Ok(true) } } #[cfg(test)] mod tests { use crossbeam_channel::unbounded; use lsp_types::notification::{Exit, Initialized, Notification}; use lsp_types::request::{Initialize, Request}; use lsp_types::{InitializeParams, InitializedParams}; use serde_json::to_value; use crate::{Connection, Message, ProtocolError, RequestId}; struct TestCase { test_messages: Vec, expected_resp: Result<(RequestId, serde_json::Value), ProtocolError>, } fn initialize_start_test(test_case: TestCase) { let (reader_sender, reader_receiver) = unbounded::(); let (writer_sender, writer_receiver) = unbounded::(); let conn = Connection { sender: writer_sender, receiver: reader_receiver }; for msg in test_case.test_messages { assert!(reader_sender.send(msg).is_ok()); } let resp = conn.initialize_start(); assert_eq!(test_case.expected_resp, resp); assert!(writer_receiver.recv_timeout(std::time::Duration::from_secs(1)).is_err()); } #[test] fn not_exit_notification() { let notification = crate::Notification { method: Initialized::METHOD.to_owned(), params: to_value(InitializedParams {}).unwrap(), }; let params_as_value = to_value(InitializeParams::default()).unwrap(); let req_id = RequestId::from(234); let request = crate::Request { id: req_id.clone(), method: Initialize::METHOD.to_owned(), params: params_as_value.clone(), }; initialize_start_test(TestCase { test_messages: vec![notification.into(), request.into()], expected_resp: Ok((req_id, params_as_value)), }); } #[test] fn exit_notification() { let notification = crate::Notification { method: Exit::METHOD.to_owned(), params: to_value(()).unwrap() }; let notification_msg = Message::from(notification); initialize_start_test(TestCase { test_messages: vec![notification_msg.clone()], expected_resp: Err(ProtocolError::new(format!( "expected initialize request, got {notification_msg:?}" ))), }); } } lsp-server-0.7.9/src/msg.rs000064400000000000000000000255751046102023000137040ustar 00000000000000use std::{ fmt, io::{self, BufRead, Write}, }; use serde::de::DeserializeOwned; use serde_derive::{Deserialize, Serialize}; use crate::error::ExtractError; #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(untagged)] pub enum Message { Request(Request), Response(Response), Notification(Notification), } impl From for Message { fn from(request: Request) -> Message { Message::Request(request) } } impl From for Message { fn from(response: Response) -> Message { Message::Response(response) } } impl From for Message { fn from(notification: Notification) -> Message { Message::Notification(notification) } } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[serde(transparent)] pub struct RequestId(IdRepr); #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[serde(untagged)] enum IdRepr { I32(i32), String(String), } impl From for RequestId { fn from(id: i32) -> RequestId { RequestId(IdRepr::I32(id)) } } impl From for RequestId { fn from(id: String) -> RequestId { RequestId(IdRepr::String(id)) } } impl fmt::Display for RequestId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.0 { IdRepr::I32(it) => fmt::Display::fmt(it, f), // Use debug here, to make it clear that `92` and `"92"` are // different, and to reduce WTF factor if the sever uses `" "` as an // ID. IdRepr::String(it) => fmt::Debug::fmt(it, f), } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Request { pub id: RequestId, pub method: String, #[serde(default = "serde_json::Value::default")] #[serde(skip_serializing_if = "serde_json::Value::is_null")] pub params: serde_json::Value, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Response { // JSON-RPC allows this to be null if we can't find or parse the // request id. We fail deserialization in that case, so we just // make this field mandatory. pub id: RequestId, #[serde(skip_serializing_if = "Option::is_none", default)] pub result: Option, #[serde(skip_serializing_if = "Option::is_none", default)] pub error: Option, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ResponseError { pub code: i32, pub message: String, #[serde(skip_serializing_if = "Option::is_none", default)] pub data: Option, } #[derive(Clone, Copy, Debug)] #[non_exhaustive] pub enum ErrorCode { // Defined by JSON RPC: ParseError = -32700, InvalidRequest = -32600, MethodNotFound = -32601, InvalidParams = -32602, InternalError = -32603, ServerErrorStart = -32099, ServerErrorEnd = -32000, /// Error code indicating that a server received a notification or /// request before the server has received the `initialize` request. ServerNotInitialized = -32002, UnknownErrorCode = -32001, // Defined by the protocol: /// The client has canceled a request and a server has detected /// the cancel. RequestCanceled = -32800, /// The server detected that the content of a document got /// modified outside normal conditions. A server should /// NOT send this error code if it detects a content change /// in it unprocessed messages. The result even computed /// on an older state might still be useful for the client. /// /// If a client decides that a result is not of any use anymore /// the client should cancel the request. ContentModified = -32801, /// The server cancelled the request. This error code should /// only be used for requests that explicitly support being /// server cancellable. /// /// @since 3.17.0 ServerCancelled = -32802, /// A request failed but it was syntactically correct, e.g the /// method name was known and the parameters were valid. The error /// message should contain human readable information about why /// the request failed. /// /// @since 3.17.0 RequestFailed = -32803, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Notification { pub method: String, #[serde(default = "serde_json::Value::default")] #[serde(skip_serializing_if = "serde_json::Value::is_null")] pub params: serde_json::Value, } fn invalid_data(error: impl Into>) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, error) } macro_rules! invalid_data { ($($tt:tt)*) => (invalid_data(format!($($tt)*))) } impl Message { pub fn read(r: &mut impl BufRead) -> io::Result> { Message::_read(r) } fn _read(r: &mut dyn BufRead) -> io::Result> { let text = match read_msg_text(r)? { None => return Ok(None), Some(text) => text, }; let msg = match serde_json::from_str(&text) { Ok(msg) => msg, Err(e) => { return Err(invalid_data!("malformed LSP payload: {:?}", e)); } }; Ok(Some(msg)) } pub fn write(&self, w: &mut impl Write) -> io::Result<()> { self._write(w) } fn _write(&self, w: &mut dyn Write) -> io::Result<()> { #[derive(Serialize)] struct JsonRpc<'a> { jsonrpc: &'static str, #[serde(flatten)] msg: &'a Message, } let text = serde_json::to_string(&JsonRpc { jsonrpc: "2.0", msg: self })?; write_msg_text(w, &text) } } impl Response { pub fn new_ok(id: RequestId, result: R) -> Response { Response { id, result: Some(serde_json::to_value(result).unwrap()), error: None } } pub fn new_err(id: RequestId, code: i32, message: String) -> Response { let error = ResponseError { code, message, data: None }; Response { id, result: None, error: Some(error) } } } impl Request { pub fn new(id: RequestId, method: String, params: P) -> Request { Request { id, method, params: serde_json::to_value(params).unwrap() } } pub fn extract( self, method: &str, ) -> Result<(RequestId, P), ExtractError> { if self.method != method { return Err(ExtractError::MethodMismatch(self)); } match serde_json::from_value(self.params) { Ok(params) => Ok((self.id, params)), Err(error) => Err(ExtractError::JsonError { method: self.method, error }), } } pub(crate) fn is_shutdown(&self) -> bool { self.method == "shutdown" } pub(crate) fn is_initialize(&self) -> bool { self.method == "initialize" } } impl Notification { pub fn new(method: String, params: impl serde::Serialize) -> Notification { Notification { method, params: serde_json::to_value(params).unwrap() } } pub fn extract( self, method: &str, ) -> Result> { if self.method != method { return Err(ExtractError::MethodMismatch(self)); } match serde_json::from_value(self.params) { Ok(params) => Ok(params), Err(error) => Err(ExtractError::JsonError { method: self.method, error }), } } pub(crate) fn is_exit(&self) -> bool { self.method == "exit" } pub(crate) fn is_initialized(&self) -> bool { self.method == "initialized" } } fn read_msg_text(inp: &mut dyn BufRead) -> io::Result> { let mut size = None; let mut buf = String::new(); loop { buf.clear(); if inp.read_line(&mut buf)? == 0 { return Ok(None); } if !buf.ends_with("\r\n") { return Err(invalid_data!("malformed header: {:?}", buf)); } let buf = &buf[..buf.len() - 2]; if buf.is_empty() { break; } let mut parts = buf.splitn(2, ": "); let header_name = parts.next().unwrap(); let header_value = parts.next().ok_or_else(|| invalid_data!("malformed header: {:?}", buf))?; if header_name.eq_ignore_ascii_case("Content-Length") { size = Some(header_value.parse::().map_err(invalid_data)?); } } let size: usize = size.ok_or_else(|| invalid_data!("no Content-Length"))?; let mut buf = buf.into_bytes(); buf.resize(size, 0); inp.read_exact(&mut buf)?; let buf = String::from_utf8(buf).map_err(invalid_data)?; log::debug!("< {buf}"); Ok(Some(buf)) } fn write_msg_text(out: &mut dyn Write, msg: &str) -> io::Result<()> { log::debug!("> {msg}"); write!(out, "Content-Length: {}\r\n\r\n", msg.len())?; out.write_all(msg.as_bytes())?; out.flush()?; Ok(()) } #[cfg(test)] mod tests { use super::{Message, Notification, Request, RequestId}; #[test] fn shutdown_with_explicit_null() { let text = "{\"jsonrpc\": \"2.0\",\"id\": 3,\"method\": \"shutdown\", \"params\": null }"; let msg: Message = serde_json::from_str(text).unwrap(); assert!( matches!(msg, Message::Request(req) if req.id == 3.into() && req.method == "shutdown") ); } #[test] fn shutdown_with_no_params() { let text = "{\"jsonrpc\": \"2.0\",\"id\": 3,\"method\": \"shutdown\"}"; let msg: Message = serde_json::from_str(text).unwrap(); assert!( matches!(msg, Message::Request(req) if req.id == 3.into() && req.method == "shutdown") ); } #[test] fn notification_with_explicit_null() { let text = "{\"jsonrpc\": \"2.0\",\"method\": \"exit\", \"params\": null }"; let msg: Message = serde_json::from_str(text).unwrap(); assert!(matches!(msg, Message::Notification(not) if not.method == "exit")); } #[test] fn notification_with_no_params() { let text = "{\"jsonrpc\": \"2.0\",\"method\": \"exit\"}"; let msg: Message = serde_json::from_str(text).unwrap(); assert!(matches!(msg, Message::Notification(not) if not.method == "exit")); } #[test] fn serialize_request_with_null_params() { let msg = Message::Request(Request { id: RequestId::from(3), method: "shutdown".into(), params: serde_json::Value::Null, }); let serialized = serde_json::to_string(&msg).unwrap(); assert_eq!("{\"id\":3,\"method\":\"shutdown\"}", serialized); } #[test] fn serialize_notification_with_null_params() { let msg = Message::Notification(Notification { method: "exit".into(), params: serde_json::Value::Null, }); let serialized = serde_json::to_string(&msg).unwrap(); assert_eq!("{\"method\":\"exit\"}", serialized); } } lsp-server-0.7.9/src/req_queue.rs000064400000000000000000000034061046102023000150760ustar 00000000000000use std::collections::HashMap; use crate::{ErrorCode, Request, RequestId, Response, ResponseError}; /// Manages the set of pending requests, both incoming and outgoing. #[derive(Debug)] pub struct ReqQueue { pub incoming: Incoming, pub outgoing: Outgoing, } impl Default for ReqQueue { fn default() -> ReqQueue { ReqQueue { incoming: Incoming { pending: HashMap::default() }, outgoing: Outgoing { next_id: 0, pending: HashMap::default() }, } } } #[derive(Debug)] pub struct Incoming { pending: HashMap, } #[derive(Debug)] pub struct Outgoing { next_id: i32, pending: HashMap, } impl Incoming { pub fn register(&mut self, id: RequestId, data: I) { self.pending.insert(id, data); } pub fn cancel(&mut self, id: RequestId) -> Option { let _data = self.complete(&id)?; let error = ResponseError { code: ErrorCode::RequestCanceled as i32, message: "canceled by client".to_owned(), data: None, }; Some(Response { id, result: None, error: Some(error) }) } pub fn complete(&mut self, id: &RequestId) -> Option { self.pending.remove(id) } pub fn is_completed(&self, id: &RequestId) -> bool { !self.pending.contains_key(id) } } impl Outgoing { pub fn register(&mut self, method: String, params: P, data: O) -> Request { let id = RequestId::from(self.next_id); self.pending.insert(id.clone(), data); self.next_id += 1; Request::new(id, method, params) } pub fn complete(&mut self, id: RequestId) -> Option { self.pending.remove(&id) } } lsp-server-0.7.9/src/socket.rs000064400000000000000000000035051046102023000143730ustar 00000000000000use std::{ io::{self, BufReader}, net::TcpStream, thread, }; use crossbeam_channel::{Receiver, Sender, bounded}; use crate::{ Message, stdio::{IoThreads, make_io_threads}, }; pub(crate) fn socket_transport( stream: TcpStream, ) -> (Sender, Receiver, IoThreads) { let (reader_receiver, reader) = make_reader(stream.try_clone().unwrap()); let (writer_sender, writer, messages_to_drop) = make_write(stream); let dropper = std::thread::spawn(move || { messages_to_drop.into_iter().for_each(drop); }); let io_threads = make_io_threads(reader, writer, dropper); (writer_sender, reader_receiver, io_threads) } fn make_reader(stream: TcpStream) -> (Receiver, thread::JoinHandle>) { let (reader_sender, reader_receiver) = bounded::(0); let reader = thread::spawn(move || { let mut buf_read = BufReader::new(stream); while let Some(msg) = Message::read(&mut buf_read).unwrap() { let is_exit = matches!(&msg, Message::Notification(n) if n.is_exit()); reader_sender.send(msg).unwrap(); if is_exit { break; } } Ok(()) }); (reader_receiver, reader) } fn make_write( mut stream: TcpStream, ) -> (Sender, thread::JoinHandle>, Receiver) { let (writer_sender, writer_receiver) = bounded::(0); let (drop_sender, drop_receiver) = bounded::(0); let writer = thread::spawn(move || { writer_receiver .into_iter() .try_for_each(|it| { let result = it.write(&mut stream); let _ = drop_sender.send(it); result }) .unwrap(); Ok(()) }); (writer_sender, writer, drop_receiver) } lsp-server-0.7.9/src/stdio.rs000064400000000000000000000052401046102023000142230ustar 00000000000000use std::{ io::{self, stdin, stdout}, thread, }; use log::debug; use crossbeam_channel::{Receiver, Sender, bounded}; use crate::Message; /// Creates an LSP connection via stdio. pub(crate) fn stdio_transport() -> (Sender, Receiver, IoThreads) { let (drop_sender, drop_receiver) = bounded::(0); let (writer_sender, writer_receiver) = bounded::(0); let writer = thread::Builder::new() .name("LspServerWriter".to_owned()) .spawn(move || { let stdout = stdout(); let mut stdout = stdout.lock(); writer_receiver.into_iter().try_for_each(|it| { let result = it.write(&mut stdout); let _ = drop_sender.send(it); result }) }) .unwrap(); let dropper = thread::Builder::new() .name("LspMessageDropper".to_owned()) .spawn(move || drop_receiver.into_iter().for_each(drop)) .unwrap(); let (reader_sender, reader_receiver) = bounded::(0); let reader = thread::Builder::new() .name("LspServerReader".to_owned()) .spawn(move || { let stdin = stdin(); let mut stdin = stdin.lock(); while let Some(msg) = Message::read(&mut stdin)? { let is_exit = matches!(&msg, Message::Notification(n) if n.is_exit()); debug!("sending message {msg:#?}"); if let Err(e) = reader_sender.send(msg) { return Err(io::Error::other(e)); } if is_exit { break; } } Ok(()) }) .unwrap(); let threads = IoThreads { reader, writer, dropper }; (writer_sender, reader_receiver, threads) } // Creates an IoThreads pub(crate) fn make_io_threads( reader: thread::JoinHandle>, writer: thread::JoinHandle>, dropper: thread::JoinHandle<()>, ) -> IoThreads { IoThreads { reader, writer, dropper } } pub struct IoThreads { reader: thread::JoinHandle>, writer: thread::JoinHandle>, dropper: thread::JoinHandle<()>, } impl IoThreads { pub fn join(self) -> io::Result<()> { match self.reader.join() { Ok(r) => r?, Err(err) => std::panic::panic_any(err), } match self.dropper.join() { Ok(_) => (), Err(err) => { std::panic::panic_any(err); } } match self.writer.join() { Ok(r) => r, Err(err) => { std::panic::panic_any(err); } } } }