FFFF GitHub - giuinktse7/ols: Language server for Odin · GitHub
[go: up one dir, main page]

Skip to content
giuinktse7Public
forked from DanielGavin/ols

About

Language server for Odin

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

ols

Language server for Odin. This project is still in early development.

Note: This project is made to be up to date with the master branch of Odin.

Table Of Contents

Patches in this fork

This fork's master branch carries the following patches on top of upstream OLS. The linked feature branches retain the individual patch histories; related formatter patches are combined on master.

Patch Behavior
feat/better-named-arg-param-completion Completes unused procedure parameter names as named arguments, including in nested calls and partially edited argument lists. Existing named and positional arguments are accounted for when choosing suggestions.
feat/closing-brace-on-own-line Introduces the opt-in odinfmt closing_brace_on_own_line setting.
feat/declaration-theming Marks declared symbols with the semantic-token declaration modifier and expands VS Code syntax scopes so themes can distinguish declarations, declaration operators, directives, and related language constructs.
feat/enable-checks-for-test-files Checks a package in both normal and -build-mode:test modes when it contains a file tagged with #+test, then deduplicates diagnostics from the two runs.
feat/odinfmt-closing-brace-layout Refines the closing-brace layout so multiline statement blocks end with the brace on its own line while single-line blocks stay compact.
feat/odinfmt-inline-switch-cases Adds configurable inlining and optional alignment for consecutive single-statement switch cases, bounded by character_width.
feat/odinfmt-remove-empty-block-boundary-lines Extends block cleanup to both boundaries through remove_empty_lines_at_start_or_end_of_blocks, without removing blank lines between statements.
feat/preserve-do-mode Adds preserve_do_mode, which controls which kinds of single-statement do bodies remain in do form.
feat/preserve-struct-blank-lines Adds preserve_struct_blank_lines and keeps field alignment scoped to sections separated by preserved blank lines.
feat/remove-empty-lines-at-start-of-blocks Adds the original opt-in formatter behavior for removing blank lines immediately after a statement block's opening brace. This is superseded on master by the block-boundary patch above.
feat/switch-case-inlining-policy Adds inline_single_stmt_case_mode policies ranging from return-only cases to the legacy Any behavior.

Installation

cd ols

# for windows
./build.bat
# To install the odinfmt formatter
./odinfmt.bat

# for linux and macos
./build.sh
# To install the odinfmt formatter
./odinfmt.sh

In order for ols to find symbols for builtin types and procedures, the builtin folder in the repo needs to be located next to the ols binary. Alternatively you can specify the path to this folder using the OLS_BUILTIN_FOLDER environment variable.

Configuration

In order for the language server to index your files, it must know about your collections.

To do that you can either configure ols via an ols.json file (it should be located at the root of your workspace).

Or you can provide the configuration via your editor of choice.

Example of ols.json:

{
	"$schema": "https://raw.githubusercontent.com/DanielGavin/ols/master/misc/ols.schema.json",
	"collections": [
		{ "name": "custom_collection", "path": "c:/path/to/collection" }
	],
	"enable_semantic_tokens": false,
	"enable_document_symbols": true,
	"enable_hover": true,
	"enable_snippets": true,
	"profile": "default",
	"profiles": [
		{ "name": "default", "checker_path": ["src"], "defines": { "ODIN_DEBUG": "false" }},
		{ "name": "linux_profile", "os": "linux", "checker_path": ["src/main.odin"], "defines": { "ODIN_DEBUG": "false" }},
		{ "name": "mac_profile", "os": "darwin", "arch": "arm64", "defines": { "ODIN_DEBUG": "false" }},
		{ "name": "windows_profile", "os": "windows", "checker_path": ["src"], "defines": { "ODIN_DEBUG": "false" }}
	]
}

Options:

  • enable_format: Turns on formatting with odinfmt. (Enabled by default)

  • enable_hover: Enables hover feature. (Enabled by default)

  • enable_hover_layout: Show the memory layout (size, alignment, field offsets and padding) of types on hover. Computed by ols from the resolved types, for the configured profile arch. This feature is experimental and the reported layout may not always match the compiler. (Disabled by default)

  • enable_document_symbols: Turns on outline of all your global declarations in your document. (Enabled by default)

  • enable_fake_methods: Turn on fake methods completion. This is currently highly experimental and requires client snippet support.

  • enable_overload_resolution: Enable go-to-definition to resolve overloaded procedures from procedure groups based on call arguments.

  • enable_references: Turns on finding references for a symbol. (Enabled by default)

  • enable_document_highlights: Turns on highlighting of symbol references in file. (Enabled by default)

  • enable_document_links: Follow links when opening documentation. This is usually done via <ctrl+click> and will open the documentation in a browser (or similar). (Enabled by default)

  • enable_completions: Enables completion results. (Enabled by default)

  • enable_completion_matching: Attempt to match types and pointers when passing arguments to procedures. (Enabled by default)

  • enable_unused_imports_reporting: Turn on reporting of unused imported packages. (Enabled by default)

  • enable_unused_imports_on_change: Report unused imported packages after each document change. This can slow editing in large files. (Disabled by default)

  • enable_inlay_hints_params: Turn on inlay hints for (non-default) parameters.

  • enable_inlay_hints_default_params: Turn on inlay hints for default parameters.

  • enable_inlay_hints_implicit_return: Turn on inlay hints for implicit return values.

  • enable_inlay_hints_optional_result: Adds inlay hints for unhandled optional result value. (#optional_ok and #optional_allocator_error)

  • enable_semantic_tokens: Turns on syntax highlighting.

  • enable_snippets: Turns on builtin snippets

  • enable_procedure_snippet: Use snippets when completing procedures—adds parenthesis after the name. This requires client snippet support. (Enabled by default)

  • enable_checker_only_saved: Turns on only calling the checker on the package being saved. (Enabled by default)

  • enable_compiler_semantics: Enables compiler semantics for reporting type information. This is currently experimental and under active development. Needs an odin with -export-semantics.

    • enable_checker_on_change: Turns on calling the checker on the package being edited once typing pauses for checker_on_change_delay, with the unsaved text of the open documents. Needs an odin with -overlay.

    • checker_on_change_delay: How long typing must pause, in milliseconds, before enable_checker_on_change calls the checker. (Defaults to 400)

    • enable_fade_untaken_when_branches: Fades the branches of when statements that the checker did not take. Needs an odin with -export-semantics. (Enabled by default)

  • enable_checker_workspace_diagnostics: Turns on running all workspace diagnostics using odin check. This is currently experimental and may cause problems. A better option is using the checker_path feature to explicity tell ols the projects that it should check. (experimental).

  • enable_auto_import: Automatically import packages that aren't in your import on completion.

  • enable_auto_import_skip_hidden_paths: Skip hidden directories when discovering packages for auto-import. (Enabled by default)

  • enable_comp_lit_signature_help: Provide signature help for comp lits such as when instantiating structs. Will not display correctly on some editors such as vscode.

  • enable_comp_lit_signature_help_use_docs: Put signature help for comp lits in the documentation. This will allow it to be rendered nicely using markdown in editors that render the label without colour on one line.

  • enable_code_action_invert_if: Enables a code action to invert if statement 8000 s.

  • struct_fields_underscore_visibility: Controls visibility of struct fields starting with _:

    • "" (default): no hiding, all fields are visible
    • "file": hide fields when accessed from outside the declaring file
    • "package": hide fields when accessed from outside the declaring package
  • enable_parser_errors: Enable real-time diagnostics from core:odin/parser. (Enabled by default)

  • enable_diagnostics: Enable real-time diagnostics from the lsp. (Enabled by default)

  • odin_command: Specify the location to your Odin executable, rather than relying on the environment path.

  • odin_root_override: Allows you to specify a custom ODIN_ROOT that ols will use to look for odin core libraries when implementing custom runtimes.

  • checker_args: Pass custom arguments to odin check.

Packages containing #+test files are checked in both normal and test modes.

  • checker_skip_packages: Paths to packages that should not be checked by odin check when using enable_checker_workspace_diagnostics.

  • completion_exclude_attributes: Filter procedures that include the provided attributes from completions. For example @(test).

  • verbose: Logs warnings instead of just errors.

  • profile: What profile to currently use.

  • profiles: List of different profiles that describe the environment ols is running under. This allows you to define different operating systems, architectures and defines for ols to use during development, easily switching between them using the profile configuration.

Odinfmt configurations

Odinfmt reads configuration through odinfmt.json.

Pass one or more files or directories to format them, using -w to write the results in place:

odinfmt -w src/main.odin src/ui.odin

Configuration is discovered separately for each input path. Use -config:path/to/odinfmt.json to apply the same configuration to all inputs. With -stdin, at most one path may be supplied for configuration discovery.

Example:

{
	"$schema": "https://raw.githubusercontent.com/DanielGavin/ols/master/misc/odinfmt.schema.json",
	"character_width": 80,
	"tabs": true,
	"tabs_width": 4
}

Options:

  • character_width: How many characters it takes before it line breaks it.

  • spaces: How many spaces is in one indentation.

  • newline_limit: The limit of newlines between statements and declarations.

  • remove_empty_lines_at_start_or_end_of_blocks: Remove blank lines immediately after an opening brace or before a closing brace while preserving blank lines between statements. (Disabled by default)

  • tabs: Tabs or spaces.

  • tabs_width: How many characters one tab represents.

  • convert_do: Convert all do statements to brace blocks.

  • preserve_do_mode: Select which do statement bodies are preserved. Return permits only return statements; Guard permits return, break, and continue; Return_And_Branch also permits fallthrough; Simple also permits assignments, declarations, using statements, and expression statements; Any preserves every do statement. Other bodies are converted to brace blocks. Defaults to Any; convert_do overrides this setting.

  • brace_style: Style of braces. One of _1TBS, Allman, Stroustrup, K_And_R.

  • multiline_call_style: Style for calls containing a non-final multiline composite literal. Block_Arguments keeps preceding and consecutive scalar arguments packed when they fit, starts the argument after each multiline composite literal on a new line, indents composite contents relative to the call, and puts the closing parenthesis on its own line after a trailing call comma. Defaults to Default.

  • indent_cases: Indent case statements within a switch.

  • newline_style: Line endings to use. One of CRLF, LF.

  • sort_imports: A boolean that defaults to true, which can be set to false to disable sorting imports.

  • inline_single_stmt_case: When a case clause contains one statement allowed by inline_single_stmt_case_mode, inline the case and statement when they fit.

  • inline_single_stmt_case_mode: Select which single statements may be inlined. Return permits only return statements; Return_And_Branch also permits break, continue, and fallthrough; Simple also permits assignments, declarations, using statements, and expression statements; Any permits every statement and preserves the legacy behavior. Defaults to Any.

  • align_single_stmt_case: Align statements in consecutive inline single-statement cases while respecting character_width.

  • spaces_around_colons: Put a space on both sides of a single colon during variable/field declaration, such as foo : bar

  • space_single_line_blocks: Put spaces around braces of single-line blocks: {return 0} => { return 0 }

  • closing_brace_on_own_line: Put the closing brace of a multiline statement block on its own line.

  • align_struct_fields: Align the types of struct fields so they all start at the same column.

  • align_struct_values: Align the values of struct fields when assigning a struct value to a variable so they all start at the same column.

  • align_comments: Align trailing line comments on consecutive lines so they all start at the same column. The alignment resets on a blank line, a line without a trailing comment, or a change in indentation. Standalone comment lines and /* */ block comments are not aligned.

  • multiline_composite_literals: When enabled, composite literals that were written across multiple lines are kept multiline.

  • preserve_struct_blank_lines: Preserve blank lines between struct fields, up to newline_limit.

Features

Support Language server features:

  • Completion
  • Go to definition
  • Semantic tokens
  • Document symbols
  • Rename
  • References
  • Signature help
  • Hover

Clients

VS Code

Install the extension https://marketplace.visualstudio.com/items?itemName=DanielGavin.ols

Sublime

Install the package https://github.com/sublimelsp/LSP

Configuration of the LSP:

{
	"clients": {
		"odin": {
			"command": [
				"/path/to/ols"
			],
			"enabled": false, // true for globally-enabled, but not required due to 'Enable In Project' command
			"selector": "source.odin",
			"initializationOptions": {
				"collections": [
					{
						"name": "collection_a",
						"path": "/path/to/collection_a"
					}
				],
				"enable_semantic_tokens": true,
				"enable_document_symbols": true,
				"enable_hover": true,
				"enable_snippets": true,
				"enable_format": true,
			}
		}
	}
}

Vim

Install Coc.

Configuration of the LSP:

{
	"languageserver": {
		"odin": {
			"command": "ols",
			"filetypes": ["odin"],
			"rootPatterns": ["ols.json"]
		}
	}
}

Neovim

Neovim has a builtin support for LSP.

There is a plugin that makes the setup easier, called nvim-lspconfig. You can install it with your preferred package manager.

A simple configuration that uses the default ols settings would be like this:

require'lspconfig'.ols.setup {}

And here is an example of a configuration with a couple of settings applied:

require'lspconfig'.ols.setup {
	init_options = {
		checker_args = "-strict-style",
		collections = {
			{ name = "shared", path = vim.fn.expand('$HOME/odin-lib') }
		},
	},
}
  • use an explicit cmd for ols when using a custom build

Neovim can run Odinfmt on save using the conform plugin. Here is a sample configuration using the lazy.nvim package manager:

local M = {
   "stevearc/conform.nvim",
   opts = {
      notify_on_error = false,
      -- Odinfmt gets its configuration from odinfmt.json. It defaults
      -- writing to stdout but needs to be told to read from stdin.
      formatters = {
         odinfmt = {
            -- Change where to find the command if it isn't in your path.
            command = "odinfmt",
            args = { "-stdin" },
            stdin = true,
         },
      },
      -- and instruct conform to use odinfmt.
      formatters_by_ft = {
         odin = { "odinfmt" },
      },
   },
}
return M

LazyVim + Mason

If you use LazyVim with Mason, cmd = { "ols" } may resolve to Mason's shim instead of your custom ols binary. OLS already documents editor-provided configuration and odin_command, so when using a custom OLS build it is safer to disable Mason only for OLS and set explicit paths.

return {
  {
    "neovim/nvim-lspconfig",
    opts = {
      servers = {
        ols = {
          mason = false,
          cmd = { "/path/to/ols" },
          settings = {
            odin_command = "/path/to/odin",
          },
        },
      },
    },
  },
}

Notes:

  • put ols inside opts.servers
  • keep Mason enabled for other language servers if you want

Emacs

For Emacs, there are two packages available for LSP; lsp-mode and eglot.

The latter is built-in, spec-compliant and favours built-in Emacs functionality and the former offers richer UI elements and automatic installation for some of the servers.

In either case, you'll also need an associated major mode.

Pick either of the below, the former is likely to be more stable but the latter will allow you to take advantage of tree-sitter and other packages that integrate with it.

The use-package statements below assume you're using a package manager like Straight or Elpaca and as such should be taken as references rather than guaranteed copy/pasteable. If you're using package.el or another package manager then you'll have to look into instructions for that yourself.

;; Enable odin-mode and configure OLS as the language server
(use-package odin-mode
  :ensure (:host github :repo "mattt-b/odin-mode")
  :mode ("\\.odin\\'" . odin-mode))

;; Or use the WIP tree-sitter mode
(use-package odin-ts-mode
  :ensure (:host github :repo "Sampie159/odin-ts-mode")
  :mode ("\\.odin\\'" . odin-ts-mode))

If you are using Emacs 29 or above you can use package-vc-install.

(package-vc-install
 '(odin-mode :url "https://github.com/mattt-b/odin-mode.git"))

(package-vc-install
 '(odin-ts-mode :url "https://github.com/Sampie159/odin-ts-mode.git"))

And then choose either the built-in eglot or lsp-mode packages below. Both should work very similarly.

lsp-mode

As of lsp-mode pull request 4818 ols is included as a pre-configured client. You will need to install lsp-mode from source until version 9.1 has been released. Just M-x lsp-install-server and select ols. This will download and install the latest version of ols from the releases. Then start lsp-mode with M-x lsp or add hook on the below package

;; Pull the lsp-mode package from elpa
(use-package lsp-mode
  :commands (lsp lsp-deferred))

;; OR Pull lsp-mode from source using Straight this snippet has the install instructions for installing straight.el
(defvar straight-use-package-by-default t)
(defvar straight-recipes-repo-clone-depth 1)
(defvar straight-enable-github-repos t)
(defvar bootstrap-version)
(let ((bootstrap-file
       (expand-file-name
        "straight/repos/straight.el/bootstrap.el"
        (or (bound-and-true-p straight-base-dir)
            user-emacs-directory)))
      (bootstrap-version 7))
  (unless (file-exists-p bootstrap-file)
    (with-current-buffer
        (url-retrieve-synchronously
         "https://raw.githubusercontent.com/radian-software/straight.el/develop/install.el"
         'silent 'inhibit-cookies)
      (goto-char (point-max))
      (eval-print-last-sexp)))
  (load bootstrap-file nil 'nomessage))

;; Configure straight.el
(straight-use-package 'use-package)

(use-package lsp-mode
  :straight (lsp-mode :host github :repo "emacs-lsp/lsp-mode")
  :commands (lsp lsp-deferred))

;; Add a hook to autostart OLS
(add-hook 'odin-mode-hook #'lsp-deferred)
(add-hook 'odin-ts-mode-hook #'lsp-deferred) ;; If you're using the TS mode

eglot

;; Add OLS to the list of available programs
;; NOTE: As of Emacs 30, this is not needed.
(with-eval-after-load 'eglot
  (add-to-list 'eglot-server-programs '((odin-mode odin-ts-mode) . ("ols"))))

;; Add a hook to autostart OLS
(add-hook 'odin-mode-hook #'eglot-ensure)
(add-hook 'odin-ts-mode-hook #'eglot-ensure) ;; If you're using the TS mode

Helix

Helix supports Odin and OLS by default. It is already enabled in the default languages.toml.

If ols or odinfmt are not on your PATH environment variable, you can enable them like this:

# Optional. The default configration requires OLS in PATH env. variable. If not,
# you can set path to the executable like so:
# [language-server.ols]
# command = "path/to/executable"

Micro

Install the LSP plugin

Configure the plugin in micro's settings.json:

{
	"lsp.server": "c=clangd,go=gopls,odin=ols"
}

Kate

First, make sure you have the LSP plugin enabled. Then, you can find LSP settings for Kate in Settings -> Configure Kate -> LSP Client -> User Server Settings.

You may have to set the folders for your Odin home path directly, like in the following example:

{
    "servers": {
        "odin": {
            "command": [
                "ols"
            ],
            "filetypes": [
                "odin"
            ],
            "url": "https://github.com/DanielGavin/ols",
            "root": "%{Project:NativePath}",
            "highlightingModeRegex": "^Odin$",
            "initializationOptions": {
                "collections": [
                    {
                        "name": "core",
                        "path": "/path/to/Odin/core"
                    },
                    {
                        "name": "vendor",
                        "path": "/path/to/Odin/vendor"
                    },
                    {
                        "name": "shared",
                        "path": "/path/to/Odin/shared"
                    },
                    {
                        "name": "src", // If your project has src-collection in root folder, 
                        "path": "src"  // this will add it as a collection
                    },
                    {
                        "name": "collection_a",
                        "path": "/path/to/collection_a"
                    }
                ],
                "odin_command": "path/to/Odin",
                "verbose": true,
                "enable_document_symbols": true,
                "enable_hover": true
            }
        }
    }
}

Kate can infer inlay hints on its own when enabled in LSP settings, so enabling it separately in the server config can cause some weird behavior.

About

Language server for Odin

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0