From 0bda3b822e797594e39602cead22b1e84d2466fe Mon Sep 17 00:00:00 2001
From: ChatDisabled <44729807+ChatDisabled@users.noreply.github.com>
Date: Sat, 19 Sep 2026 04:01:25 +0200
Subject: [PATCH 01/57] feat: add low-memory FiveM Lua language server
Closed files are reduced to a compact symbol summary and only open documents keep a syntax tree, which keeps the resident set around 10 MB for a handful of resources. Types come from LuaCATS annotations, table shapes, natives and manifest-aware globals; the lint rules are shared with qbx-lint so the editor and CI agree.
---
.gitattributes | 1 +
.gitignore | 1 +
Cargo.lock | 742 ++++++++++++++++
Cargo.toml | 33 +
LICENSE | 674 ++++++++++++++
rustfmt.toml | 2 +
scripts/bench.mjs | 93 ++
src/document.rs | 65 ++
src/features/code_action.rs | 48 +
src/features/completion.rs | 487 ++++++++++
src/features/definition.rs | 61 ++
src/features/diagnostics.rs | 88 ++
src/features/folding.rs | 91 ++
src/features/hover.rs | 195 ++++
src/features/inlay.rs | 78 ++
src/features/mod.rs | 29 +
src/features/references.rs | 136 +++
src/features/semantic_tokens.rs | 194 ++++
src/features/signature.rs | 63 ++
src/features/symbols.rs | 179 ++++
src/index.rs | 365 ++++++++
src/indexer.rs | 531 +++++++++++
src/infer.rs | 832 ++++++++++++++++++
src/lib.rs | 10 +
src/locate.rs | 148 ++++
src/luacats.rs | 318 +++++++
src/main.rs | 40 +
src/server.rs | 448 ++++++++++
src/types.rs | 573 ++++++++++++
src/workspace.rs | 235 +++++
.../resources/[core]/mylib/fxmanifest.lua | 7 +
.../fixtures/resources/[core]/mylib/init.lua | 54 ++
.../[core]/mylib/modules/settings.lua | 6 +
.../resources/[core]/mylib/server.lua | 14 +
.../resources/myresource/client/main.lua | 18 +
.../resources/myresource/fxmanifest.lua | 12 +
.../resources/myresource/server/main.lua | 11 +
.../resources/myresource/shared/config.lua | 11 +
tests/lsp.rs | 429 +++++++++
39 files changed, 7322 insertions(+)
create mode 100644 .gitattributes
create mode 100644 .gitignore
create mode 100644 Cargo.lock
create mode 100644 Cargo.toml
create mode 100644 LICENSE
create mode 100644 rustfmt.toml
create mode 100644 scripts/bench.mjs
create mode 100644 src/document.rs
create mode 100644 src/features/code_action.rs
create mode 100644 src/features/completion.rs
create mode 100644 src/features/definition.rs
create mode 100644 src/features/diagnostics.rs
create mode 100644 src/features/folding.rs
create mode 100644 src/features/hover.rs
create mode 100644 src/features/inlay.rs
create mode 100644 src/features/mod.rs
create mode 100644 src/features/references.rs
create mode 100644 src/features/semantic_tokens.rs
create mode 100644 src/features/signature.rs
create mode 100644 src/features/symbols.rs
create mode 100644 src/index.rs
create mode 100644 src/indexer.rs
create mode 100644 src/infer.rs
create mode 100644 src/lib.rs
create mode 100644 src/locate.rs
create mode 100644 src/luacats.rs
create mode 100644 src/main.rs
create mode 100644 src/server.rs
create mode 100644 src/types.rs
create mode 100644 src/workspace.rs
create mode 100644 tests/fixtures/resources/[core]/mylib/fxmanifest.lua
create mode 100644 tests/fixtures/resources/[core]/mylib/init.lua
create mode 100644 tests/fixtures/resources/[core]/mylib/modules/settings.lua
create mode 100644 tests/fixtures/resources/[core]/mylib/server.lua
create mode 100644 tests/fixtures/resources/myresource/client/main.lua
create mode 100644 tests/fixtures/resources/myresource/fxmanifest.lua
create mode 100644 tests/fixtures/resources/myresource/server/main.lua
create mode 100644 tests/fixtures/resources/myresource/shared/config.lua
create mode 100644 tests/lsp.rs
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..6313b56
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+* text=auto eol=lf
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..ea8c4bf
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+/target
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..b2ccdb5
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,742 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "borsh"
+version = "1.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
+dependencies = [
+ "bytes",
+ "cfg_aliases",
+]
+
+[[package]]
+name = "bstr"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"
+dependencies = [
+ "memchr",
+ "serde_core",
+]
+
+[[package]]
+name = "bytes"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
+[[package]]
+name = "crossbeam-channel"
+version = "0.5.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+
+[[package]]
+name = "displaydoc"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "either"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "globset"
+version = "0.4.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988"
+dependencies = [
+ "aho-corasick",
+ "bstr",
+ "log",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "icu_collections"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "utf8_iter",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
+
+[[package]]
+name = "icu_properties"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
+dependencies = [
+ "displaydoc",
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
+
+[[package]]
+name = "icu_provider"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "litemap"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
+
+[[package]]
+name = "log"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "lsp-server"
+version = "0.7.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d6ada348dbc2703cbe7637b2dda05cff84d3da2819c24abcb305dd613e0ba2e"
+dependencies = [
+ "crossbeam-channel",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+]
+
+[[package]]
+name = "lsp-types"
+version = "0.95.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e34d33a8e9b006cd3fc4fe69a921affa097bae4bb65f76271f4644f9a334365"
+dependencies = [
+ "bitflags",
+ "serde",
+ "serde_json",
+ "serde_repr",
+ "url",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "potential_utf"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
+dependencies = [
+ "zerovec",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "qbx_fivem_data"
+version = "0.1.0"
+
+[[package]]
+name = "qbx_lua_analysis"
+version = "0.1.0"
+dependencies = [
+ "globset",
+ "qbx_fivem_data",
+ "qbx_lua_syntax",
+ "rayon",
+ "rustc-hash",
+ "serde",
+ "smol_str",
+ "toml",
+ "walkdir",
+]
+
+[[package]]
+name = "qbx_lua_ls"
+version = "0.1.0"
+dependencies = [
+ "crossbeam-channel",
+ "lsp-server",
+ "lsp-types",
+ "qbx_fivem_data",
+ "qbx_lua_analysis",
+ "qbx_lua_syntax",
+ "rustc-hash",
+ "serde",
+ "serde_json",
+ "smol_str",
+ "walkdir",
+]
+
+[[package]]
+name = "qbx_lua_syntax"
+version = "0.1.0"
+dependencies = [
+ "smol_str",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "rayon"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_repr"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"
+
+[[package]]
+name = "smol_str"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4aaa7368fcf4852a4c2dd92df0cace6a71f2091ca0a23391ce7f3a31833f1523"
+dependencies = [
+ "borsh",
+ "serde_core",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "syn"
+version = "3.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tinystr"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "toml"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
+dependencies = [
+ "serde",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_edit",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.22.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
+dependencies = [
+ "indexmap",
+ "serde",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_write",
+ "winnow",
+]
+
+[[package]]
+name = "toml_write"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+ "serde_derive",
+]
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "winnow"
+version = "0.7.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "writeable"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+
+[[package]]
+name = "yoke"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zerotrie"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..bc12b91
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,33 @@
+[package]
+name = "qbx_lua_ls"
+description = "A low-memory language server for FiveM Lua"
+version = "0.1.0"
+edition = "2021"
+license = "GPL-3.0-or-later"
+repository = "https://github.com/Qbox-project/qbx-lua-ls"
+rust-version = "1.85"
+
+[[bin]]
+name = "qbx-lua-ls"
+path = "src/main.rs"
+
+[dependencies]
+# Switch these to git dependencies on Qbox-project/qbx-lint once that repository is published.
+qbx_lua_syntax = { path = "../qbx-lint/crates/qbx_lua_syntax" }
+qbx_lua_analysis = { path = "../qbx-lint/crates/qbx_lua_analysis", features = ["docs"] }
+qbx_fivem_data = { path = "../qbx-lint/crates/qbx_fivem_data", features = ["docs"] }
+lsp-server = "0.7"
+lsp-types = "0.95"
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+crossbeam-channel = "0.5"
+rustc-hash = "2"
+smol_str = "0.3"
+walkdir = "2"
+
+[profile.release]
+opt-level = 3
+lto = "fat"
+codegen-units = 1
+strip = true
+panic = "abort"
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/rustfmt.toml b/rustfmt.toml
new file mode 100644
index 0000000..c775577
--- /dev/null
+++ b/rustfmt.toml
@@ -0,0 +1,2 @@
+max_width = 120
+use_small_heuristics = "Max"
diff --git a/scripts/bench.mjs b/scripts/bench.mjs
new file mode 100644
index 0000000..213501f
--- /dev/null
+++ b/scripts/bench.mjs
@@ -0,0 +1,93 @@
+// Starts the server over stdio against a folder, opens one file and reports timings and memory.
+// usage: node scripts/bench.mjs [file-to-open] [server-binary]
+import { spawn, execFileSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const [workspace, fileToOpen, binary = 'target/release/qbx-lua-ls'] = process.argv.slice(2);
+if (!workspace) {
+ console.error('usage: node scripts/bench.mjs [file-to-open] [server-binary]');
+ process.exit(2);
+}
+
+const server = spawn(resolve(binary), [], { stdio: ['pipe', 'pipe', 'inherit'] });
+let buffer = Buffer.alloc(0);
+let nextId = 0;
+const pending = new Map();
+
+server.stdout.on('data', (chunk) => {
+ buffer = Buffer.concat([buffer, chunk]);
+ for (;;) {
+ const headerEnd = buffer.indexOf('\r\n\r\n');
+ if (headerEnd < 0) return;
+ const length = Number(/Content-Length: (\d+)/i.exec(buffer.subarray(0, headerEnd).toString())[1]);
+ if (buffer.length < headerEnd + 4 + length) return;
+ const message = JSON.parse(buffer.subarray(headerEnd + 4, headerEnd + 4 + length).toString());
+ buffer = buffer.subarray(headerEnd + 4 + length);
+ if (message.id !== undefined && message.method) {
+ send({ jsonrpc: '2.0', id: message.id, result: null });
+ } else if (message.id !== undefined) {
+ pending.get(message.id)?.(message.result);
+ pending.delete(message.id);
+ } else if (message.method === 'window/logMessage') {
+ console.log(`server: ${message.params.message}`);
+ }
+ }
+});
+
+function send(message) {
+ const body = JSON.stringify(message);
+ server.stdin.write(`Content-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`);
+}
+
+function request(method, params) {
+ const id = ++nextId;
+ const started = performance.now();
+ return new Promise((done) => {
+ pending.set(id, (result) => done({ result, ms: performance.now() - started }));
+ send({ jsonrpc: '2.0', id, method, params });
+ });
+}
+
+function memoryMb() {
+ if (process.platform === 'win32') {
+ const out = execFileSync('powershell', ['-NoProfile', '-Command', `(Get-Process -Id ${server.pid}).WorkingSet64`]);
+ return Number(out.toString().trim()) / 1024 / 1024;
+ }
+ const out = execFileSync('ps', ['-o', 'rss=', '-p', String(server.pid)]);
+ return Number(out.toString().trim()) / 1024;
+}
+
+const rootUri = pathToFileURL(resolve(workspace)).href;
+const init = await request('initialize', {
+ processId: process.pid,
+ rootUri,
+ capabilities: {},
+ workspaceFolders: [{ uri: rootUri, name: 'bench' }],
+});
+send({ jsonrpc: '2.0', method: 'initialized', params: {} });
+const status = await request('qbx/status', null);
+console.log(`initialize: ${init.ms.toFixed(0)} ms, index ready after: ${status.ms.toFixed(0)} ms`, status.result);
+console.log(`memory after indexing: ${memoryMb().toFixed(1)} MB`);
+
+if (fileToOpen) {
+ const uri = pathToFileURL(resolve(fileToOpen)).href;
+ const text = readFileSync(resolve(fileToOpen), 'utf8');
+ send({ jsonrpc: '2.0', method: 'textDocument/didOpen', params: { textDocument: { uri, languageId: 'lua', version: 1, text } } });
+ const lines = text.split('\n');
+ const line = Math.floor(lines.length / 2);
+ const position = { line, character: Math.min(4, lines[line].length) };
+ for (const method of ['textDocument/documentSymbol', 'textDocument/semanticTokens/full', 'textDocument/foldingRange']) {
+ const { ms } = await request(method, { textDocument: { uri } });
+ console.log(`${method}: ${ms.toFixed(1)} ms`);
+ }
+ for (const method of ['textDocument/hover', 'textDocument/completion', 'textDocument/definition']) {
+ const { ms } = await request(method, { textDocument: { uri }, position });
+ console.log(`${method}: ${ms.toFixed(1)} ms`);
+ }
+ console.log(`memory with one document open: ${memoryMb().toFixed(1)} MB`);
+}
+
+await request('shutdown', null);
+send({ jsonrpc: '2.0', method: 'exit' });
diff --git a/src/document.rs b/src/document.rs
new file mode 100644
index 0000000..92aec0a
--- /dev/null
+++ b/src/document.rs
@@ -0,0 +1,65 @@
+use std::path::PathBuf;
+
+use lsp_types::{Position, Range, TextDocumentContentChangeEvent, Url};
+use qbx_lua_analysis::scope::{resolve, Resolution};
+use qbx_lua_syntax::ast::Chunk;
+use qbx_lua_syntax::{parse, LineCol, LineIndex, Span};
+
+use crate::index::FileId;
+
+pub struct Document {
+ pub uri: Url,
+ pub path: PathBuf,
+ pub version: i32,
+ pub text: String,
+ pub lines: LineIndex,
+ pub chunk: Chunk,
+ pub resolution: Resolution,
+ pub file: FileId,
+}
+
+impl Document {
+ pub fn new(uri: Url, path: PathBuf, version: i32, text: String) -> Self {
+ let lines = LineIndex::new(&text);
+ let chunk = parse(&text);
+ let resolution = resolve(&chunk);
+ Self { uri, path, version, text, lines, chunk, resolution, file: 0 }
+ }
+
+ pub fn apply_changes(&mut self, version: i32, changes: Vec) {
+ for change in changes {
+ match change.range {
+ Some(range) => {
+ let start = self.offset(range.start) as usize;
+ let end = self.offset(range.end) as usize;
+ self.text.replace_range(start..end.max(start), &change.text);
+ self.lines = LineIndex::new(&self.text);
+ }
+ None => {
+ self.text = change.text;
+ self.lines = LineIndex::new(&self.text);
+ }
+ }
+ }
+ self.version = version;
+ self.chunk = parse(&self.text);
+ self.resolution = resolve(&self.chunk);
+ }
+
+ pub fn offset(&self, position: Position) -> u32 {
+ self.lines.offset_utf16(&self.text, LineCol { line: position.line, col: position.character })
+ }
+
+ pub fn position(&self, offset: u32) -> Position {
+ let pos = self.lines.line_col_utf16(&self.text, offset);
+ Position::new(pos.line, pos.col)
+ }
+
+ pub fn range(&self, span: Span) -> Range {
+ Range::new(self.position(span.start), self.position(span.end.max(span.start)))
+ }
+
+ pub fn is_manifest(&self) -> bool {
+ qbx_lua_analysis::project::is_manifest_file(&self.path)
+ }
+}
diff --git a/src/features/code_action.rs b/src/features/code_action.rs
new file mode 100644
index 0000000..95b32f2
--- /dev/null
+++ b/src/features/code_action.rs
@@ -0,0 +1,48 @@
+use std::collections::HashMap;
+
+use lsp_types::{CodeAction, CodeActionKind, CodeActionOrCommand, Diagnostic, NumberOrString, Position, Range, TextEdit, WorkspaceEdit};
+
+use super::diagnostics::{FixData, SOURCE};
+use crate::document::Document;
+
+fn edit_for(doc: &Document, edits: Vec) -> WorkspaceEdit {
+ WorkspaceEdit { changes: Some(HashMap::from([(doc.uri.clone(), edits)])), ..WorkspaceEdit::default() }
+}
+
+pub fn code_actions(doc: &Document, diagnostics: &[Diagnostic]) -> Vec {
+ let mut actions = Vec::new();
+ let ours = diagnostics.iter().filter(|d| d.source.as_deref() == Some(SOURCE));
+ for diagnostic in ours {
+ let Some(NumberOrString::String(code)) = &diagnostic.code else { continue };
+ let fix = diagnostic.data.clone().and_then(|data| serde_json::from_value::(data).ok());
+ if let Some(fix) = fix {
+ let edits = fix.edits.into_iter().map(|(range, text)| TextEdit::new(range, text)).collect();
+ actions.push(CodeActionOrCommand::CodeAction(CodeAction {
+ title: fix.title,
+ kind: Some(CodeActionKind::QUICKFIX),
+ diagnostics: Some(vec![diagnostic.clone()]),
+ edit: Some(edit_for(doc, edits)),
+ is_preferred: Some(true),
+ ..CodeAction::default()
+ }));
+ }
+ if code == "syntax-error" {
+ continue;
+ }
+ let line = diagnostic.range.start.line;
+ let line_text = doc.lines.line_span(line).text(&doc.text);
+ let indent: String = line_text.chars().take_while(|c| c.is_whitespace() && *c != '\n' && *c != '\r').collect();
+ let at = Position::new(line, 0);
+ actions.push(CodeActionOrCommand::CodeAction(CodeAction {
+ title: format!("Disable {code} for this line"),
+ kind: Some(CodeActionKind::QUICKFIX),
+ diagnostics: Some(vec![diagnostic.clone()]),
+ edit: Some(edit_for(
+ doc,
+ vec![TextEdit::new(Range::new(at, at), format!("{indent}-- qbx-lint: disable-next-line {code}\n"))],
+ )),
+ ..CodeAction::default()
+ }));
+ }
+ actions
+}
diff --git a/src/features/completion.rs b/src/features/completion.rs
new file mode 100644
index 0000000..385dc49
--- /dev/null
+++ b/src/features/completion.rs
@@ -0,0 +1,487 @@
+use lsp_types::{
+ CompletionItem, CompletionItemKind, CompletionItemTag, CompletionList, CompletionResponse, Documentation,
+ InsertTextFormat, Position,
+};
+use qbx_fivem_data::{native, native_docs, natives, Side};
+use qbx_lua_analysis::manifest::KNOWN_DIRECTIVES;
+use qbx_lua_analysis::project::relative_slash_path;
+use qbx_lua_analysis::scope::LocalKind;
+use qbx_lua_syntax::ast::ExprKind;
+use qbx_lua_syntax::{CommentKind, TokenKind};
+use rustc_hash::FxHashSet;
+use serde_json::json;
+
+use super::{lua_block, markdown, with_infer};
+use crate::document::Document;
+use crate::index::{EventKind, FileOrigin, SymbolKind};
+use crate::infer::{Infer, MemberInfo};
+use crate::locate::locate;
+use crate::types::Type;
+use crate::workspace::Workspace;
+
+const MAX_NATIVES: usize = 120;
+const MAX_ITEMS: usize = 600;
+
+const KEYWORDS: &[&str] = &[
+ "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in", "local", "nil",
+ "not", "or", "repeat", "return", "then", "true", "until", "while",
+];
+
+const SNIPPETS: &[(&str, &str, &str)] = &[
+ ("CreateThread", "CreateThread(function()\n\t$0\nend)", "Start a new thread"),
+ ("thread loop", "CreateThread(function()\n\twhile true do\n\t\t$0\n\t\tWait(${1:0})\n\tend\nend)", "Thread with a loop that yields every iteration"),
+ ("RegisterNetEvent", "RegisterNetEvent('${1:resource}:${2:event}', function(${3})\n\t$0\nend)", "Register a network event with a handler"),
+ ("AddEventHandler", "AddEventHandler('${1:eventName}', function(${2})\n\t$0\nend)", "Handle a local event"),
+ ("RegisterCommand", "RegisterCommand('${1:name}', function(source, args, raw)\n\t$0\nend, ${2:false})", "Register a console/chat command"),
+ ("lib.callback.register", "lib.callback.register('${1:resource}:${2:name}', function(source${3})\n\t$0\nend)", "Register an ox_lib server callback"),
+ ("lib.callback.await", "lib.callback.await('${1:resource}:${2:name}', ${3:false}$0)", "Await an ox_lib callback"),
+ ("for pairs", "for ${1:k}, ${2:v} in pairs(${3:t}) do\n\t$0\nend", "Iterate over a table"),
+ ("for ipairs", "for ${1:i}, ${2:v} in ipairs(${3:t}) do\n\t$0\nend", "Iterate over an array"),
+ ("for i", "for ${1:i} = ${2:1}, ${3:#t} do\n\t$0\nend", "Numeric for loop"),
+ ("function", "function ${1:name}(${2})\n\t$0\nend", "Function declaration"),
+ ("local function", "local function ${1:name}(${2})\n\t$0\nend", "Local function declaration"),
+ ("if", "if ${1:condition} then\n\t$0\nend", "If statement"),
+ ("while", "while ${1:condition} do\n\t$0\nend", "While loop"),
+];
+
+const DOC_TAGS: &[(&str, &str)] = &[
+ ("param", "param ${1:name} ${2:type}"),
+ ("return", "return ${1:type}"),
+ ("type", "type ${1:type}"),
+ ("class", "class ${1:Name}"),
+ ("field", "field ${1:name} ${2:type}"),
+ ("alias", "alias ${1:Name} ${2:type}"),
+ ("enum", "enum ${1:Name}"),
+ ("generic", "generic ${1:T}"),
+ ("overload", "overload fun(${1}): ${2:any}"),
+ ("deprecated", "deprecated"),
+ ("async", "async"),
+ ("nodiscard", "nodiscard"),
+ ("meta", "meta"),
+ ("diagnostic", "diagnostic disable-next-line: ${1:undefined-global}"),
+ ("see", "see ${1:symbol}"),
+];
+
+const PRIMITIVE_TYPES: &[&str] = &[
+ "any", "nil", "boolean", "number", "integer", "string", "table", "function", "thread", "userdata", "unknown",
+ "fun()", "table",
+];
+
+const EVENT_NAME_CALLS: &[&str] = &[
+ "TriggerEvent",
+ "TriggerServerEvent",
+ "TriggerClientEvent",
+ "TriggerLatentServerEvent",
+ "TriggerLatentClientEvent",
+ "AddEventHandler",
+ "RegisterNetEvent",
+ "RegisterServerEvent",
+];
+const CALLBACK_NAME_CALLS: &[&str] = &["lib.callback", "lib.callback.await", "lib.callback.register"];
+const REQUIRE_CALLS: &[&str] = &["require", "lib.require", "lib.load"];
+const RESOURCE_NAME_CALLS: &[&str] = &["GetResourceState", "StartResource", "StopResource", "GetResourcePath", "GetResourceMetadata", "LoadResourceFile"];
+
+fn kind_of(kind: SymbolKind, ty: &Type) -> CompletionItemKind {
+ match kind {
+ SymbolKind::Function | SymbolKind::Export => CompletionItemKind::FUNCTION,
+ SymbolKind::Method => CompletionItemKind::METHOD,
+ SymbolKind::Class => CompletionItemKind::CLASS,
+ SymbolKind::Alias => CompletionItemKind::INTERFACE,
+ SymbolKind::Table => CompletionItemKind::MODULE,
+ _ if ty.as_fun().is_some() => CompletionItemKind::FUNCTION,
+ SymbolKind::Field => CompletionItemKind::FIELD,
+ SymbolKind::Variable => CompletionItemKind::VARIABLE,
+ }
+}
+
+fn detail_of(name: &str, ty: &Type) -> Option {
+ match ty {
+ Type::Unknown => None,
+ Type::Fun(fun) => Some(fun.signature(name)),
+ Type::GlobalTable(path) if path.starts_with('%') => Some("table".into()),
+ other => Some(other.to_string()),
+ }
+}
+
+fn item(label: &str, kind: CompletionItemKind, sort_group: u8) -> CompletionItem {
+ CompletionItem { label: label.to_string(), kind: Some(kind), sort_text: Some(format!("{sort_group}{label}")), ..CompletionItem::default() }
+}
+
+fn member_item(member: &MemberInfo) -> CompletionItem {
+ let mut out = item(&member.name, kind_of(member.kind, &member.ty), 0);
+ out.detail = detail_of(&member.name, &member.ty);
+ out.documentation = member.doc.as_ref().map(|d| Documentation::MarkupContent(markdown(d.to_string())));
+ if member.deprecated {
+ out.tags = Some(vec![CompletionItemTag::DEPRECATED]);
+ }
+ if !is_identifier(&member.name) {
+ out.filter_text = Some(member.name.to_string());
+ }
+ out
+}
+
+fn is_identifier(text: &str) -> bool {
+ let mut chars = text.chars();
+ chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
+}
+
+fn identifier_prefix(before: &str) -> &str {
+ let start = before.rfind(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).map_or(0, |i| i + 1);
+ &before[start..]
+}
+
+pub fn completion(ws: &Workspace, doc: &Document, position: Position) -> Option {
+ let offset = doc.offset(position);
+ let line_start = doc.lines.line_start(position.line) as usize;
+ let before = doc.text.get(line_start..offset as usize)?;
+
+ if let Some(comment) = doc.chunk.comments.iter().find(|c| c.span.start < offset && offset <= c.span.end) {
+ let is_doc = comment.kind == CommentKind::Line && comment.span.text(&doc.text).starts_with("---");
+ return is_doc.then(|| respond(doc_comment_items(ws, before), false));
+ }
+
+ let in_string = doc
+ .chunk
+ .tokens
+ .iter()
+ .position(|t| matches!(t.kind, TokenKind::String | TokenKind::LongString) && t.span.start < offset && offset < t.span.end.max(t.span.start + 1));
+ if let Some(token_index) = in_string {
+ return Some(respond(string_items(ws, doc, offset, token_index), false));
+ }
+
+ let prefix = identifier_prefix(before);
+ let head = before[..before.len() - prefix.len()].trim_end();
+ if prefix.chars().next().is_some_and(|c| c.is_ascii_digit()) {
+ return None;
+ }
+
+ if (head.ends_with('.') && !head.ends_with("..")) || (head.ends_with(':') && !head.ends_with("::")) {
+ let via_colon = head.ends_with(':');
+ let items = with_infer(ws, doc, |infer| member_items(infer, doc, offset, head, via_colon));
+ return Some(respond(items, false));
+ }
+
+ if doc.is_manifest() {
+ return Some(respond(manifest_items(before, prefix), false));
+ }
+
+ if head.ends_with('{') || head.ends_with(',') || head.is_empty() {
+ let fields = with_infer(ws, doc, |infer| expected_field_items(infer, doc, offset));
+ if !fields.is_empty() {
+ return Some(respond(fields, false));
+ }
+ }
+ if prefix.is_empty() {
+ return None;
+ }
+ let (items, incomplete) = with_infer(ws, doc, |infer| scope_items(ws, infer, doc, offset, prefix));
+ Some(respond(items, incomplete))
+}
+
+fn respond(mut items: Vec, incomplete: bool) -> CompletionResponse {
+ let truncated = items.len() > MAX_ITEMS;
+ items.truncate(MAX_ITEMS);
+ CompletionResponse::List(CompletionList { is_incomplete: incomplete || truncated, items })
+}
+
+fn doc_comment_items(ws: &Workspace, before: &str) -> Vec {
+ let Some(at) = before.rfind("---") else { return Vec::new() };
+ let content = before[at + 3..].trim_start();
+ if let Some(tag_prefix) = content.strip_prefix('@').filter(|rest| !rest.contains(char::is_whitespace)) {
+ return DOC_TAGS
+ .iter()
+ .filter(|(tag, _)| tag.starts_with(tag_prefix))
+ .map(|(tag, snippet)| {
+ let mut out = item(tag, CompletionItemKind::KEYWORD, 0);
+ out.insert_text = Some(snippet.to_string());
+ out.insert_text_format = Some(InsertTextFormat::SNIPPET);
+ out
+ })
+ .collect();
+ }
+ let takes_type = ["@type", "@return", "@param", "@field", "@alias", "@class", "@overload", "@generic", "|"]
+ .iter()
+ .any(|tag| content.starts_with(tag));
+ if !takes_type {
+ return Vec::new();
+ }
+ let mut items: Vec = PRIMITIVE_TYPES.iter().map(|t| item(t, CompletionItemKind::KEYWORD, 1)).collect();
+ let mut seen = FxHashSet::default();
+ for name in ws.index.class_names().filter(|n| seen.insert((*n).clone())) {
+ items.push(item(name, CompletionItemKind::CLASS, 0));
+ }
+ items
+}
+
+fn string_items(ws: &Workspace, doc: &Document, offset: u32, token_index: usize) -> Vec {
+ let tokens = &doc.chunk.tokens;
+ let indexes_exports = token_index >= 2
+ && tokens[token_index - 1].kind == TokenKind::LBracket
+ && tokens[token_index - 2].span.text(&doc.text) == "exports";
+ if indexes_exports {
+ return resource_items(ws);
+ }
+ if doc.is_manifest() {
+ return manifest_path_items(ws, doc);
+ }
+
+ let located = locate(&doc.chunk, offset);
+ let Some((_, Some((call, arg_index)))) = located.string else { return Vec::new() };
+ let path = match &call.kind {
+ ExprKind::Call { callee, .. } => callee.dotted_path(),
+ _ => None,
+ };
+ let Some(path) = path else { return Vec::new() };
+ let path = path.as_str();
+
+ if arg_index == 0 && (EVENT_NAME_CALLS.contains(&path) || CALLBACK_NAME_CALLS.contains(&path)) {
+ let wants_callbacks = CALLBACK_NAME_CALLS.contains(&path);
+ let mut seen = FxHashSet::default();
+ return ws
+ .index
+ .events()
+ .filter(|(_, e)| (e.kind == EventKind::Callback) == wants_callbacks || e.kind == EventKind::Trigger)
+ .filter(|(_, e)| seen.insert(e.name.clone()))
+ .map(|(file, event)| {
+ let mut out = item(&event.name, CompletionItemKind::EVENT, 0);
+ let origin = ws.index.file(file).and_then(|f| f.resource).and_then(|r| ws.index.resource(r));
+ out.detail = match (&event.handler, origin) {
+ (Some(handler), Some(resource)) => Some(format!("{} · {}", resource.name, handler.signature(""))),
+ (None, Some(resource)) => Some(resource.name.to_string()),
+ (Some(handler), None) => Some(handler.signature("")),
+ (None, None) => None,
+ };
+ out
+ })
+ .collect();
+ }
+ if arg_index == 0 && REQUIRE_CALLS.contains(&path) {
+ return module_items(ws, doc);
+ }
+ if arg_index == 0 && RESOURCE_NAME_CALLS.contains(&path) {
+ return resource_items(ws);
+ }
+ Vec::new()
+}
+
+fn resource_items(ws: &Workspace) -> Vec {
+ ws.index.resources.iter().map(|r| item(&r.name, CompletionItemKind::MODULE, 0)).collect()
+}
+
+fn module_items(ws: &Workspace, doc: &Document) -> Vec {
+ let Some(resource) = ws.index.resource_of(doc.file) else { return Vec::new() };
+ resource
+ .files
+ .iter()
+ .filter_map(|id| ws.index.file(*id))
+ .filter(|f| f.path != doc.path)
+ .map(|f| {
+ let relative = relative_slash_path(&resource.root, &f.path);
+ let module = relative.trim_end_matches(".lua").replace('/', ".");
+ let mut out = item(&module, CompletionItemKind::FILE, 0);
+ out.detail = Some(relative);
+ out
+ })
+ .collect()
+}
+
+fn manifest_path_items(ws: &Workspace, doc: &Document) -> Vec {
+ let Some(root) = doc.path.parent() else { return Vec::new() };
+ let mut items: Vec = qbx_lua_analysis::lint::all_files(root)
+ .into_iter()
+ .filter(|f| !f.ends_with("fxmanifest.lua") && !f.starts_with('.'))
+ .take(400)
+ .map(|f| item(&f, CompletionItemKind::FILE, 1))
+ .collect();
+ for import in qbx_fivem_data::KNOWN_IMPORTS {
+ items.push(item(import.path, CompletionItemKind::REFERENCE, 0));
+ }
+ let _ = ws;
+ items
+}
+
+fn manifest_items(before: &str, prefix: &str) -> Vec {
+ if before.trim_start().len() != prefix.len() {
+ return Vec::new();
+ }
+ KNOWN_DIRECTIVES
+ .iter()
+ .map(|directive| {
+ let mut out = item(directive, CompletionItemKind::PROPERTY, 0);
+ let snippet = match *directive {
+ "fx_version" => "fx_version '${1|cerulean,bodacious,adamant|}'".to_string(),
+ "game" => "game '${1|gta5,rdr3|}'".to_string(),
+ "lua54" | "use_experimental_fxv2_oal" => format!("{directive} 'yes'"),
+ d if d.ends_with('s') && !matches!(d, "this_is_a_map") => format!("{d} {{\n\t'$0',\n}}"),
+ d => format!("{d} '$0'"),
+ };
+ out.insert_text = Some(snippet);
+ out.insert_text_format = Some(InsertTextFormat::SNIPPET);
+ out
+ })
+ .collect()
+}
+
+fn member_items(infer: &Infer, doc: &Document, offset: u32, head: &str, via_colon: bool) -> Vec {
+ let located = locate(&doc.chunk, offset);
+ let base_type = match &located.member {
+ Some(access) => infer.expr(access.base()),
+ None => type_of_path(infer, &head[..head.len() - 1], offset),
+ };
+ let members = infer.members(&base_type);
+ let has_methods = members.iter().any(|m| m.ty.as_fun().is_some());
+ members
+ .iter()
+ .filter(|m| !via_colon || !has_methods || m.ty.as_fun().is_some())
+ .filter(|m| is_identifier(&m.name))
+ .map(|m| {
+ let mut out = member_item(m);
+ let is_method = m.ty.as_fun().is_some_and(|f| f.is_method);
+ if via_colon != is_method && m.ty.as_fun().is_some() {
+ out.sort_text = Some(format!("1{}", m.name));
+ }
+ out
+ })
+ .collect()
+}
+
+/// Fallback for member completion when the parser could not attach the trailing `.` to an expression.
+fn type_of_path(infer: &Infer, text: &str, offset: u32) -> Type {
+ let start = text
+ .rfind(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':')))
+ .map_or(0, |i| i + 1);
+ let mut segments = text[start..].split(['.', ':']).filter(|s| !s.is_empty());
+ let Some(root) = segments.next() else { return Type::Unknown };
+ let mut ty = match infer.ctx.resolution.lookup_local_at(root, offset) {
+ Some(id) => infer.local_type(id),
+ None => infer.global_type(root),
+ };
+ for segment in segments {
+ ty = infer.member(&ty, segment).map(|m| m.ty).unwrap_or_default();
+ }
+ ty
+}
+
+/// Field names of the table type a call expects, when the cursor is inside a table argument.
+fn expected_field_items(infer: &Infer, doc: &Document, offset: u32) -> Vec {
+ let located = locate(&doc.chunk, offset);
+ let Some((call, arg_index, table)) = located.table_in_call else { return Vec::new() };
+ let ExprKind::Table(existing) = &table.kind else { return Vec::new() };
+ let fun = match &call.kind {
+ ExprKind::Call { callee, .. } => infer.callee_fun(callee, None),
+ ExprKind::MethodCall { base, method, .. } => infer.callee_fun(base, Some(method)),
+ _ => None,
+ };
+ let Some((fun, _)) = fun else { return Vec::new() };
+ let (skip_params, skip_args) = fun.call_offsets(matches!(call.kind, ExprKind::MethodCall { .. }));
+ let Some(param) = (arg_index + skip_params).checked_sub(skip_args).and_then(|i| fun.params.get(i)) else {
+ return Vec::new();
+ };
+ let present: FxHashSet<&str> = existing
+ .iter()
+ .filter_map(|f| match f {
+ qbx_lua_syntax::ast::TableField::Named { name, .. } => Some(name.text.as_str()),
+ _ => None,
+ })
+ .collect();
+ infer
+ .members(¶m.ty.without_nil())
+ .iter()
+ .filter(|m| !present.contains(m.name.as_str()) && is_identifier(&m.name))
+ .map(|m| {
+ let mut out = member_item(m);
+ out.kind = Some(CompletionItemKind::PROPERTY);
+ out.insert_text = Some(format!("{} = ", m.name));
+ out
+ })
+ .collect()
+}
+
+fn scope_items(ws: &Workspace, infer: &Infer, doc: &Document, offset: u32, prefix: &str) -> (Vec, bool) {
+ let matches = |name: &str| name.len() >= prefix.len() && name[..prefix.len()].eq_ignore_ascii_case(prefix);
+ let mut items = Vec::new();
+ let mut seen: FxHashSet = FxHashSet::default();
+
+ let mut locals: Vec<_> = doc.resolution.locals_visible_at(offset).filter(|(_, l)| matches(&l.name)).collect();
+ locals.sort_by_key(|(_, l)| std::cmp::Reverse(l.visible_from));
+ for (id, local) in locals {
+ if local.name.is_empty() || !seen.insert(local.name.to_string()) {
+ continue;
+ }
+ let ty = infer.local_type(id);
+ let kind = match local.kind {
+ _ if ty.as_fun().is_some() => CompletionItemKind::FUNCTION,
+ LocalKind::Param => CompletionItemKind::VARIABLE,
+ _ => CompletionItemKind::VARIABLE,
+ };
+ let mut out = item(&local.name, kind, 0);
+ out.detail = detail_of(&local.name, &ty);
+ items.push(out);
+ }
+
+ for (file, symbol) in ws.index.visible_globals(doc.file) {
+ if !matches(&symbol.name) || !seen.insert(symbol.name.to_string()) {
+ continue;
+ }
+ let is_stub = ws.index.file(file).is_some_and(|f| f.origin == FileOrigin::Stub);
+ let mut out = item(&symbol.name, kind_of(symbol.kind, &symbol.ty), if is_stub { 2 } else { 1 });
+ out.detail = detail_of(&symbol.name, &symbol.ty);
+ out.documentation = symbol.doc.as_ref().map(|d| Documentation::MarkupContent(markdown(d.to_string())));
+ if symbol.deprecated {
+ out.tags = Some(vec![CompletionItemTag::DEPRECATED]);
+ }
+ items.push(out);
+ }
+
+ for keyword in KEYWORDS.iter().filter(|k| matches(k)) {
+ items.push(item(keyword, CompletionItemKind::KEYWORD, 3));
+ }
+ for (label, body, description) in SNIPPETS.iter().filter(|(label, ..)| matches(label)) {
+ let mut out = item(label, CompletionItemKind::SNIPPET, 4);
+ out.insert_text = Some(body.to_string());
+ out.insert_text_format = Some(InsertTextFormat::SNIPPET);
+ out.detail = Some(description.to_string());
+ out.filter_text = Some(label.to_string());
+ items.push(out);
+ }
+
+ let mut incomplete = false;
+ if prefix.len() >= 3 {
+ let side = ws.index.file(doc.file).and_then(|f| f.side).unwrap_or(Side::Shared);
+ let mut count = 0;
+ for native in natives().filter(|n| matches(n.name) && n.side.is_available_on(side)) {
+ if native.name.starts_with("N_0x") || !seen.insert(native.name.to_string()) {
+ continue;
+ }
+ if count == MAX_NATIVES {
+ incomplete = true;
+ break;
+ }
+ count += 1;
+ let mut out = item(native.name, CompletionItemKind::FUNCTION, 5);
+ out.detail = Some(native.signature());
+ out.data = Some(json!({ "native": native.name }));
+ if native.alias_of.is_some() {
+ out.tags = Some(vec![CompletionItemTag::DEPRECATED]);
+ }
+ items.push(out);
+ }
+ } else {
+ incomplete = true;
+ }
+ (items, incomplete)
+}
+
+pub fn resolve(mut item: CompletionItem) -> CompletionItem {
+ let name = item.data.as_ref().and_then(|d| d.get("native")).and_then(|n| n.as_str()).map(str::to_string);
+ if let Some(native) = name.as_deref().and_then(native) {
+ let mut text = lua_block(&native.signature());
+ text.push_str(&format!("\n\n*{} native* · `{}`", native.side.label(), native.namespace));
+ if let Some(docs) = native_docs(native.name) {
+ text.push_str("\n\n");
+ text.push_str(&docs);
+ }
+ item.documentation = Some(Documentation::MarkupContent(markdown(text)));
+ }
+ item
+}
diff --git a/src/features/definition.rs b/src/features/definition.rs
new file mode 100644
index 0000000..8b8e1e8
--- /dev/null
+++ b/src/features/definition.rs
@@ -0,0 +1,61 @@
+use lsp_types::{GotoDefinitionResponse, Location, Position, Range};
+use qbx_lua_syntax::ast::ExprKind;
+
+use super::hover::{target_at, Target};
+use super::with_infer;
+use crate::document::Document;
+use crate::index::{EventKind, FileId, FileOrigin};
+use crate::locate::locate;
+use crate::workspace::Workspace;
+
+const REQUIRE_CALLS: &[&str] = &["require", "lib.require", "lib.load"];
+
+fn location(ws: &Workspace, file: FileId, range: Range) -> Option {
+ let entry = ws.index.file(file).filter(|f| f.origin != FileOrigin::Stub)?;
+ Some(Location::new(entry.uri.clone(), range))
+}
+
+fn string_definition(ws: &Workspace, doc: &Document, offset: u32) -> Vec {
+ let located = locate(&doc.chunk, offset);
+ let Some((string, call)) = located.string else { return Vec::new() };
+ let ExprKind::String(value) = &string.kind else { return Vec::new() };
+
+ let callee = call.and_then(|(call, _)| match &call.kind {
+ ExprKind::Call { callee, .. } => callee.dotted_path(),
+ _ => None,
+ });
+ if callee.as_deref().is_some_and(|path| REQUIRE_CALLS.contains(&path)) {
+ return ws
+ .index
+ .resolve_require(value, doc.file)
+ .and_then(|file| location(ws, file, Range::default()))
+ .into_iter()
+ .collect();
+ }
+ ws.index
+ .events()
+ .filter(|(_, e)| e.name == *value && e.kind != EventKind::Trigger)
+ .filter_map(|(file, event)| location(ws, file, event.range))
+ .collect()
+}
+
+pub fn definition(ws: &Workspace, doc: &Document, position: Position) -> Option {
+ let offset = doc.offset(position);
+ let locations = with_infer(ws, doc, |infer| match target_at(infer, doc, offset) {
+ Some(Target::Local(id, _)) => {
+ let local = doc.resolution.local(id);
+ vec![Location::new(doc.uri.clone(), doc.range(local.decl))]
+ }
+ Some(Target::Global(name, _)) => ws
+ .index
+ .globals_named(&name, doc.file)
+ .into_iter()
+ .filter_map(|(file, symbol)| location(ws, file, symbol.range))
+ .collect(),
+ Some(Target::Member { info, .. }) => {
+ info.location.and_then(|(file, range)| location(ws, file, range)).into_iter().collect()
+ }
+ None => string_definition(ws, doc, offset),
+ });
+ (!locations.is_empty()).then_some(GotoDefinitionResponse::Array(locations))
+}
diff --git a/src/features/diagnostics.rs b/src/features/diagnostics.rs
new file mode 100644
index 0000000..0888f6c
--- /dev/null
+++ b/src/features/diagnostics.rs
@@ -0,0 +1,88 @@
+use lsp_types::{Diagnostic, DiagnosticSeverity, DiagnosticTag, NumberOrString};
+use qbx_lua_analysis::lint::all_files;
+use qbx_lua_analysis::summary::summarize;
+use qbx_lua_analysis::{check_file, check_manifest, FileInput, Level, ManifestInput, ResourceInput, Severity, Tag};
+use serde::{Deserialize, Serialize};
+
+use crate::document::Document;
+use crate::workspace::Workspace;
+
+pub const SOURCE: &str = "qbx-lint";
+
+/// Carried in `Diagnostic.data` so code actions can offer the fix without re-running the linter.
+#[derive(Serialize, Deserialize)]
+pub struct FixData {
+ pub title: String,
+ pub edits: Vec<(lsp_types::Range, String)>,
+}
+
+pub fn diagnostics(ws: &Workspace, doc: &Document, rule_overrides: &[(String, Level)]) -> Vec {
+ let mut config = ws.lint_config.for_file(&doc.path);
+ for (code, level) in rule_overrides {
+ config.set(code, *level);
+ }
+ let entry = ws.index.file(doc.file);
+ let resource_id = entry.and_then(|f| f.resource);
+ let resource = resource_id.and_then(|id| ws.index.resource(id));
+
+ let found = if doc.is_manifest() {
+ let Some(resource) = resource.or_else(|| ws.index.resources.iter().find(|r| r.manifest_path == doc.path)) else {
+ return Vec::new();
+ };
+ let manifest = qbx_lua_analysis::manifest::Manifest::from_chunk(&doc.chunk);
+ check_manifest(&ManifestInput {
+ source: &doc.text,
+ chunk: &doc.chunk,
+ manifest: &manifest,
+ config: &config,
+ resource_files: &all_files(&resource.root),
+ has_lua_scripts: !resource.files.is_empty(),
+ })
+ } else {
+ let summary = summarize(&doc.chunk, &doc.resolution);
+ let env = resource_id.map(|id| ws.resource_env(id));
+ let resource_input = match (resource, &env) {
+ (Some(resource), Some(env)) => Some(ResourceInput { name: &resource.name, env, manifest: &resource.manifest }),
+ _ => None,
+ };
+ check_file(&FileInput {
+ source: &doc.text,
+ chunk: &doc.chunk,
+ resolution: &doc.resolution,
+ summary: &summary,
+ config: &config,
+ side: entry.and_then(|f| f.side),
+ resource: resource_input,
+ })
+ };
+
+ found
+ .into_iter()
+ .map(|d| {
+ let fix = d.fix.as_ref().map(|fix| FixData {
+ title: fix.title.clone(),
+ edits: fix.edits.iter().map(|e| (doc.range(e.span), e.new_text.clone())).collect(),
+ });
+ Diagnostic {
+ range: doc.range(d.span),
+ severity: Some(match d.severity {
+ Severity::Error => DiagnosticSeverity::ERROR,
+ Severity::Warning => DiagnosticSeverity::WARNING,
+ Severity::Info => DiagnosticSeverity::INFORMATION,
+ Severity::Hint => DiagnosticSeverity::HINT,
+ }),
+ code: Some(NumberOrString::String(d.code.to_string())),
+ source: Some(SOURCE.to_string()),
+ message: d.message,
+ tags: d.tag.map(|tag| {
+ vec![match tag {
+ Tag::Unnecessary => DiagnosticTag::UNNECESSARY,
+ Tag::Deprecated => DiagnosticTag::DEPRECATED,
+ }]
+ }),
+ data: fix.and_then(|f| serde_json::to_value(f).ok()),
+ ..Diagnostic::default()
+ }
+ })
+ .collect()
+}
diff --git a/src/features/folding.rs b/src/features/folding.rs
new file mode 100644
index 0000000..616713b
--- /dev/null
+++ b/src/features/folding.rs
@@ -0,0 +1,91 @@
+use lsp_types::{FoldingRange, FoldingRangeKind};
+use qbx_lua_syntax::ast::*;
+use qbx_lua_syntax::visit::{self, Visitor};
+use qbx_lua_syntax::Span;
+
+use crate::document::Document;
+
+struct Folds<'a> {
+ doc: &'a Document,
+ out: Vec,
+}
+
+impl Folds<'_> {
+ fn push(&mut self, span: Span, kind: Option) {
+ let start = self.doc.lines.line_of(span.start);
+ let end = self.doc.lines.line_of(span.end.saturating_sub(1).max(span.start));
+ if end > start {
+ let end_line = if kind.is_none() { end - 1 } else { end };
+ if end_line > start || kind.is_some() {
+ self.out.push(FoldingRange { start_line: start, end_line: end_line.max(start), kind, ..FoldingRange::default() });
+ }
+ }
+ }
+}
+
+impl<'ast> Visitor<'ast> for Folds<'_> {
+ fn visit_stmt(&mut self, stmt: &'ast Stmt) {
+ match &stmt.kind {
+ StmtKind::If { branches, else_block } => {
+ for (i, branch) in branches.iter().enumerate() {
+ let end = branches
+ .get(i + 1)
+ .map(|b| b.keyword_span.start)
+ .or(else_block.as_ref().map(|b| b.span.start))
+ .unwrap_or(stmt.span.end);
+ self.push(Span::new(branch.keyword_span.start, end), None);
+ }
+ if let Some(block) = else_block {
+ self.push(Span::new(block.span.start, stmt.span.end), None);
+ }
+ }
+ StmtKind::Function { .. }
+ | StmtKind::LocalFunction { .. }
+ | StmtKind::Do(_)
+ | StmtKind::While { .. }
+ | StmtKind::Repeat { .. }
+ | StmtKind::NumericFor { .. }
+ | StmtKind::GenericFor { .. }
+ | StmtKind::Defer(_) => self.push(stmt.span, None),
+ _ => {}
+ }
+ visit::walk_stmt(self, stmt);
+ }
+
+ fn visit_expr(&mut self, expr: &'ast Expr) {
+ match &expr.kind {
+ ExprKind::Function(func) => self.push(func.span, None),
+ ExprKind::Table(_) => self.push(expr.span, None),
+ ExprKind::Call { args_span, .. } | ExprKind::MethodCall { args_span, .. } => self.push(*args_span, None),
+ _ => {}
+ }
+ visit::walk_expr(self, expr);
+ }
+}
+
+pub fn folding_ranges(doc: &Document) -> Vec {
+ let mut folds = Folds { doc, out: Vec::new() };
+ folds.visit_block(&doc.chunk.block);
+
+ let mut run: Option<(u32, u32)> = None;
+ for comment in &doc.chunk.comments {
+ let first = doc.lines.line_of(comment.span.start);
+ let last = doc.lines.line_of(comment.span.end.saturating_sub(1).max(comment.span.start));
+ run = match run {
+ Some((start, end)) if first <= end + 1 => Some((start, last.max(end))),
+ Some((start, end)) => {
+ if end > start {
+ folds.out.push(FoldingRange { start_line: start, end_line: end, kind: Some(FoldingRangeKind::Comment), ..FoldingRange::default() });
+ }
+ Some((first, last))
+ }
+ None => Some((first, last)),
+ };
+ }
+ if let Some((start, end)) = run.filter(|(s, e)| e > s) {
+ folds.out.push(FoldingRange { start_line: start, end_line: end, kind: Some(FoldingRangeKind::Comment), ..FoldingRange::default() });
+ }
+ folds.out.sort_by_key(|f| (f.start_line, f.end_line));
+ folds.out.dedup_by_key(|f| f.start_line);
+ folds.out
+}
diff --git a/src/features/hover.rs b/src/features/hover.rs
new file mode 100644
index 0000000..5bd67eb
--- /dev/null
+++ b/src/features/hover.rs
@@ -0,0 +1,195 @@
+use lsp_types::{Hover, HoverContents, Position};
+use qbx_fivem_data::{native, native_docs};
+use qbx_lua_analysis::scope::{LocalId, LocalKind, Resolved};
+use qbx_lua_syntax::ast::ExprKind;
+use qbx_lua_syntax::{SmolStr, Span};
+
+use super::{lua_block, markdown, with_infer};
+use crate::document::Document;
+use crate::index::{FileOrigin, SymbolKind};
+use crate::indexer::render_doc;
+use crate::infer::{Decl, Infer, MemberInfo};
+use crate::locate::locate;
+use crate::types::Type;
+use crate::workspace::Workspace;
+
+pub enum Target {
+ Local(LocalId, Span),
+ Global(SmolStr, Span),
+ Member { info: MemberInfo, owner: Type, span: Span },
+}
+
+impl Target {
+ pub fn span(&self) -> Span {
+ match self {
+ Target::Local(_, span) | Target::Global(_, span) | Target::Member { span, .. } => *span,
+ }
+ }
+}
+
+pub fn target_at(infer: &Infer, doc: &Document, offset: u32) -> Option {
+ if let Some((resolved, span)) = doc.resolution.resolved_at_offset(offset) {
+ return Some(match resolved {
+ Resolved::Local(id) => Target::Local(id, span),
+ Resolved::Global(index) => Target::Global(doc.resolution.globals[index as usize].name.clone(), span),
+ });
+ }
+ let located = locate(&doc.chunk, offset);
+ if let Some(access) = located.member {
+ let owner = infer.expr(access.base());
+ let name = access.name();
+ let info = infer.member(&owner, &name.text)?;
+ return Some(Target::Member { info, owner, span: name.span });
+ }
+ if let Some((func_name, segment)) = located.func_name.filter(|(_, segment)| *segment > 0) {
+ let segments: Vec<_> = func_name.path.iter().chain(&func_name.method).collect();
+ let mut owner = infer.func_name_owner_type(&qbx_lua_syntax::ast::FuncName {
+ base: func_name.base.clone(),
+ path: Vec::new(),
+ method: None,
+ span: func_name.base.span,
+ });
+ for name in &segments[..segment - 1] {
+ owner = infer.member(&owner, &name.text)?.ty;
+ }
+ let name = segments[segment - 1];
+ let info = infer.member(&owner, &name.text)?;
+ return Some(Target::Member { info, owner, span: name.span });
+ }
+ None
+}
+
+fn describe_value(prefix: &str, name: &str, ty: &Type) -> String {
+ match ty.as_fun() {
+ Some(fun) if matches!(ty, Type::Fun(_)) => format!("{prefix}{}", fun.signature(name)),
+ _ => format!("{prefix}{name}: {ty}"),
+ }
+}
+
+fn local_hover(infer: &Infer, id: LocalId) -> String {
+ let local = infer.ctx.resolution.local(id);
+ let ty = infer.local_type(id);
+ let prefix = match local.kind {
+ LocalKind::Param => "(parameter) ",
+ LocalKind::ImplicitSelf => "(self) ",
+ LocalKind::LoopVar => "(loop variable) ",
+ LocalKind::Local | LocalKind::LocalFunction => "local ",
+ };
+ let mut out = lua_block(&describe_value(prefix, &local.name, &ty));
+ let doc = match infer.ctx.decl(local.decl.start) {
+ Some(Decl::Local { stmt, .. } | Decl::LocalFunction { stmt, .. }) => render_doc(&infer.ctx.doc_at(stmt.span.start)),
+ Some(Decl::Param { doc_anchor: Some(anchor), .. }) => {
+ infer.ctx.doc_at(*anchor).param_description(&local.name).map(Into::into)
+ }
+ _ => None,
+ };
+ if let Some(doc) = doc {
+ out.push_str("\n\n");
+ out.push_str(&doc);
+ }
+ out
+}
+
+fn native_hover(name: &str) -> Option {
+ let native = native(name)?;
+ let mut out = lua_block(&native.signature());
+ let canonical = native.alias_of.map(|target| format!(" · alias of `{target}`")).unwrap_or_default();
+ out.push_str(&format!(
+ "\n\n*{} native* · `{}` · `{}`{canonical}",
+ native.side.label(),
+ native.namespace,
+ native.hash
+ ));
+ if let Some(docs) = native_docs(name) {
+ out.push_str("\n\n");
+ out.push_str(&docs);
+ }
+ Some(out)
+}
+
+fn global_hover(ws: &Workspace, infer: &Infer, name: &str) -> Option {
+ let symbols = ws.index.globals_named(name, infer.ctx.file);
+ let Some((file, symbol)) = symbols.iter().find(|(_, s)| !s.ty.is_unknown()).or(symbols.first()) else {
+ if let Some(hover) = native_hover(name) {
+ return Some(hover);
+ }
+ let ty = infer.global_type(name);
+ return (!ty.is_unknown()).then(|| lua_block(&describe_value("", name, &ty)));
+ };
+ let ty = if symbol.ty.is_unknown() { infer.global_type(name) } else { symbol.ty.clone() };
+ let mut out = lua_block(&describe_value("", name, &ty));
+ if let Some(doc) = &symbol.doc {
+ out.push_str("\n\n");
+ out.push_str(doc);
+ }
+ if let Some(entry) = ws.index.file(*file).filter(|f| f.origin != FileOrigin::Stub && *file != infer.ctx.file) {
+ let resource = entry.resource.and_then(|r| ws.index.resource(r));
+ let location = match resource {
+ Some(resource) => format!(
+ "{}/{}",
+ resource.name,
+ qbx_lua_analysis::project::relative_slash_path(&resource.root, &entry.path)
+ ),
+ None => entry.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
+ };
+ out.push_str(&format!("\n\n*defined in* `{location}`"));
+ }
+ Some(out)
+}
+
+pub fn member_hover(info: &MemberInfo, owner: &Type) -> String {
+ let owner_label = match owner {
+ Type::GlobalTable(path) if path.starts_with('%') => String::new(),
+ other => other.without_nil().to_string(),
+ };
+ let is_method = info.ty.as_fun().is_some_and(|f| f.is_method);
+ let qualified = match (owner_label.is_empty(), is_method) {
+ (true, _) => info.name.to_string(),
+ (false, true) => format!("{owner_label}:{}", info.name),
+ (false, false) => format!("{owner_label}.{}", info.name),
+ };
+ let prefix = if matches!(info.kind, SymbolKind::Field) && info.ty.as_fun().is_none() { "(field) " } else { "" };
+ let mut out = lua_block(&describe_value(prefix, &qualified, &info.ty));
+ if info.deprecated {
+ out.push_str("\n\n**Deprecated**");
+ }
+ if let Some(doc) = &info.doc {
+ out.push_str("\n\n");
+ out.push_str(doc);
+ }
+ out
+}
+
+fn string_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<(String, Span)> {
+ let located = locate(&doc.chunk, offset);
+ let (string, _) = located.string?;
+ let ExprKind::String(value) = &string.kind else { return None };
+ let registrations: Vec<_> =
+ ws.index.events().filter(|(_, e)| e.name == *value && e.kind != crate::index::EventKind::Trigger).collect();
+ if registrations.is_empty() {
+ return None;
+ }
+ let mut out = format!("event `{value}`");
+ for (file, event) in registrations.iter().take(5) {
+ let Some(entry) = ws.index.file(*file) else { continue };
+ let name = entry.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ let side = entry.side.map_or("", |s| s.label());
+ let handler = event.handler.as_ref().map(|h| format!(" `{}`", h.signature(""))).unwrap_or_default();
+ out.push_str(&format!("\n- {side} `{name}:{}`{handler}", event.range.start.line + 1));
+ }
+ Some((out, string.span))
+}
+
+pub fn hover(ws: &Workspace, doc: &Document, position: Position) -> Option {
+ let offset = doc.offset(position);
+ let (text, span) = with_infer(ws, doc, |infer| {
+ let Some(target) = target_at(infer, doc, offset) else { return string_hover(ws, doc, offset) };
+ let text = match &target {
+ Target::Local(id, _) => Some(local_hover(infer, *id)),
+ Target::Global(name, _) => global_hover(ws, infer, name),
+ Target::Member { info, owner, .. } => Some(member_hover(info, owner)),
+ };
+ text.map(|t| (t, target.span()))
+ })?;
+ Some(Hover { contents: HoverContents::Markup(markdown(text)), range: Some(doc.range(span)) })
+}
diff --git a/src/features/inlay.rs b/src/features/inlay.rs
new file mode 100644
index 0000000..5b91029
--- /dev/null
+++ b/src/features/inlay.rs
@@ -0,0 +1,78 @@
+use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range};
+use qbx_lua_syntax::ast::*;
+use qbx_lua_syntax::visit::{self, Visitor};
+use qbx_lua_syntax::Span;
+
+use super::with_infer;
+use crate::document::Document;
+use crate::infer::Infer;
+use crate::workspace::Workspace;
+
+const MAX_HINTS: usize = 400;
+
+struct Hints<'a, 'b> {
+ doc: &'a Document,
+ infer: &'a Infer<'b>,
+ range: Span,
+ out: Vec,
+}
+
+fn is_literal(expr: &Expr) -> bool {
+ match &expr.kind {
+ ExprKind::Nil | ExprKind::True | ExprKind::False | ExprKind::Number(_) | ExprKind::String(_) => true,
+ ExprKind::Unary { op: UnOp::Neg, expr } => matches!(expr.kind, ExprKind::Number(_)),
+ ExprKind::Table(fields) => fields.is_empty(),
+ _ => false,
+ }
+}
+
+impl Hints<'_, '_> {
+ fn call(&mut self, base: &Expr, method: Option<&Name>, args: &[Expr]) {
+ if self.out.len() >= MAX_HINTS || !args.iter().any(is_literal) {
+ return;
+ }
+ let Some((fun, _)) = self.infer.callee_fun(base, method) else { return };
+ let (skip_params, skip_args) = fun.call_offsets(method.is_some());
+ for (arg, param) in args.iter().skip(skip_args).zip(fun.params.iter().skip(skip_params)) {
+ if !is_literal(arg) || param.name == "..." || param.name.is_empty() || !self.range.contains(arg.span.start) {
+ continue;
+ }
+ self.out.push(InlayHint {
+ position: self.doc.position(arg.span.start),
+ label: InlayHintLabel::String(format!("{}:", param.name)),
+ kind: Some(InlayHintKind::PARAMETER),
+ text_edits: None,
+ tooltip: None,
+ padding_left: None,
+ padding_right: Some(true),
+ data: None,
+ });
+ }
+ }
+}
+
+impl<'ast> Visitor<'ast> for Hints<'_, '_> {
+ fn visit_stmt(&mut self, stmt: &'ast Stmt) {
+ if stmt.span.end >= self.range.start && stmt.span.start <= self.range.end {
+ visit::walk_stmt(self, stmt);
+ }
+ }
+
+ fn visit_expr(&mut self, expr: &'ast Expr) {
+ match &expr.kind {
+ ExprKind::Call { callee, args, style: CallStyle::Paren, .. } => self.call(callee, None, args),
+ ExprKind::MethodCall { base, method, args, style: CallStyle::Paren, .. } => self.call(base, Some(method), args),
+ _ => {}
+ }
+ visit::walk_expr(self, expr);
+ }
+}
+
+pub fn inlay_hints(ws: &Workspace, doc: &Document, range: Range) -> Vec {
+ let span = Span::new(doc.offset(range.start), doc.offset(range.end));
+ with_infer(ws, doc, |infer| {
+ let mut hints = Hints { doc, infer, range: span, out: Vec::new() };
+ hints.visit_block(&doc.chunk.block);
+ hints.out
+ })
+}
diff --git a/src/features/mod.rs b/src/features/mod.rs
new file mode 100644
index 0000000..6b6d941
--- /dev/null
+++ b/src/features/mod.rs
@@ -0,0 +1,29 @@
+pub mod code_action;
+pub mod completion;
+pub mod definition;
+pub mod diagnostics;
+pub mod folding;
+pub mod hover;
+pub mod inlay;
+pub mod references;
+pub mod semantic_tokens;
+pub mod signature;
+pub mod symbols;
+
+use crate::document::Document;
+use crate::infer::{FileContext, Infer};
+use crate::workspace::Workspace;
+
+pub fn with_infer(ws: &Workspace, doc: &Document, f: impl FnOnce(&Infer) -> R) -> R {
+ let ctx = FileContext::new(doc.file, &doc.text, &doc.chunk, &doc.resolution);
+ let infer = Infer::new(&ctx, &ws.index);
+ f(&infer)
+}
+
+pub fn markdown(value: String) -> lsp_types::MarkupContent {
+ lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value }
+}
+
+pub fn lua_block(code: &str) -> String {
+ format!("```lua\n{code}\n```")
+}
diff --git a/src/features/references.rs b/src/features/references.rs
new file mode 100644
index 0000000..8c181e5
--- /dev/null
+++ b/src/features/references.rs
@@ -0,0 +1,136 @@
+use std::collections::HashMap;
+
+use lsp_types::{DocumentHighlight, DocumentHighlightKind, Location, Position, PrepareRenameResponse, TextEdit, Url, WorkspaceEdit};
+use qbx_lua_analysis::project::read_source;
+use qbx_lua_analysis::scope::{resolve, GlobalRefKind, Resolved};
+use qbx_lua_syntax::{parse, LineIndex, Span};
+
+use crate::document::Document;
+use crate::index::FileOrigin;
+use crate::indexer::span_to_range;
+use crate::server::Documents;
+use crate::workspace::Workspace;
+
+struct Occurrence {
+ span: Span,
+ write: bool,
+}
+
+fn local_occurrences(doc: &Document, offset: u32) -> Option> {
+ let (Resolved::Local(id), _) = doc.resolution.resolved_at_offset(offset)? else { return None };
+ let local = doc.resolution.local(id);
+ let mut out = Vec::new();
+ if !local.decl.is_empty() {
+ out.push(Occurrence { span: local.decl, write: true });
+ }
+ out.extend(local.refs.iter().map(|r| Occurrence { span: r.span, write: r.write }));
+ Some(out)
+}
+
+fn global_name_at(doc: &Document, offset: u32) -> Option<&str> {
+ match doc.resolution.resolved_at_offset(offset)? {
+ (Resolved::Global(index), _) => Some(doc.resolution.globals[index as usize].name.as_str()),
+ _ => None,
+ }
+}
+
+/// Every occurrence of a global across the files that can see it. Closed files are parsed on demand
+/// instead of keeping their reference lists in memory.
+fn global_occurrences(ws: &Workspace, docs: &Documents, doc: &Document, name: &str) -> Vec<(Url, lsp_types::Range, bool)> {
+ let mut out = Vec::new();
+ for (id, entry) in ws.index.files() {
+ if entry.origin == FileOrigin::Stub || !ws.index.is_related(doc.file, id) {
+ continue;
+ }
+ let mentions = |text: &str| text.contains(name);
+ if let Some(open) = docs.get(&entry.uri) {
+ for global in open.resolution.globals.iter().filter(|g| g.name == name) {
+ out.push((entry.uri.clone(), open.range(global.span), global.kind != GlobalRefKind::Read));
+ }
+ continue;
+ }
+ let Ok(source) = read_source(&entry.path) else { continue };
+ if !mentions(&source) {
+ continue;
+ }
+ let resolution = resolve(&parse(&source));
+ let lines = LineIndex::new(&source);
+ for global in resolution.globals.iter().filter(|g| g.name == name) {
+ out.push((entry.uri.clone(), span_to_range(&source, &lines, global.span), global.kind != GlobalRefKind::Read));
+ }
+ }
+ out
+}
+
+pub fn references(ws: &Workspace, docs: &Documents, doc: &Document, position: Position, include_declaration: bool) -> Vec {
+ let offset = doc.offset(position);
+ if let Some(occurrences) = local_occurrences(doc, offset) {
+ let decl = doc.resolution.resolved_at_offset(offset).and_then(|(r, _)| match r {
+ Resolved::Local(id) => Some(doc.resolution.local(id).decl),
+ Resolved::Global(_) => None,
+ });
+ return occurrences
+ .into_iter()
+ .filter(|o| include_declaration || Some(o.span) != decl)
+ .map(|o| Location::new(doc.uri.clone(), doc.range(o.span)))
+ .collect();
+ }
+ let Some(name) = global_name_at(doc, offset) else { return Vec::new() };
+ global_occurrences(ws, docs, doc, name)
+ .into_iter()
+ .filter(|(_, _, is_definition)| include_declaration || !is_definition)
+ .map(|(uri, range, _)| Location::new(uri, range))
+ .collect()
+}
+
+pub fn highlights(doc: &Document, position: Position) -> Vec {
+ let offset = doc.offset(position);
+ let kind = |write: bool| Some(if write { DocumentHighlightKind::WRITE } else { DocumentHighlightKind::READ });
+ if let Some(occurrences) = local_occurrences(doc, offset) {
+ return occurrences.into_iter().map(|o| DocumentHighlight { range: doc.range(o.span), kind: kind(o.write) }).collect();
+ }
+ let Some(name) = global_name_at(doc, offset) else { return Vec::new() };
+ doc.resolution
+ .globals
+ .iter()
+ .filter(|g| g.name == name)
+ .map(|g| DocumentHighlight { range: doc.range(g.span), kind: kind(g.kind != GlobalRefKind::Read) })
+ .collect()
+}
+
+pub fn prepare_rename(doc: &Document, position: Position) -> Option {
+ let offset = doc.offset(position);
+ let (resolved, span) = doc.resolution.resolved_at_offset(offset)?;
+ if span.is_empty() {
+ return None;
+ }
+ if let Resolved::Global(index) = resolved {
+ let name = &doc.resolution.globals[index as usize].name;
+ let is_runtime = qbx_lua_analysis::env::builtins().get(name).is_some() || qbx_fivem_data::native(name).is_some();
+ if is_runtime {
+ return None;
+ }
+ }
+ Some(PrepareRenameResponse::Range(doc.range(span)))
+}
+
+pub fn rename(ws: &Workspace, docs: &Documents, doc: &Document, position: Position, new_name: &str) -> Option {
+ let valid = new_name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
+ && new_name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
+ && qbx_lua_syntax::lexer::keyword(new_name).is_none();
+ if !valid {
+ return None;
+ }
+ let offset = doc.offset(position);
+ let mut changes: HashMap> = HashMap::new();
+ if let Some(occurrences) = local_occurrences(doc, offset) {
+ let edits = occurrences.into_iter().map(|o| TextEdit::new(doc.range(o.span), new_name.to_string())).collect();
+ changes.insert(doc.uri.clone(), edits);
+ } else {
+ let name = global_name_at(doc, offset)?;
+ for (uri, range, _) in global_occurrences(ws, docs, doc, name) {
+ changes.entry(uri).or_default().push(TextEdit::new(range, new_name.to_string()));
+ }
+ }
+ Some(WorkspaceEdit { changes: Some(changes), ..WorkspaceEdit::default() })
+}
diff --git a/src/features/semantic_tokens.rs b/src/features/semantic_tokens.rs
new file mode 100644
index 0000000..61c91fe
--- /dev/null
+++ b/src/features/semantic_tokens.rs
@@ -0,0 +1,194 @@
+use lsp_types::{SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokens, SemanticTokensLegend};
+use qbx_fivem_data::native;
+use qbx_lua_analysis::env::builtins;
+use qbx_lua_analysis::scope::{LocalKind, Resolved};
+use qbx_lua_syntax::ast::*;
+use qbx_lua_syntax::visit::{self, Visitor};
+use qbx_lua_syntax::Span;
+
+use crate::document::Document;
+use crate::workspace::Workspace;
+
+const TYPE_VARIABLE: u32 = 0;
+const TYPE_PARAMETER: u32 = 1;
+const TYPE_FUNCTION: u32 = 2;
+const TYPE_METHOD: u32 = 3;
+const TYPE_PROPERTY: u32 = 4;
+const TYPE_NAMESPACE: u32 = 5;
+
+const MOD_DECLARATION: u32 = 1 << 0;
+const MOD_READONLY: u32 = 1 << 1;
+const MOD_STATIC: u32 = 1 << 2;
+const MOD_DEFAULT_LIBRARY: u32 = 1 << 3;
+const MOD_MODIFICATION: u32 = 1 << 4;
+
+pub fn legend() -> SemanticTokensLegend {
+ SemanticTokensLegend {
+ token_types: vec![
+ SemanticTokenType::VARIABLE,
+ SemanticTokenType::PARAMETER,
+ SemanticTokenType::FUNCTION,
+ SemanticTokenType::METHOD,
+ SemanticTokenType::PROPERTY,
+ SemanticTokenType::NAMESPACE,
+ ],
+ token_modifiers: vec![
+ SemanticTokenModifier::DECLARATION,
+ SemanticTokenModifier::READONLY,
+ SemanticTokenModifier::STATIC,
+ SemanticTokenModifier::DEFAULT_LIBRARY,
+ SemanticTokenModifier::MODIFICATION,
+ ],
+ }
+}
+
+struct Collector<'a> {
+ doc: &'a Document,
+ ws: &'a Workspace,
+ raw: Vec<(Span, u32, u32)>,
+}
+
+impl Collector<'_> {
+ fn name(&mut self, name: &Name, called: bool) {
+ if name.is_missing() {
+ return;
+ }
+ let Some(resolved) = self.doc.resolution.resolve_at(name.span.start) else { return };
+ let (ty, modifiers) = match resolved {
+ Resolved::Local(id) => {
+ let local = self.doc.resolution.local(id);
+ let mut modifiers = if local.decl == name.span { MOD_DECLARATION } else { 0 };
+ if local.attrib.is_some() || !local.refs.iter().any(|r| r.write) {
+ modifiers |= MOD_READONLY;
+ }
+ let ty = match local.kind {
+ LocalKind::Param | LocalKind::ImplicitSelf => TYPE_PARAMETER,
+ LocalKind::LocalFunction => TYPE_FUNCTION,
+ _ if called => TYPE_FUNCTION,
+ _ => TYPE_VARIABLE,
+ };
+ (ty, modifiers)
+ }
+ Resolved::Global(index) => {
+ let global = &self.doc.resolution.globals[index as usize];
+ let mut modifiers = MOD_STATIC;
+ if global.is_definition() {
+ modifiers |= MOD_MODIFICATION;
+ }
+ let user_defined = !self.ws.index.globals_named(&name.text, self.doc.file).is_empty()
+ && builtins().get(&name.text).is_none();
+ let is_native = !user_defined && native(&name.text).is_some();
+ let is_builtin = builtins().get(&name.text);
+ if is_native || is_builtin.is_some() {
+ modifiers |= MOD_DEFAULT_LIBRARY;
+ }
+ let is_library_table = is_builtin.is_some_and(|b| !b.fields.is_empty());
+ let ty = if is_library_table {
+ TYPE_NAMESPACE
+ } else if called || is_native {
+ TYPE_FUNCTION
+ } else {
+ TYPE_VARIABLE
+ };
+ (ty, modifiers)
+ }
+ };
+ self.raw.push((name.span, ty, modifiers));
+ }
+
+ fn callee(&mut self, callee: &Expr) {
+ match &callee.kind {
+ ExprKind::Name(name) => self.name(name, true),
+ ExprKind::Field { name, .. } if !name.is_missing() => self.raw.push((name.span, TYPE_FUNCTION, 0)),
+ _ => {}
+ }
+ }
+}
+
+impl<'ast> Visitor<'ast> for Collector<'_> {
+ fn visit_func_body(&mut self, func: &'ast FuncBody) {
+ for param in &func.params {
+ self.name(param, false);
+ }
+ visit::walk_func_body(self, func);
+ }
+
+ fn visit_stmt(&mut self, stmt: &'ast Stmt) {
+ match &stmt.kind {
+ StmtKind::Local { names, .. } => names.iter().for_each(|n| self.name(&n.name, false)),
+ StmtKind::LocalFunction { name, .. } => self.name(name, true),
+ StmtKind::Function { name, .. } => {
+ let is_plain = name.path.is_empty() && name.method.is_none();
+ self.name(&name.base, is_plain);
+ let last = name.method.as_ref().or(name.path.last());
+ for segment in &name.path {
+ let is_last = last.is_some_and(|l| std::ptr::eq(l, segment));
+ self.raw.push((segment.span, if is_last { TYPE_FUNCTION } else { TYPE_PROPERTY }, MOD_DECLARATION));
+ }
+ if let Some(method) = &name.method {
+ self.raw.push((method.span, TYPE_METHOD, MOD_DECLARATION));
+ }
+ }
+ StmtKind::NumericFor { var, .. } => self.name(var, false),
+ StmtKind::GenericFor { names, .. } => names.iter().for_each(|n| self.name(n, false)),
+ _ => {}
+ }
+ visit::walk_stmt(self, stmt);
+ }
+
+ fn visit_expr(&mut self, expr: &'ast Expr) {
+ match &expr.kind {
+ ExprKind::Name(name) => self.name(name, false),
+ ExprKind::Call { callee, args, .. } => {
+ self.callee(callee);
+ match &callee.kind {
+ ExprKind::Name(_) => {}
+ ExprKind::Field { base, .. } => self.visit_expr(base),
+ _ => self.visit_expr(callee),
+ }
+ args.iter().for_each(|a| self.visit_expr(a));
+ return;
+ }
+ ExprKind::MethodCall { method, .. } if !method.is_missing() => self.raw.push((method.span, TYPE_METHOD, 0)),
+ ExprKind::Field { name, .. } if !name.is_missing() => self.raw.push((name.span, TYPE_PROPERTY, 0)),
+ ExprKind::Table(fields) => {
+ for field in fields {
+ if let TableField::Named { name, .. } | TableField::SetMember(name) = field {
+ self.raw.push((name.span, TYPE_PROPERTY, MOD_DECLARATION));
+ }
+ }
+ }
+ _ => {}
+ }
+ visit::walk_expr(self, expr);
+ }
+}
+
+pub fn semantic_tokens(ws: &Workspace, doc: &Document) -> SemanticTokens {
+ let mut collector = Collector { doc, ws, raw: Vec::new() };
+ collector.visit_block(&doc.chunk.block);
+ collector.raw.sort_by_key(|(span, ..)| span.start);
+ collector.raw.dedup_by_key(|(span, ..)| span.start);
+
+ let mut data = Vec::with_capacity(collector.raw.len());
+ let (mut prev_line, mut prev_col) = (0u32, 0u32);
+ for (span, token_type, modifiers) in collector.raw {
+ let start = doc.position(span.start);
+ let end = doc.position(span.end);
+ if end.line != start.line || end.character <= start.character {
+ continue;
+ }
+ let delta_line = start.line - prev_line;
+ let delta_start = if delta_line == 0 { start.character - prev_col } else { start.character };
+ data.push(SemanticToken {
+ delta_line,
+ delta_start,
+ length: end.character - start.character,
+ token_type,
+ token_modifiers_bitset: modifiers,
+ });
+ prev_line = start.line;
+ prev_col = start.character;
+ }
+ SemanticTokens { result_id: None, data }
+}
diff --git a/src/features/signature.rs b/src/features/signature.rs
new file mode 100644
index 0000000..8e8feef
--- /dev/null
+++ b/src/features/signature.rs
@@ -0,0 +1,63 @@
+use lsp_types::{Documentation, ParameterInformation, ParameterLabel, Position, SignatureHelp, SignatureInformation};
+use qbx_fivem_data::native_docs;
+use qbx_lua_syntax::ast::ExprKind;
+
+use super::{markdown, with_infer};
+use crate::document::Document;
+use crate::locate::locate;
+use crate::workspace::Workspace;
+
+pub fn signature_help(ws: &Workspace, doc: &Document, position: Position) -> Option {
+ let offset = doc.offset(position);
+ let located = locate(&doc.chunk, offset);
+ let site = located.call?;
+ with_infer(ws, doc, |infer| {
+ let (fun, member) = infer.callee_fun(site.base, site.method)?;
+ let (skip_params, skip_args) = fun.call_offsets(site.method.is_some());
+ let params: Vec<_> = fun.params.iter().skip(skip_params).collect();
+
+ let name = match (site.method, &site.base.kind) {
+ (Some(method), _) => method.text.to_string(),
+ (None, _) => site.base.dotted_path().unwrap_or_default(),
+ };
+ let labels: Vec = params.iter().map(|p| p.to_string()).collect();
+ let mut label = format!("{name}({})", labels.join(", "));
+ if !fun.returns.is_empty() {
+ let returns: Vec = fun.returns.iter().map(|r| r.to_string()).collect();
+ label.push_str(&format!(": {}", returns.join(", ")));
+ }
+
+ let mut documentation = member.and_then(|m| m.doc).map(|d| d.to_string());
+ if documentation.is_none() {
+ if let ExprKind::Name(global) = &site.base.kind {
+ documentation = ws
+ .index
+ .globals_named(&global.text, doc.file)
+ .into_iter()
+ .find_map(|(_, s)| s.doc.as_ref().map(|d| d.to_string()))
+ .or_else(|| native_docs(&global.text));
+ }
+ }
+
+ let mut active = site.active_argument(&doc.text, offset).saturating_sub(skip_args);
+ let is_variadic = params.last().is_some_and(|p| p.name == "...");
+ if active >= params.len() && is_variadic {
+ active = params.len() - 1;
+ }
+ Some(SignatureHelp {
+ signatures: vec![SignatureInformation {
+ label,
+ documentation: documentation.map(|d| Documentation::MarkupContent(markdown(d))),
+ parameters: Some(
+ labels
+ .into_iter()
+ .map(|l| ParameterInformation { label: ParameterLabel::Simple(l), documentation: None })
+ .collect(),
+ ),
+ active_parameter: Some(active as u32),
+ }],
+ active_signature: Some(0),
+ active_parameter: Some(active as u32),
+ })
+ })
+}
diff --git a/src/features/symbols.rs b/src/features/symbols.rs
new file mode 100644
index 0000000..1dfe65c
--- /dev/null
+++ b/src/features/symbols.rs
@@ -0,0 +1,179 @@
+use lsp_types::{DocumentSymbol, Location, SymbolInformation, SymbolKind as LspKind};
+use qbx_lua_syntax::ast::*;
+use qbx_lua_syntax::Span;
+
+use crate::document::Document;
+use crate::index::{FileOrigin, SymbolKind};
+use crate::workspace::Workspace;
+
+const MAX_WORKSPACE_SYMBOLS: usize = 300;
+
+#[allow(deprecated)]
+fn symbol(doc: &Document, name: String, detail: Option, kind: LspKind, full: Span, selection: Span, children: Vec) -> DocumentSymbol {
+ let selection = if full.contains_span(selection) { selection } else { full };
+ DocumentSymbol {
+ name: if name.is_empty() { "".into() } else { name },
+ detail,
+ kind,
+ tags: None,
+ deprecated: None,
+ range: doc.range(full),
+ selection_range: doc.range(selection),
+ children: (!children.is_empty()).then_some(children),
+ }
+}
+
+fn params_detail(func: &FuncBody) -> String {
+ let mut params: Vec<&str> = func.params.iter().map(|p| p.text.as_str()).collect();
+ if func.vararg.is_some() {
+ params.push("...");
+ }
+ format!("({})", params.join(", "))
+}
+
+fn block_symbols(doc: &Document, block: &Block, out: &mut Vec) {
+ for stmt in &block.stmts {
+ match &stmt.kind {
+ StmtKind::Function { name, func } => {
+ let mut label = name.base.text.to_string();
+ for segment in &name.path {
+ label.push('.');
+ label.push_str(&segment.text);
+ }
+ if let Some(method) = &name.method {
+ label.push(':');
+ label.push_str(&method.text);
+ }
+ let kind = if name.method.is_some() { LspKind::METHOD } else { LspKind::FUNCTION };
+ let mut children = Vec::new();
+ block_symbols(doc, &func.body, &mut children);
+ out.push(symbol(doc, label, Some(params_detail(func)), kind, stmt.span, name.span, children));
+ }
+ StmtKind::LocalFunction { name, func } => {
+ let mut children = Vec::new();
+ block_symbols(doc, &func.body, &mut children);
+ out.push(symbol(doc, name.text.to_string(), Some(params_detail(func)), LspKind::FUNCTION, stmt.span, name.span, children));
+ }
+ StmtKind::Local { names, exprs, .. } => {
+ for (i, name) in names.iter().enumerate() {
+ out.push(value_symbol(doc, name.name.text.to_string(), name.name.span, stmt.span, exprs.get(i)));
+ }
+ }
+ StmtKind::Assign { targets, exprs } => {
+ for (i, target) in targets.iter().enumerate() {
+ if let Some(path) = target.dotted_path() {
+ out.push(value_symbol(doc, path, target.span, stmt.span, exprs.get(i)));
+ }
+ }
+ }
+ StmtKind::Expr(expr) => call_symbols(doc, expr, stmt.span, out),
+ StmtKind::Do(body) | StmtKind::While { body, .. } | StmtKind::Repeat { body, .. } => block_symbols(doc, body, out),
+ StmtKind::NumericFor { body, .. } | StmtKind::GenericFor { body, .. } => block_symbols(doc, body, out),
+ StmtKind::If { branches, else_block } => {
+ branches.iter().for_each(|b| block_symbols(doc, &b.block, out));
+ if let Some(block) = else_block {
+ block_symbols(doc, block, out);
+ }
+ }
+ _ => {}
+ }
+ }
+}
+
+fn value_symbol(doc: &Document, name: String, selection: Span, full: Span, value: Option<&Expr>) -> DocumentSymbol {
+ let mut children = Vec::new();
+ let (kind, detail) = match value.map(|v| &v.kind) {
+ Some(ExprKind::Function(func)) => {
+ block_symbols(doc, &func.body, &mut children);
+ (LspKind::FUNCTION, Some(params_detail(func)))
+ }
+ Some(ExprKind::Table(fields)) => {
+ for field in fields.iter().take(200) {
+ if let TableField::Named { name, value } = field {
+ children.push(value_symbol(doc, name.text.to_string(), name.span, name.span.to(value.span), Some(value)));
+ }
+ }
+ (LspKind::OBJECT, None)
+ }
+ Some(ExprKind::String(_)) => (LspKind::STRING, None),
+ Some(ExprKind::Number(_)) => (LspKind::NUMBER, None),
+ Some(ExprKind::True | ExprKind::False) => (LspKind::BOOLEAN, None),
+ _ => (LspKind::VARIABLE, None),
+ };
+ symbol(doc, name, detail, kind, full, selection, children)
+}
+
+/// Event handlers, threads, commands and exports are the landmarks of a FiveM script, so they
+/// show up in the outline even though they are plain calls.
+fn call_symbols(doc: &Document, expr: &Expr, full: Span, out: &mut Vec) {
+ let ExprKind::Call { callee, args, .. } = &expr.kind else { return };
+ let Some(path) = callee.dotted_path() else { return };
+ let label = match path.as_str() {
+ "RegisterNetEvent" | "AddEventHandler" | "RegisterServerEvent" | "RegisterCommand" | "RegisterNUICallback"
+ | "exports" | "lib.callback.register" => {
+ let Some(name) = args.first().and_then(|a| a.as_string()) else { return };
+ format!("{path} '{name}'")
+ }
+ "CreateThread" | "Citizen.CreateThread" | "SetTimeout" => path.clone(),
+ _ => return,
+ };
+ let mut children = Vec::new();
+ for arg in args {
+ if let ExprKind::Function(func) = &arg.kind {
+ block_symbols(doc, &func.body, &mut children);
+ }
+ }
+ out.push(symbol(doc, label, None, LspKind::EVENT, full, callee.span, children));
+}
+
+pub fn document_symbols(doc: &Document) -> Vec {
+ let mut out = Vec::new();
+ block_symbols(doc, &doc.chunk.block, &mut out);
+ out
+}
+
+#[allow(deprecated)]
+pub fn workspace_symbols(ws: &Workspace, query: &str) -> Vec {
+ let query = query.to_ascii_lowercase();
+ let matches = |name: &str| query.is_empty() || name.to_ascii_lowercase().contains(&query);
+ let mut out = Vec::new();
+ for (_, file) in ws.index.files().filter(|(_, f)| f.origin != FileOrigin::Stub) {
+ let mut push = |name: String, kind: LspKind, range, container: Option| {
+ if out.len() < MAX_WORKSPACE_SYMBOLS {
+ out.push(SymbolInformation {
+ name,
+ kind,
+ tags: None,
+ deprecated: None,
+ location: Location::new(file.uri.clone(), range),
+ container_name: container,
+ });
+ }
+ };
+ for symbol in file.index.globals.iter().filter(|s| matches(&s.name)) {
+ let kind = if symbol.ty.as_fun().is_some() { LspKind::FUNCTION } else { LspKind::VARIABLE };
+ push(symbol.name.to_string(), kind, symbol.range, None);
+ }
+ for member in file.index.members.iter().filter(|m| matches(&m.symbol.name) && !m.owner.starts_with('%')) {
+ let kind = match member.symbol.kind {
+ SymbolKind::Method => LspKind::METHOD,
+ _ if member.symbol.ty.as_fun().is_some() => LspKind::FUNCTION,
+ _ => LspKind::FIELD,
+ };
+ push(format!("{}.{}", member.owner, member.symbol.name), kind, member.symbol.range, Some(member.owner.to_string()));
+ }
+ for class in file.index.classes.iter().filter(|c| matches(&c.name)) {
+ push(class.name.to_string(), LspKind::CLASS, class.range, None);
+ }
+ for export in file.index.exports.iter().filter(|e| matches(&e.name)) {
+ push(format!("exports:{}", export.name), LspKind::INTERFACE, export.range, None);
+ }
+ for event in file.index.events.iter().filter(|e| e.kind != crate::index::EventKind::Trigger && matches(&e.name)) {
+ push(event.name.to_string(), LspKind::EVENT, event.range, None);
+ }
+ if out.len() >= MAX_WORKSPACE_SYMBOLS {
+ break;
+ }
+ }
+ out
+}
diff --git a/src/index.rs b/src/index.rs
new file mode 100644
index 0000000..e6580fa
--- /dev/null
+++ b/src/index.rs
@@ -0,0 +1,365 @@
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+use lsp_types::{Range, Url};
+use qbx_fivem_data::Side;
+use qbx_lua_analysis::manifest::Manifest;
+use qbx_lua_analysis::summary::FileSummary;
+use rustc_hash::FxHashMap;
+use smol_str::SmolStr;
+
+use crate::types::{FunType, Type};
+
+pub type FileId = u32;
+pub type ResourceId = u32;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SymbolKind {
+ Function,
+ Method,
+ Variable,
+ Table,
+ Field,
+ Class,
+ Alias,
+ Export,
+}
+
+#[derive(Clone, Debug)]
+pub struct Symbol {
+ pub name: SmolStr,
+ pub kind: SymbolKind,
+ pub ty: Type,
+ pub doc: Option>,
+ pub deprecated: bool,
+ pub range: Range,
+}
+
+#[derive(Clone, Debug)]
+pub struct Member {
+ pub owner: SmolStr,
+ pub symbol: Symbol,
+}
+
+#[derive(Clone, Debug)]
+pub struct ClassDef {
+ pub name: SmolStr,
+ pub parents: Vec,
+ pub fields: Vec,
+ pub index: Option<(Type, Type)>,
+ pub call: Option>,
+ pub doc: Option>,
+ pub range: Range,
+}
+
+#[derive(Clone, Debug)]
+pub struct AliasDef {
+ pub name: SmolStr,
+ pub ty: Type,
+ pub doc: Option>,
+ pub range: Range,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum EventKind {
+ NetEvent,
+ Handler,
+ Callback,
+ Trigger,
+}
+
+#[derive(Clone, Debug)]
+pub struct EventDef {
+ pub name: SmolStr,
+ pub kind: EventKind,
+ pub handler: Option>,
+ pub range: Range,
+}
+
+#[derive(Clone, Debug, Default)]
+pub struct FileIndex {
+ pub globals: Vec,
+ pub members: Vec,
+ pub classes: Vec,
+ pub aliases: Vec,
+ pub exports: Vec,
+ pub events: Vec,
+ pub module_return: Option,
+ pub summary: FileSummary,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum FileOrigin {
+ Stub,
+ Workspace,
+ Library,
+}
+
+#[derive(Debug)]
+pub struct FileEntry {
+ pub path: PathBuf,
+ pub uri: Url,
+ pub origin: FileOrigin,
+ pub resource: Option,
+ pub side: Option,
+ pub index: FileIndex,
+}
+
+#[derive(Debug)]
+pub struct ResourceEntry {
+ pub name: SmolStr,
+ pub root: PathBuf,
+ pub manifest_path: PathBuf,
+ pub manifest: Manifest,
+ pub files: Vec,
+ /// Files pulled in through `@resource/file.lua` manifest entries, with the side they load on.
+ pub imports: Vec<(FileId, Side)>,
+}
+
+type Slot = (FileId, u32);
+
+#[derive(Debug, Default)]
+pub struct Index {
+ files: Vec