### Display Help for Luau LSP Source: https://github.com/johnnymorganz/luau-lsp/blob/main/README.md Run this command after installing the binary to view all available options and information for the luau-lsp tool. ```bash luau-lsp --help ``` -------------------------------- ### Neovim Setup with nvim-lspconfig Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Basic configuration for using luau-lsp with Neovim's native LSP client via the nvim-lspconfig plugin. ```APIDOC ## Neovim Setup ### Description Basic configuration for using luau-lsp with Neovim's native LSP client. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters N/A ### Request Example ```lua -- Using nvim-lspconfig local lspconfig = require('lspconfig') lspconfig.luau_lsp.setup({ cmd = { 'luau-lsp', 'lsp', '--definitions:@roblox=/path/to/globalTypes.d.luau' }, filetypes = { 'luau', 'lua' }, root_dir = lspconfig.util.root_pattern('.luaurc', 'default.project.json', '.git'), settings = { ['luau-lsp'] = { platform = { type = 'roblox' }, sourcemap = { enabled = true, autogenerate = false }, completion = { imports = { enabled = true } } } } }) ``` ### Response N/A (Configuration) ``` -------------------------------- ### Sentry Integration Setup Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CMakeLists.txt Configures Sentry native SDK integration for crash reporting. Requires FetchContent module and sets specific build options for Sentry and Crashpad. ```cmake if (LSP_BUILD_WITH_SENTRY) include(FetchContent) set(SENTRY_BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) set(SENTRY_BACKEND "crashpad" CACHE STRING "" FORCE) set(SENTRY_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(SENTRY_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(SENTRY_BUILD_RUNTIMESTATIC ${LSP_STATIC_CRT} CACHE BOOL "" FORCE) set(SENTRY_ENABLE_INSTALL OFF CACHE BOOL "" FORCE) set(CRASHPAD_ENABLE_STACKTRACE ON CACHE BOOL "" FORCE) FetchContent_Declare(sentry URL https://github.com/getsentry/sentry-native/releases/download/0.11.0/sentry-native.zip URL_HASH SHA256=2946d5d13ef2aa791fc4cee3663658da78ad8b3260f6976e1fd8f6e237c14db0 ) FetchContent_MakeAvailable(sentry) endif () ``` -------------------------------- ### Get Luau Language Server Help Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/README.md Display all available command-line options for the Luau Language Server. ```sh $ luau-lsp --help ``` -------------------------------- ### Start Luau Language Server Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Starts the language server listening on stdin/stdout for LSP protocol messages. Supports custom type definitions, documentation databases, base configurations, FFlags, and pipe communication. ```bash luau-lsp lsp ``` ```bash luau-lsp lsp --definitions:@roblox=/path/to/globalTypes.d.luau ``` ```bash luau-lsp lsp --definitions:@roblox=/path/to/globalTypes.d.luau --docs=/path/to/api-docs.json ``` ```bash luau-lsp lsp --base-luaurc=/path/to/.luaurc ``` ```bash luau-lsp lsp --flag:LuauSolverV2=true ``` ```bash luau-lsp lsp --no-flags-enabled ``` ```bash luau-lsp lsp --settings=/path/to/settings.json ``` ```bash luau-lsp lsp --pipe=/tmp/luau-lsp.sock ``` -------------------------------- ### Luau LSP Test Fixture Example Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Demonstrates the basic structure of a test case using the Fixture class for setting up documents and performing checks. ```cpp TEST_CASE_FIXTURE(Fixture, "FeatureName") { auto uri = newDocument("test.luau", "local x = 1"); // Test operations using workspace } ``` -------------------------------- ### Start Luau Language Server Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/README.md Run the Luau Language Server from the command line. The server communicates via stdin and stdout following the Language Server Protocol. ```sh $ luau-lsp lsp ``` -------------------------------- ### Plugin Transformation Example Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md An example of a Luau LSP plugin that transforms source code by replacing all occurrences of 'DEBUG' with 'false'. ```APIDOC ## POST /transformSource (Conceptual) ### Description This endpoint represents the core transformation function of a Luau LSP plugin. It receives the original source code and returns a list of text edits to be applied. ### Method POST (Conceptual) ### Endpoint /transformSource ### Parameters #### Request Body - **source** (string) - Required - The original source code of the file. - **context** (object) - Required - Contextual information for the transformation. ### Request Example ```json { "source": "---", "context": {} } ``` ### Response #### Success Response (200) - **edits** (array) - A list of text edits to apply to the source code. - **startLine** (number) - The starting line of the edit. - **startColumn** (number) - The starting column of the edit. - **endLine** (number) - The ending line of the edit. - **endColumn** (number) - The ending column of the edit. - **newText** (string) - The new text to insert. ### Response Example ```json { "edits": [ { "startLine": 1, "startColumn": 1, "endLine": 1, "endColumn": 5, "newText": "false" } ] } ``` ``` -------------------------------- ### Basic CMake Configuration for Luau LSP Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CMakeLists.txt Sets the minimum CMake version and configures macOS architectures. This is a foundational setup for the Luau LSP project. ```cmake cmake_minimum_required(VERSION 3.19) set(CMAKE_OSX_ARCHITECTURES "arm64;x86_64" CACHE STRING "") ``` -------------------------------- ### Minimal Plugin Example Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md A minimal Luau plugin that returns nil, indicating no source code transformations are needed. This serves as a basic structure for plugins. ```luau return { transformSource = function(source, context) -- Return nil or {} for no changes -- Return a list of TextEdits to transform the source return nil end } :: PluginApi ``` -------------------------------- ### Generate Sourcemap with Rojo Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/code/assets/walkthrough-sourcemap-generation.md This command generates a sourcemap file using Rojo. It watches the specified Rojo project file and outputs the sourcemap. Ensure Rojo is installed and configured. ```bash rojo sourcemap --watch default.project.json --output sourcemap.json ``` -------------------------------- ### Luau LSP CodeGen Instructions Request Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Example of a custom LSP request to obtain annotated native code generation instructions. Specify the optimizationLevel and the desired codeGenTarget. ```typescript // Request: luau-lsp/codeGen interface CodeGenParams { textDocument: TextDocumentIdentifier; optimizationLevel: number; codeGenTarget: "host" | "a64" | "a64_nofeatures" | "x64_windows" | "x64_systemv"; } // Example request { "method": "luau-lsp/codeGen", "params": { "textDocument": { "uri": "file:///project/src/main.luau" }, "optimizationLevel": 2, "codeGenTarget": "x64_windows" } } ``` -------------------------------- ### LSP Notifications for Studio Companion Plugin Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Defines the LSP notifications used by the Studio companion plugin to forward HTTP requests to the language server. Includes example notification structure. ```typescript // $/plugin/full - Send DataModel tree (params: tree object directly) // $/plugin/clear - Clear DataModel information (no params) // Example notification { "method": "$/plugin/full", "params": { "Name": "game", "ClassName": "DataModel", "Children": { /* ... */ } } } ``` -------------------------------- ### Download Roblox Type Definitions Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Download Roblox type definitions from a CDN for use with the language server. Includes commands for downloading global types and API docs, and starting the server with definitions. ```bash # Download from CDN (recommended to avoid GitHub rate limits) curl -o globalTypes.d.luau https://luau-lsp.pages.dev/type-definitions/globalTypes.PluginSecurity.d.luau curl -o api-docs.json https://luau-lsp.pages.dev/api-docs/en-us.json # Available security levels: # - globalTypes.None.d.luau # - globalTypes.LocalUserSecurity.d.luau # - globalTypes.PluginSecurity.d.luau (default) # - globalTypes.RobloxScriptSecurity.d.luau # Start server with definitions luau-lsp lsp --definitions:@roblox=./globalTypes.d.luau --docs=./api-docs.json ``` -------------------------------- ### Sourcemap Structure Example Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/code/assets/walkthrough-sourcemap-generation.md This JSON structure represents a sourcemap file. It maps DataModel hierarchy and instance names to their corresponding file paths on the file system. Use this structure if you are generating your own sourcemap. ```json { "name": "Game", "className": "DataModel", "children": [ { "name": "ReplicatedStorage", "className": "ReplicatedStorage", "children": [ { "name": "Library", "className": "ModuleScript", "filePaths": ["ReplicatedStorage/Library.luau"] }, { "name": "Logging", "className": "ModuleScript", "filePaths": ["ReplicatedStorage/Logging.luau"] } ] }, { "name": "ServerScriptService", "className": "ServerScriptService", "children": [ ... ] } ... ] } ``` -------------------------------- ### Enable New Luau Type Solver in Tests Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Use the ENABLE_NEW_SOLVER() macro at the start of a test case to enable the new Luau type solver (LuauSolverV2). This macro is required to correctly update both the FFlag and the Frontend's cached solver mode. ```cpp TEST_CASE_FIXTURE(Fixture, "feature_requiring_new_solver") { ENABLE_NEW_SOLVER(); auto uri = newDocument("test.luau", "local x = 1"); // Test code... } ``` -------------------------------- ### Studio Companion Plugin HTTP Endpoints Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Defines the HTTP endpoints and data structures used by the Studio companion plugin to communicate DataModel information. Includes example tree structure. ```typescript // GET /get-file-paths - Returns file path mappings // POST /full - Receives full DataModel tree // POST /clear - Clears DataModel information // DataModel tree structure sent to /full interface DataModelTree { tree: { Name: string; ClassName: string; Children: { [name: string]: DataModelTree['tree'] }; } } // Example tree { "tree": { "Name": "game", "ClassName": "DataModel", "Children": { "Workspace": { "Name": "Workspace", "ClassName": "Workspace", "Children": {} }, "ReplicatedStorage": { "Name": "ReplicatedStorage", "ClassName": "ReplicatedStorage", "Children": {} } } } } ``` -------------------------------- ### Luau LSP Compiler Remarks Request Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Example of a custom LSP request to retrieve compiler optimization remarks for a Luau file. The optimizationLevel parameter specifies the desired optimization level. ```typescript // Request: luau-lsp/compilerRemarks interface CompilerRemarksParams { textDocument: TextDocumentIdentifier; optimizationLevel: number; } // Example request { "method": "luau-lsp/compilerRemarks", "params": { "textDocument": { "uri": "file:///project/src/main.luau" }, "optimizationLevel": 2 } } ``` -------------------------------- ### Plugin API transformSource Function Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md Example of the `transformSource` function within a Luau plugin, demonstrating its signature and expected return types. It accepts source code and context, returning a list of `TextEdit` objects or nil. ```luau return { transformSource = function(source: string, context: PluginContext): {TextEdit}? -- Return nil or {} for no changes -- Return list of edits to transform the source end } :: PluginApi ``` -------------------------------- ### Basic Luau LSP Plugin Structure Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Defines a basic Luau LSP plugin that transforms source code. The transformSource function receives the source code and context, returning TextEdit objects to modify the code. This example replaces 'DEBUG' with 'false'. ```luau -- plugins/my_plugin.luau return { transformSource = function(source: string, context: PluginContext): {TextEdit}? local edits = {} local line = 1 local lineStart = 1 for i = 1, #source do if string.sub(source, i, i) == "\n" then line += 1 lineStart = i + 1 end -- Replace DEBUG with false if string.sub(source, i, i + 4) == "DEBUG" then local col = i - lineStart + 1 table.insert(edits, { startLine = line, startColumn = col, endLine = line, endColumn = col + 5, newText = "false", }) end end return edits end, } :: PluginApi ``` -------------------------------- ### LSP Initialization Options for Non-VSCode Clients Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Configuration passed during LSP initialization for non-VSCode clients, specifically for setting FFlags. ```json { "initializationOptions": { "fflags": { "LuauSolverV2": "false", "LuauTinyControlFlowAnalysis": "true" } } } ``` -------------------------------- ### Build Luau LSP from Source Source: https://github.com/johnnymorganz/luau-lsp/blob/main/README.md Commands to update submodules, create a build directory, configure with CMake, and build the language server executable. ```sh git submodule update --init --recursive mkdir build && cd build cmake .. -DCMAKE_BUILD_TYPE=Release cmake --build . --target Luau.LanguageServer.CLI --config Release ``` -------------------------------- ### List All Test Cases Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Prints a list of all available test cases that can be run. ```bash ./build/Luau.LanguageServer.Test --list-test-cases ``` -------------------------------- ### Read File Content using Filesystem API Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md Demonstrates reading a file's content from the workspace using the sandboxed filesystem API. It uses `pcall` to handle potential errors during file reading and includes joining the root URI with a relative path. ```luau local ok, content = pcall(function() local rootUri = lsp.workspace.getRootUri() local fileUri = rootUri:joinPath("src", "config.luau") return lsp.fs.readFile(fileUri) end) if ok then -- Use content else print("Failed:", content) end ``` -------------------------------- ### Run All Tests Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Executes the entire test suite from the repository root directory. Ensure you are in the root directory before running. ```bash ./build/Luau.LanguageServer.Test ``` -------------------------------- ### Configure CMake Build (Release) Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Sets up the build environment using CMake for a Release build type, suitable for production. ```bash cmake .. -DCMAKE_BUILD_TYPE=Release ``` -------------------------------- ### Custom LSP Command Payload for Cursor Move Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/README.md Example payload for the custom `$/command` notification, specifically for the `cursorMove` command. This is used by the Luau Language Server for end autocompletion. ```json { "command": "cursorMove", "data": { "to": "prevBlankLine" } } ``` -------------------------------- ### Build with ASan Enabled Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Configures and builds the test suite with AddressSanitizer (ASan) enabled for memory error detection. Requires Linux or macOS. ```bash cmake .. -DLSP_BUILD_ASAN:BOOL=ON cmake --build . --target Luau.LanguageServer.Test -j$NUM_CPUS ``` -------------------------------- ### Require File with Standard Platform Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/code/assets/walkthrough-select-your-platform.md Use this when the 'Standard' platform is configured. It follows Luau's require-by-string semantics for resolving modules. ```lua local library = require("../library") ``` -------------------------------- ### Filesystem API Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md Provides access to the workspace's filesystem in a sandboxed manner. Requires `luau-lsp.plugins.fileSystem.enabled` to be set to true. ```APIDOC ## Filesystem API ### `lsp.workspace.getRootUri(): Uri` Returns the workspace root as a Uri object. ### `lsp.fs.readFile(uri: Uri): string` Reads a file within the workspace. Only files within the workspace can be read; attempting to read files outside the workspace throws an "access denied" error. ```luau local ok, content = pcall(function() local rootUri = lsp.workspace.getRootUri() local fileUri = rootUri:joinPath("src", "config.luau") return lsp.fs.readFile(fileUri) end) if ok then -- Use content else print("Failed:", content) end ``` ### `lsp.fs.exists(uri: Uri): boolean` Checks whether a file exists within the workspace. Returns `true` if the file exists and is readable, `false` otherwise. Like `readFile`, only files within the workspace can be checked. ### `lsp.fs.listDirectory(uri: Uri): {Uri}` Lists the entries in a directory within the workspace. Returns an array of Uri objects for each entry (files and subdirectories). Only directories within the workspace can be listed. ```luau local rootUri = lsp.workspace.getRootUri() local srcUri = rootUri:joinPath("src") local entries = lsp.fs.listDirectory(srcUri) for _, entry in entries do print(entry.fsPath) end ``` ### `lsp.Uri.parse(uriString: string): Uri` Parses a URI string into a Uri object. ### `lsp.Uri.file(fsPath: string): Uri` Creates a `file://` Uri from a filesystem path. ### Uri Object **Properties** (read-only): `scheme`, `authority`, `path`, `query`, `fragment`, `fsPath` **Methods**: - `:joinPath(...segments: string): Uri` - Join path segments, returns new Uri - `:toString(): string` - Convert to URI string ``` -------------------------------- ### Run Tests with New Type Solver Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Executes the test suite using the experimental new type solver. ```bash ./build/Luau.LanguageServer.Test --new-solver ``` -------------------------------- ### Request Internal Source Representation via Luau LSP Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md Send a 'luau-lsp/debug/viewInternalSource' request to get the transformed source code that Luau type-checks. This is useful for debugging and verifying plugin output. ```json { "jsonrpc": "2.0", "id": 1, "method": "luau-lsp/debug/viewInternalSource", "params": { "textDocument": { "uri": "file:///path/to/your/file.luau" } } } ``` -------------------------------- ### List Directory Entries using Filesystem API Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md Shows how to list the entries (files and subdirectories) within a specified directory in the workspace. It retrieves the root URI, joins it with a subdirectory path, and then iterates through the returned URIs to print their filesystem paths. ```luau local rootUri = lsp.workspace.getRootUri() local srcUri = rootUri:joinPath("src") local entries = lsp.fs.listDirectory(srcUri) for _, entry in entries do print(entry.fsPath) end ``` -------------------------------- ### Configure CMake Build (Debug) Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Sets up the build environment using CMake for a Debug build type, which is faster for development. ```bash mkdir build && cd build cmake .. -DCMAKE_BUILD_TYPE=Debug ``` -------------------------------- ### TextEdit Type Definition Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md Defines the structure for a `TextEdit` object used in Luau LSP plugins. It specifies the start and end positions (line and column) for a text replacement and the new text to be inserted. ```luau type TextEdit = { startLine: number, -- 1-indexed, inclusive startColumn: number, -- 1-indexed, inclusive, UTF-8 byte offset endLine: number, -- 1-indexed, inclusive endColumn: number, -- 1-indexed, exclusive, UTF-8 byte offset newText: string, } ``` -------------------------------- ### Optional: Roblox Studio Plugin Integration Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/README.md Provides intellisense for non-Rojo and non-filesystem based DataModel instances via a companion plugin. This involves HTTP requests to localhost and LSP notifications. ```APIDOC ## Roblox Studio Companion Plugin Integration ### Description Enables intellisense for DataModel instances not managed by Rojo or filesystem-based workflows. Requires a companion plugin and a local HTTP listener in the language client. ### Companion Plugin Endpoints (HTTP Requests to localhost) - `GET /get-file-paths` - `POST /full` - `POST /clear` ### Language Server Notifications (from Language Client) - `$/plugin/full` - `$/plugin/clear` ### `POST /full` Request Body ```json { "tree": { "Name": "string", "ClassName": "string", "Children": { ... } } } ``` ### `$/plugin/full` LSP Notification Expects the `tree` property directly from the request body. ### Implementation Language clients need to implement an HTTP listener to receive data from the companion plugin and then send the corresponding LSP notification to the server. ``` -------------------------------- ### Luau LSP Bytecode Generation Request Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/README.md Implement this custom LSP request to get textual bytecode output for a given document and optimization level. Ensure the TextDocumentIdentifier and optimizationLevel are correctly provided. ```typescript { textDocument: TextDocumentIdentifier, optimizationLevel: number } ``` -------------------------------- ### Configure Luau LSP with Neovim Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Basic configuration for luau-lsp using nvim-lspconfig. Ensure to replace '@roblox=/path/to/globalTypes.d.luau' with the actual path to your Roblox global types definition file. ```lua -- Using nvim-lspconfig local lspconfig = require('lspconfig') lspconfig.luau_lsp.setup({ cmd = { 'luau-lsp', 'lsp', '--definitions:@roblox=/path/to/globalTypes.d.luau' }, filetypes = { 'luau', 'lua' }, root_dir = lspconfig.util.root_pattern('.luaurc', 'default.project.json', '.git'), settings = { ['luau-lsp'] = { platform = { type = 'roblox' }, sourcemap = { enabled = true, autogenerate = false }, completion = { imports = { enabled = true } } } } }) ``` -------------------------------- ### Luau LSP Debug View Internal Source Request Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Example of a custom LSP request to retrieve the transformed source code after plugin processing, useful for debugging plugins. Requires the textDocument identifier. ```typescript // Request: luau-lsp/debug/viewInternalSource interface ViewInternalSourceParams { textDocument: TextDocumentIdentifier; } // Example request { "method": "luau-lsp/debug/viewInternalSource", "params": { "textDocument": { "uri": "file:///project/src/main.luau" } } } // Response: string containing transformed source ``` -------------------------------- ### Configure Luau.LanguageServer.CLI Target Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CMakeLists.txt Sets the output name, compile options, include directories, and link libraries for the Luau.LanguageServer.CLI target. ```cmake set_target_properties(Luau.LanguageServer.CLI PROPERTIES OUTPUT_NAME luau-lsp) target_compile_options(Luau.LanguageServer.CLI PRIVATE ${LUAU_LSP_OPTIONS}) target_include_directories(Luau.LanguageServer.CLI PRIVATE src/include) target_include_directories(Luau.LanguageServer.CLI SYSTEM PRIVATE ${EXTERN_INCLUDES}) target_link_libraries(Luau.LanguageServer.CLI PRIVATE Luau.LanguageServer Luau.Analysis) ``` -------------------------------- ### Plugin System Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Information on how to create and configure plugins for luau-lsp to transform source code. ```APIDOC ## Plugin System ### Description Plugins transform source code before type checking while maintaining position mapping for LSP features. ### Basic Plugin Structure ```luau -- plugins/my_plugin.luau return { transformSource = function(source: string, context: PluginContext): {TextEdit}? local edits = {} local line = 1 local lineStart = 1 for i = 1, #source do if string.sub(source, i, i) == "\n" then line += 1 lineStart = i + 1 end -- Replace DEBUG with false if string.sub(source, i, i + 4) == "DEBUG" then local col = i - lineStart + 1 table.insert(edits, { startLine = line, startColumn = col, endLine = line, endColumn = col + 5, newText = "false", }) end end return edits end, } :: PluginApi ``` ### Plugin Configuration Enable and configure plugins via LSP client settings. ```json { "luau-lsp.plugins.enabled": true, "luau-lsp.plugins.paths": [ "./plugins/my_plugin.luau", "./plugins/macros.luau" ], "luau-lsp.plugins.timeoutMs": 5000, "luau-lsp.plugins.fileSystem.enabled": true } ``` ``` -------------------------------- ### Add Sentry and Crashpad Handler Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CMakeLists.txt Links the 'sentry' library and copies the 'crashpad_handler' executable to the output directory when LSP_BUILD_WITH_SENTRY is enabled. ```cmake if (LSP_BUILD_WITH_SENTRY) target_link_libraries(Luau.LanguageServer PRIVATE sentry) target_link_libraries(Luau.LanguageServer.CLI PRIVATE sentry) add_custom_command( TARGET Luau.LanguageServer.CLI POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "$" "$" COMMENT "Copying crashpad_handler to output directory" ) endif () ``` -------------------------------- ### Luau LSP Plugin Architecture Overview Source: https://github.com/johnnymorganz/luau-lsp/blob/main/plugin/README.md This directory structure outlines the core components of the Luau Language Server Studio plugin. It includes the main entry point, connection management, instance tracking, server endpoints, type definitions, settings management, and utility modules. ```plaintext src/ ├── init.server.luau # Main entry point and UI setup ├── LSPManager.luau # Connection lifecycle and server communication ├── InstanceTracker.luau # DataModel change detection and encoding ├── ServerEndpoints.luau # HTTP request handling ├── types.luau # Type definitions ├── Assets.luau # Toolbar icon asset IDs ├── Settings/ │ ├── init.luau # Settings management with live reload │ └── DefaultSettings.luau # Default configuration values └── Utils/ ├── Debounce.luau # Rate-limiting utility ├── Log.luau # Leveled logging system └── Signal.luau # Event/callback management ``` -------------------------------- ### Configure Luau.LanguageServer.Test Target Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CMakeLists.txt Sets compile options, include directories, and link libraries for the Luau.LanguageServer.Test target, including system includes for external libraries. ```cmake target_compile_options(Luau.LanguageServer.Test PRIVATE ${LUAU_LSP_OPTIONS}) target_include_directories(Luau.LanguageServer.Test PRIVATE tests) target_include_directories(Luau.LanguageServer.Test SYSTEM PRIVATE ${EXTERN_INCLUDES} extern/doctest) target_link_libraries(Luau.LanguageServer.Test PRIVATE Luau.Ast Luau.Analysis Luau.LanguageServer) ``` -------------------------------- ### Luau LSP Build Options Configuration Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CMakeLists.txt Configures build options such as time tracing, AddressSanitizer (ASAN), static CRT linking, Sentry integration, and warnings as errors. These options control various aspects of the build process and debugging capabilities. ```cmake option(LUAU_ENABLE_TIME_TRACE "Build with Luau TimeTrace" OFF) option(LSP_BUILD_ASAN "Build with ASAN" OFF) option(LSP_STATIC_CRT "Link with the static CRT (/MT)" OFF) option(LSP_BUILD_WITH_SENTRY "Build with Sentry (crash reporting)" OFF) option(LSP_WERROR "Warnings as errors" ON) ``` -------------------------------- ### Configure Luau.LanguageServer Target Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CMakeLists.txt Sets C++ standard, compile options, definitions, and include directories for the Luau.LanguageServer target. ```cmake target_compile_features(Luau.LanguageServer PUBLIC cxx_std_17) target_compile_options(Luau.LanguageServer PRIVATE ${LUAU_LSP_OPTIONS}) target_compile_definitions(Luau.LanguageServer PUBLIC LSP_VERSION="${LSP_VERSION}" LSP_NAME="${LSP_NAME}" $<$:LSP_BUILD_WITH_SENTRY> ) target_include_directories(Luau.LanguageServer PUBLIC src/include) target_include_directories(Luau.LanguageServer SYSTEM PUBLIC ${EXTERN_INCLUDES}) target_link_libraries(Luau.LanguageServer PRIVATE Luau.Ast Luau.Analysis Luau.Compiler Luau.VM Luau.CodeGen) ``` -------------------------------- ### Build Luau Language Server CLI (Release) Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Compiles the Luau Language Server CLI executable in Release mode. ```bash cmake --build . --target Luau.LanguageServer.CLI --config Release -j$NUM_CPUS ``` -------------------------------- ### Configure Luau LSP Plugins Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt JSON configuration for enabling and managing Luau LSP plugins. Specify paths to plugin files, enable/disable the plugin system, set timeouts, and configure file system access. ```json { "luau-lsp.plugins.enabled": true, "luau-lsp.plugins.paths": [ "./plugins/my_plugin.luau", "./plugins/macros.luau" ], "luau-lsp.plugins.timeoutMs": 5000, "luau-lsp.plugins.fileSystem.enabled": true } ``` -------------------------------- ### Read Configuration File in Plugin Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md Attempts to read a JSON configuration file from the workspace root. If the file is not found or cannot be read, it returns `nil` to indicate that default settings should be used. This snippet is intended to be part of a larger `transformSource` function. ```luau return { transformSource = function(source, context) -- Try to read a configuration file local ok, configContent = pcall(function() local rootUri = lsp.workspace.getRootUri() local configUri = rootUri:joinPath(".luau-plugin-config.json") return lsp.fs.readFile(configUri) end) if not ok then -- Config file doesn't exist or can't be read, use defaults return nil end -- Use configuration to decide how to transform -- ... return nil end } ``` -------------------------------- ### Plugin with File System Access Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Plugins can read workspace files when filesystem access is enabled. This snippet shows how to read a configuration file, parse JSON, and use it for transformations. ```luau -- plugins/config_loader.luau return { transformSource = function(source, context) -- Read configuration file local ok, configContent = pcall(function() local rootUri = lsp.workspace.getRootUri() local configUri = rootUri:joinPath(".plugin-config.json") return lsp.fs.readFile(configUri) end) if not ok then lsp.client.sendLogMessage("warning", "Config not found, using defaults") return nil end -- Parse JSON configuration local config = lsp.json.deserialize(configContent) -- Use configuration for transformations local edits = {} -- ... transformation logic using config ... return edits end } :: PluginApi ``` -------------------------------- ### Create a Plugin File Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md This Luau script transforms all occurrences of 'TODO' to 'DONE' in the source code. It identifies 'TODO' strings and generates a list of text edits to replace them. Ensure the return value is annotated with `:: PluginApi` for type checking. ```luau -- Replace all occurrences of "TODO" with "DONE" return { transformSource = function(source, context) local edits = {} local line = 1 local lineStart = 1 for i = 1, #source do if string.sub(source, i, i) == "\n" then line += 1 lineStart = i + 1 end if string.sub(source, i, i + 3) == "TODO" then local col = i - lineStart + 1 table.insert(edits, { startLine = line, startColumn = col, endLine = line, endColumn = col + 4, newText = "DONE", }) end end return edits end, } :: PluginApi ``` -------------------------------- ### Send Log Messages to Editor Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md Demonstrates sending log messages to the editor using the client API. Supports different log levels: 'info', 'warning', 'error', and 'log'. The global `print` function is equivalent to sending an 'info' level message. ```luau lsp.client.sendLogMessage("info", "Processing file...") lsp.client.sendLogMessage("warning", "Deprecated syntax detected") ``` -------------------------------- ### Plugin API Types Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Reference for plugin type definitions including TextEdit, PluginContext, and Uri. ```luau type TextEdit = { startLine: number, -- 1-indexed, inclusive startColumn: number, -- 1-indexed, inclusive, UTF-8 byte offset endLine: number, -- 1-indexed, inclusive endColumn: number, -- 1-indexed, exclusive, UTF-8 byte offset newText: string, } type PluginContext = { filePath: string, -- Absolute filesystem path moduleName: string, -- Luau module name (virtual path for Roblox) } type Uri = { scheme: string, authority: string, path: string, query: string, fragment: string, fsPath: string, joinPath: (...segments: string) -> Uri, toString: () -> string, } -- Available APIs lsp.workspace.getRootUri(): Uri lsp.fs.readFile(uri: Uri): string lsp.fs.exists(uri: Uri): boolean lsp.fs.listDirectory(uri: Uri): {Uri} lsp.Uri.parse(uriString: string): Uri lsp.Uri.file(fsPath: string): Uri lsp.client.sendLogMessage(type: string, message: string) lsp.json.deserialize(jsonString: string): any ``` -------------------------------- ### Build Luau Language Server CLI Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Compiles the Luau Language Server CLI executable. Uses the number of available CPU cores for parallel builds. ```bash NUM_CPUS=$(nproc) cmake --build . --target Luau.LanguageServer.CLI --config Debug -j$NUM_CPUS ``` -------------------------------- ### VSCode Luau LSP Settings Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Complete VSCode configuration for the Luau Language Server extension, covering platform types, sourcemap settings, definition and documentation files, diagnostics, ignore globs, completion, inlay hints, and FFlags. ```json { "luau-lsp.platform.type": "roblox", "luau-lsp.sourcemap.enabled": true, "luau-lsp.sourcemap.autogenerate": true, "luau-lsp.sourcemap.rojoProjectFile": "default.project.json", "luau-lsp.sourcemap.includeNonScripts": true, "luau-lsp.types.definitionFiles": { "@roblox": "./types/globalTypes.d.luau", "@custom": "./types/custom.d.luau" }, "luau-lsp.types.documentationFiles": ["./docs/api-docs.json"], "luau-lsp.diagnostics.workspace": false, "luau-lsp.diagnostics.strictDatamodelTypes": false, "luau-lsp.ignoreGlobs": ["**/_Index/**", "**/Packages/**"], "luau-lsp.completion.imports.enabled": true, "luau-lsp.completion.imports.suggestServices": true, "luau-lsp.completion.imports.suggestRequires": true, "luau-lsp.completion.addParentheses": true, "luau-lsp.completion.fillCallArguments": true, "luau-lsp.inlayHints.parameterNames": "literals", "luau-lsp.inlayHints.variableTypes": true, "luau-lsp.inlayHints.functionReturnTypes": true, "luau-lsp.fflags.sync": true, "luau-lsp.fflags.enableNewSolver": false, "luau-lsp.fflags.override": { "LuauSolverV2": "false" } } ``` -------------------------------- ### Plugin Configuration Settings Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md JSON configuration for Luau LSP plugins, including enabling plugins, specifying their paths, setting execution timeouts, and enabling file system access. ```json { "luau-lsp.plugins.enabled": true, "luau-lsp.plugins.paths": ["./plugins/my_plugin.luau"], "luau-lsp.plugins.timeoutMs": 5000 } ``` -------------------------------- ### Manual Rojo Sourcemap Generation Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Command to manually generate Rojo sourcemaps with watching enabled. Specify project file, output file, and include non-script files. ```bash # Manual sourcemap generation with watching rojo sourcemap --include-non-scripts --watch default.project.json --output sourcemap.json ``` -------------------------------- ### Luau LSP Initialization Options for FFlags Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/README.md Configure FFlags for the Luau Language Server using initialization options within a JSON payload. This is an alternative to command-line arguments. ```json { "initializationOptions": { "fflags": { "Foo": "True" } } } ``` -------------------------------- ### VS Code Settings for Plugins Source: https://github.com/johnnymorganz/luau-lsp/blob/main/src/Plugin/README.md Configure VS Code to enable and specify paths for Luau LSP plugins. Ensure the `luau-lsp.plugins.enabled` setting is true and provide the correct path to your plugin file in `luau-lsp.plugins.paths`. ```json { "luau-lsp.plugins.enabled": true, "luau-lsp.plugins.paths": ["./plugins/my_plugin.luau"] } ``` -------------------------------- ### Configure AddressSanitizer Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CMakeLists.txt Sets up AddressSanitizer flags for compilation and linking when LSP_BUILD_ASAN is enabled. Includes specific handling for MSVC and non-MSVC targets. ```cmake if (LSP_BUILD_ASAN) if (MSVC) set(ASAN_FLAG /fsanitize=address) else () set(ASAN_FLAG -fsanitize=address) endif () list(APPEND LUAU_LSP_OPTIONS ${ASAN_FLAG}) set(LUAU_ASAN_TARGETS Luau.Ast Luau.Analysis Luau.Compiler Luau.Config Luau.VM Luau.CodeGen Luau.Common) foreach (TARGET_NAME IN LISTS LUAU_ASAN_TARGETS) target_compile_options(${TARGET_NAME} PRIVATE ${ASAN_FLAG}) endforeach () if (NOT MSVC) foreach (TARGET_NAME IN LISTS LUAU_ASAN_TARGETS ITEMS Luau.LanguageServer Luau.LanguageServer.CLI Luau.LanguageServer.Test) target_link_options(${TARGET_NAME} PRIVATE ${ASAN_FLAG}) endforeach () endif () endif () ``` -------------------------------- ### Analyze Luau Files with Luau-lsp Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Runs static type checking and linting on Luau files, suitable for CI/CD pipelines. Supports single files, directories, platform types, sourcemaps, custom formatters, ignore patterns, and annotated output. ```bash luau-lsp analyze src/main.luau ``` ```bash luau-lsp analyze src/ ``` ```bash luau-lsp analyze --platform=roblox --sourcemap=sourcemap.json --definitions:@roblox=globalTypes.d.luau src/ ``` ```bash luau-lsp analyze --formatter=gnu src/ ``` ```bash luau-lsp analyze --ignore="**/_Index/**" --ignore="**/node_modules/**" src/ ``` ```bash luau-lsp analyze --annotate src/module.luau ``` ```bash luau-lsp analyze --settings=settings.json src/ ``` -------------------------------- ### Configure Definitions with Luau LSP Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/README.md Add built-in definitions to the Luau Language Server by specifying a name and path. This can be repeated for multiple definition files. ```sh $ luau-lsp lsp --definitions:@roblox=/path/to/globalTypes.d.luau ``` -------------------------------- ### Require File with Roblox Platform Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/code/assets/walkthrough-select-your-platform.md Use this when the 'Roblox' platform is configured. It supports instance-based requires using a sourcemap to map file-system paths to Roblox DataModel paths. ```lua local library = require(game.ReplicatedStorage.Library) ``` -------------------------------- ### Build Luau Language Server Tests Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Compiles the test suite for the Luau Language Server. Debug builds are recommended for faster iteration during testing. ```bash cmake --build . --target Luau.LanguageServer.Test --config Debug -j$NUM_CPUS ``` -------------------------------- ### Clone Luau LSP with Submodules Source: https://github.com/johnnymorganz/luau-lsp/blob/main/README.md Use this command to clone the Luau LSP repository, ensuring all necessary submodules are included. ```sh git clone https://github.com/JohnnyMorganz/luau-lsp.git --recurse-submodules ``` -------------------------------- ### Luau Syntax Configuration for Luau LSP Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Configure Luau LSP project-wide settings using a `.config.luau` file. This format allows for Luau-specific syntax and return values. ```luau -- .config.luau return { languageMode = "strict", lint = { ["*" ] = true, LocalShadow = false, }, aliases = { ["@shared"] = "./src/shared", } } ``` -------------------------------- ### JSON Configuration for Luau LSP Source: https://context7.com/johnnymorganz/luau-lsp/llms.txt Configure Luau LSP project-wide settings using a JSON file. Supports language mode, linting rules, type checking, global variables, and path aliases. ```json { "languageMode": "strict", "lint": { "*": true, "LocalShadow": false }, "lintErrors": false, "typeErrors": true, "globals": ["game", "script", "workspace"], "aliases": { "@shared": "./src/shared", "@client": "./src/client", "@server": "./src/server" } } ``` -------------------------------- ### Project Definition for Luau Language Server Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CMakeLists.txt Defines the project name and languages for the Luau Language Server build. This is a standard CMake command to initialize the project. ```cmake project(Luau.LanguageServer LANGUAGES CXX) ``` -------------------------------- ### Optional: Bytecode Generation Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/README.md The Language Server supports generating textual bytecode, source code remarks, and codegen instructions for debugging purposes via custom LSP requests. ```APIDOC ## Bytecode Generation ### Description Provides custom LSP requests for generating file-level textual bytecode, source code remarks, and codegen instructions. ### Custom LSP Requests - **`luau-lsp/bytecode`** - **Description**: Computes textual bytecode for a given file. - **Arguments**: `{ textDocument: TextDocumentIdentifier, optimizationLevel: number }` - **Returns**: `string` - Textual bytecode output. - **`luau-lsp/compilerRemarks`** - **Description**: Generates source code with inline remarks as comments. - **Arguments**: `{ textDocument: TextDocumentIdentifier, optimizationLevel: number }` - **Returns**: `string` - Source code with remarks. - **`luau-lsp/codeGen`** - **Description**: Generates annotated codegen instructions. - **Arguments**: `{ textDocument: TextDocumentIdentifier, optimizationLevel: number, codeGenTarget: string }` - **Returns**: `string` - Annotated codegen instructions. - **`codeGenTarget` values**: `"host" | "a64" | "a64_nofeatures" | "x64_windows" | "x64_systemv"` ### Usage Implement these requests via custom commands in your editor to surface this information. ``` -------------------------------- ### Optional: Require Graph Generation Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/README.md The Language Server can generate a require graph in DOT format, visualizing dependency links between modules, either for a single file or the entire workspace. ```APIDOC ## Require Graph Generation ### Description Generates a require graph in DOT format to visualize module dependencies. This can be done for a single file or the entire workspace. ### Custom LSP Request - **`luau-lsp/requireGraph`** - **Description**: Generates a require graph visualizing dependency links between modules. - **Arguments**: `{ textDocument: TextDocumentIdentifier, fromTextDocumentOnly: boolean }` - `textDocument`: The text document for which to generate the require graph. - `fromTextDocumentOnly`: If `true`, the graph includes only dependencies from the selected text document. If `false`, it includes all indexed modules from the workspace relevant to the selected document. - **Returns**: `string` - DOT file output. ### Usage Implement this request via a custom command in your editor. A `dot` visualizer may be required to render the output. ``` -------------------------------- ### Run Rojo Sourcemap Watch Command Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/README.md Use this command to automatically generate or update a sourcemap.json file when project files change. It's recommended to make the project file and include-non-scripts option configurable. ```sh $ rojo sourcemap --include-non-scripts --watch default.project.json --output sourcemap.json ``` -------------------------------- ### Luau LSP Version and Name Settings Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CMakeLists.txt Sets the version and name for the Luau Language Server. These variables are used to identify and manage the build. ```cmake set(LSP_VERSION "1.66.0") set(LSP_NAME "Luau") ``` -------------------------------- ### Run Tests with All FFlags Enabled Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Executes the test suite with all feature flags (FFlags) enabled. ```bash ./build/Luau.LanguageServer.Test --fflags=true ``` -------------------------------- ### Run Specific Test Case Source: https://github.com/johnnymorganz/luau-lsp/blob/main/CLAUDE.md Executes a single test case identified by its name. ```bash ./build/Luau.LanguageServer.Test --test-case="TestName" ``` -------------------------------- ### Luau LSP CodeGen Instructions Request Source: https://github.com/johnnymorganz/luau-lsp/blob/main/editors/README.md Implement this custom LSP request to obtain annotated codegen instructions. Specify the TextDocumentIdentifier, optimizationLevel, and the desired codeGenTarget. ```typescript { textDocument: TextDocumentIdentifier, optimizationLevel: number, codeGenTarget: string } ```