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

Skip to content
tischenkobPublic
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

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_range_format: Format only the declarations that the selection touches. Defaults to true.

  • 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_postfix_completions: After a dot on a value, offer postfix templates and builtin or core procedures that take the value, each replacing the expression. Templates: if, ifnot, not on bools; for on integers; fori on arrays, slices, strings and maps; switch with every case on enums; nil and notnil on nilable values; ^ and free on pointers; orr (or_return), ore (or_else) and defer on calls; and &, cast, transmute, paren, return, var, print, printf, logd, logi, logw, loge on any value. Procedures: delete, copy and raw_data, and strings, strconv and slice helpers such as s.contains for strings.contains(s, …) and xs.sort for slice.sort(xs[:]), adding the import when the file lacks it. Statement templates appear only when the value starts its line. Every item appears only where the code it writes compiles: orr needs a callee whose last result is a bool or nilable and an enclosing procedure whose last result takes it, ore needs two results, defer skips @(require_results) procedures, & and slicing a fixed array need an addressable value, return needs an enclosing procedure with one result of that type, slice.sort and slice.contains need ordered and comparable elements, the string procedures skip distinct strings, and a contextless procedure gets no item that needs context. Requires client snippet support. Defaults to true.

  • 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) An import named only in a when branch that the host does not build counts as used, so organize-imports on save keeps an import that another target needs, while odin check reports it on the host.

  • 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_variable_types: Turn on inlay hints for inferred variable types. Defaults to true.

  • enable_inlay_hints_comp_lit_fields: Turn on inlay hints for struct field names in positional composite literals. Defaults to true.

  • enable_inlay_hints_range_types: Turn on inlay hints for the types of range loop variables. Defaults to true.

  • enable_inlay_hints_constant_values: Turn on inlay hints for the folded value of constant expressions. Defaults to false.

  • 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. Completing after mem. also lists the members of an unimported core:mem, and accepting one adds the import.

  • 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. Inside a comp literal passed to a call, the comp literal signature comes before the procedure signature. (Enabled by default in rols)

  • 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 the code actions to invert if statements and to rewrite them as early returns. Defaults to true.

  • enable_code_action_extract_variable: Enables the code action to extract an expression into a local variable. It also offers "Extract variable (replace all N)" when the expression occurs at least twice in the enclosing block with identical text and every occurrence reads the same value. With only a cursor, it offers one action for each enclosing expression. Defaults to true.

  • enable_code_action_inline_variable: Enables the code action to inline a local variable into its uses, with the cursor on the declaration's name or on any use. With the cursor on one of several uses, a second action inlines only that use and keeps the declaration. A typed declaration keeps its type at each use: x: f32 = 1 inlines as f32(1). Defaults to true.

  • enable_code_action_extract_procedure: Enables the code action to extract selected statements into a new procedure. Defaults to true.

  • enable_code_action_add_explicit_type: Enables the code action to add the inferred type to a := declaration. Defaults to true.

  • enable_code_action_ternary: Enables the code actions converting between an if/else and a ternary expression. Defaults to true.

  • enable_code_action_unwrap: Enables the code actions to unwrap a bare block or an if body, to turn else if c {…} into else {…}, and to remove a redundant else. Loops are never unwrapped, since that runs the body once. Defaults to true.

  • enable_code_action_do_block: Enables the code actions converting a one-statement block to a do body and back. Defaults to true.

  • enable_code_action_fill_struct: Enables the code action filling the missing fields of a struct literal with zero values. Defaults to true.

  • enable_code_action_if_to_switch: Enables the code action converting an if/else-if chain of equality tests to a switch. Defaults to true.

  • enable_code_action_result_handling: Enables the code actions adding or_return, or_else, an if on the ok/error result, or discarding the results of a call. Defaults to true.

  • enable_code_action_generate_proc: Enables the code action generating a stub for a called procedure that does not exist. Defaults to true.

  • enable_code_action_named_results: Enables the code action naming the results of a procedure. Defaults to true.

  • enable_code_action_add_ok_result: Enables the code action adding a bool result to a procedure, with , _ added at each caller. It is not offered when the last result is already a bool, b8, b16, b32 or b64, or when the procedure has platform variants, as rename finds them. Defaults to true.

  • enable_code_action_result_union: Enables the quick fix changing the last result type of a procedure to a union of the types its return statements and or_return calls produce. With several results, it also names the unnamed ones, since or_return needs named results. Defaults to true.

  • enable_code_action_defer_delete: Enables the code action adding a defer that frees an allocation. Defaults to true.

  • enable_code_action_extract_constant: Enables the code action extracting a constant expression into a file-scope constant. With only a cursor, it offers one action for each enclosing expression. Defaults to true.

  • enable_code_action_inline_proc: Enables the code action inlining a procedure call. Defaults to true.

  • enable_code_action_introduce_param: Enables the code action turning a constant expression into a parameter passed by every caller. With only a cursor, it offers one action for each enclosing expression. It is not offered when the procedure has platform variants. Defaults to true.

  • enable_code_action_remove_param: Enables the code action removing an unused parameter from a procedure and its callers. A procedure with platform variants, as rename finds them, loses the parameter in every variant; the action is not offered when a variant cannot take the change (as for reorder-params) or reads that parameter. Defaults to true.

  • enable_code_action_move_decl: Enables the code action moving a top-level declaration to another file of the package, or to a new file when the client can create files. Defaults to true.

  • enable_code_action_generate_test: Enables the code action generating a @(test) stub for the procedure at the cursor in <file>_test.odin of the same package, created when the client can create files with the #+ tag lines of the source file. Odin builds a _test.odin file in every build, and core:testing does not compile for js, wasi, orca and freestanding, so a created file also gets one line per OS, such as #+build !js, for each of those that the source builds on. A source that builds only on those gets no stub, and neither does a file-private procedure, by @(private="file") or #+private file. The stub checks a result against its zero value, spelled pkg.T{} for a type of another package, with that import added to the test file. It is not offered when such an import would be shadowed by t, testing or a result name, or when the test file imports that package under another name or another package under that name. A result that testing.expect_value cannot compare, such as a struct holding a slice, is bound to _ with a comment saying it is not checked. Defaults to true.

  • enable_code_action_expand: Expand an array scalar, or_else, or_return or a range loop back to the long form. Defaults to true.

  • enable_code_action_checker_fix: Enables quick fixes for odin check errors: dropping an unused variable and removing a cast to the same type. Defaults to true.

  • enable_code_action_comment: Enables the code actions adding a doc comment above the top-level declaration at the cursor, and converting the selected comments between // lines and a /* */ block. Defaults to true.

  • enable_code_action_literal: Enables the code actions on the literal at the cursor: converting a string to and from a raw string, converting an integer between hexadecimal, decimal and binary, and adding or removing digit separators. Defaults to true.

  • enable_code_action_lift_using: Enables the code action lifting a selector path such as a.b into a using a.b statement before its first use in the block at the cursor, removing the path from every use in that block and its nested blocks. It adds #+feature using-stmt when the file lacks that tag. Defaults to true.

  • enable_code_action_attr: Enables the code actions adding and removing @(require_results), @(private) and @(test) on the top-level declaration at the cursor, where the result compiles. Defaults to true.

  • enable_code_action_add_allocator: Enables "Add allocator parameter" and "Add caller location" on the name of a top-level procedure. They add allocator := context.allocator or loc := #caller_location, pass allocator = allocator or loc = loc to each call in the body whose callee takes that parameter and gets none, such as make or new (and append for the location), and make each caller that has a parameter of that kind pass it. They refuse a contextless or foreign procedure, a variadic one, one that has the parameter or reads the name already, one with platform variants, one used other than as a callee, and one whose body has no call to pass it to. Defaults to true.

  • enable_code_action_param_pointer: Enables "Pass by pointer" and "Pass by value" on a parameter of a top-level procedure. "Pass by pointer" turns x: T into x: ^T, reads x^ in the body, or x.f for a struct, and passes &arg, refusing an argument without an address. "Pass by value" does the reverse and refuses when the body writes through the pointer, compares it with nil, or stores or passes it on. Defaults to true.

  • enable_code_action_param_object: Enables "Introduce parameter object" on a selection of two or more adjacent parameters of a top-level procedure foo. It declares Foo_Params :: struct {...} after the procedure, takes params: Foo_Params in their place, reads params.a in the body and passes Foo_Params{a = ..., b = ...} at each call. It refuses a default value, using, a parametric parameter, and a taken name. Defaults to true.

  • enable_code_action_proc_group: Enables "Make group foo" and "Add to group foo" on the name of a top-level procedure foo_a. "Make group foo" declares foo :: proc{foo_a, foo_b} over the procedures of the file named with the prefix before the last _, and refuses a taken name. "Add to group foo" adds the procedure to a group foo of the package that lacks it, and refuses when a call of the group could pick the new member. Defaults to true.

  • enable_code_action_extract_type: Enables "Extract type" on an inline struct, union, enum, bit_set, procedure type or long array type (one that nests another array or a map, or spans 16 characters) written as the type of a parameter, field or declaration. It declares a top-level type named after the field, such as Opts for opts, after the enclosing declaration, and writes its name in place. It refuses a type that names a poly parameter, a local or a local type, and an inline struct, union or enum spelled the same elsewhere in the workspace, since a named type would no longer match it. It also enables "Inline type alias" on the name of a top-level X :: Y, which writes Y at each use across the workspace and deletes the alias. It refuses distinct, a struct, union or enum declaration, a parametric alias, an alias that another package reaches unless Y is a plain name, and an exported alias whose name appears in a file the workspace filter leaves out. Defaults to true.

  • enable_code_action_reorder_fields: Enables "Reorder fields to reduce padding (A to B bytes)" on the name of a top-level struct. It sorts the fields by descending alignment, keeping the order of fields with the same alignment and the comments of each field, and is offered only when the struct shrinks on a 64-bit target. It refuses #packed, #raw_union, #align and the field alignment tags, a parametric struct, using, #subtype, a _ field, a field whose size it does not compute, and a struct that a positional literal, a transmute or a foreign block of the workspace uses. A binary layout read through a memory cast, such as a pointer cast of bytes from a file, is outside what the search can see, so check such code before applying it. Defaults to true.

  • enable_code_action_proc_tags: Enables the code actions on the name of a top-level procedure with a body that add or remove #force_inline, #force_no_inline and "contextless". "Add #force_inline" refuses a procedure that calls itself. "Add "contextless"" requires a body that never names context and calls only type conversions, builtins such as len, and procedures whose calling convention passes no context, and every use of the procedure must be a call. "Remove "contextless"" refuses when a call lies in a contextless procedure or the procedure is used other than as a callee. Both refuse an @(export) or @(link_name) procedure and one with platform variants. Defaults to true.

  • enable_code_action_swap_param: Enables the code actions moving the parameter at the cursor one place left or right in a top-level procedure, updating its platform variants and every call. Defaults to true.

  • enable_code_action_init_move: Enables the code actions moving a declaration into the init of the if, switch or for that follows it, and moving an init out above its statement. Defaults to true.

  • enable_code_action_split_decl: Enables the code actions splitting a local declaration into a declaration and an assignment, joining them back, and splitting a multi-name declaration into one declaration per name. Defaults to true.

  • enable_code_action_const_var: Enables the code actions converting a local x := v to x :: v and back, where every use keeps its meaning. Defaults to true.

  • enable_code_action_range_loop: Enables the code actions on the header of a range loop: adding an index, iterating by reference or by value, toggling #reverse, and converting between a..<10 and a..=9. Defaults to true.

  • enable_code_action_surround: Enables the code actions surrounding the statement at the cursor, or the statements a selection touches, with a block, if true, for true, when true, defer or #no_bounds_check. Defaults to true.

  • enable_code_action_expand_using: Enables the code actions removing a using. On a using statement, "Expand using" writes the path before each name the statement promotes in the rest of its block and deletes the statement, so it is the inverse of "Lift using". It leaves a #+feature using-stmt tag in place. On a using struct field, "Convert using to #subtype" keeps the implicit conversion to the embedded type and drops the promotion, and applies only when a search of the workspace finds no use of a member through the promotion. core:reflect and what reads it, such as core:encoding/json, stop treating that field as using. Defaults to true.

  • enable_code_action_named_form: Enables the code actions converting a struct literal between Foo{1, 2} and Foo{x = 1, y = 2}, and a call between f(1, 2) and f(a = 1, b = 2). A call with named arguments no longer qualifies for "Move parameter", "Remove parameter", "Introduce parameter" and ols query reorder-params, which refuse a call site that names its arguments. Defaults to true.

  • enable_code_action_type_switch: Enables the code actions on type assertions and type switches. "Convert to type switch" turns if v, ok := u.(T); ok {...} and its else if chain over one subject into switch v in u, with the else as case:. "Convert to if chain" turns a type switch of at most eight cases back. "Add #partial" and "Remove #partial" change the switch, and removal needs a case for every variant. "Add default case" adds case:. Defaults to true.

  • enable_code_action_cast: Enables the code actions on casts. "Convert to T(x)" and "Convert to cast(T)x" switch between the two forms, with parentheses around a type such as ^T or []u8. "Convert to auto_cast" and its reverse apply where the place of the expression expects T. "Convert to transmute" and its reverse apply only between pointer types, where both keep the value. Defaults to true.

  • enable_code_action_bit_set: Enables the code actions converting .A in flags to flags & {.A} != {} and .A not_in flags to flags & {.A} == {}, and back, for one member and a flags that resolves to a bit_set. Defaults to true.

  • enable_code_action_evaluate: Enables the "Evaluate constant" code action, which replaces an expression of integer literals and + - * / % << >> & | with its value. It refuses a float, a name, a zero divisor and a value outside i64. Defaults to true.

  • enable_code_action_create_member: Enables "Create field foo" on x.foo when x is a struct of the workspace, also in another file, with the type from an assignment, an operand or the parameter that receives it, and "Create enum member Foo" on .Foo when the expected enum is in the workspace. They refuse an unknown type, a parametric struct and a member that would leave a positional literal, a switch without #partial or an enumerated array literal incomplete. Defaults to true.

  • enable_code_action_create_decl: Enables "Create local variable x", "Create global variable x" and "Create constant x" on an unresolved name whose use gives a type, and "Create struct Foo" on an unresolved Foo{a = 1}, where an untyped integer gives int. x = v becomes x := v for the local form, and the constant form takes x = 1 to file scope. They refuse when no use gives a type, and "Create struct" refuses a positional literal. Defaults to true.

  • enable_code_action_generate_lifetime: Enables "Generate destroy_foo" and "Generate init_foo" on the name of a top-level struct Foo that is not parametric or a #raw_union. destroy_foo :: proc(foo: ^Foo) calls delete on each [dynamic] and map field and names the slice, string and pointer fields in a comment, since they can be borrowed. It refuses a struct with none of these fields. init_foo :: proc(foo: ^Foo, allocator := context.allocator) calls make for each [dynamic] and map field, and refuses a struct with neither. Both refuse a name the package already declares. Defaults to true.

  • enable_code_action_generate_enum: Enables "Generate bit_set" and "Generate name table" on the name of a top-level enum whose member values are constants. "Generate bit_set" declares Flags :: bit_set[Flag] for an enum Flag, else Enum_Set :: b 10BC8 it_set[Enum], and refuses a negative value or a value over 127. "Generate name table" declares ENUM_NAMES := [Enum]string {...} with one entry per value, #sparse when the values have gaps. Both refuse a name the package already declares. Defaults to true.

  • enable_code_action_qualify: Enables the code actions converting between .A and Enum.A, and adding or dropping the type of a composite literal, where a declared type, an assignment, a return, a parameter, a field or an element supplies the type. A comparison and a case also supply the type of an enum member. Defaults to true.

  • enable_code_action_loop_label: Enables the code action adding a label to the loop at the cursor, so nested break and continue can target it. Defaults to true.

  • enable_code_action_merge_cases: Enables the code actions to merge a switch case with the next one when their bodies match, and to split a multi-value case into one case per value. Defaults to true.

  • enable_code_action_split_merge_if: Enables the code actions to split an if on &&, to merge nested ifs, and to split an if at the || under the cursor with a copy of the body in each branch, as an else-if chain or as separate ifs. Separate ifs run the body twice when both conditions hold. Defaults to true.

  • enable_code_action_rewrite_expression: Enables the code actions to flip a comparison, apply De Morgan's law and convert between compound and plain assignment. Defaults to true.

  • enable_organize_imports_on_save: Removes unused imports and adds missing ones on save through workspace/applyEdit. A new import goes among the kept imports of its collection when the file keeps one. Otherwise it goes after the first import, or at the top of the import block when that import is removed. Defaults to true.

  • 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, split like a shell does for the simple cases: whitespace separates arguments, a double or single quote at the start of an argument or right after = or : groups the text up to its closing quote. Quotes around text with whitespace are removed (-collection:x="/my path"), while quotes around text without whitespace stay as written (-define:NAME="text" reaches odin with its quotes, as before). Any other quote, such as the apostrophe in -define:MSG=it's, and every backslash is an ordinary character, so a string without such a group splits as before. Tabs and line breaks separate arguments too. A backslash is an ordinary character, so a Windows path such as C:\libs\x keeps it. An unterminated quote keeps the rest of the text in its argument. Odin rejects a repeated flag, so a flag here replaces the same flag that rols adds itself: -no-entry-point, -json-errors, a -vet-* flag that its enable_checker_vet_* key turns on, and a -collection:NAME= or -define:NAME= of the same NAME. -custom-attribute and -sanitize may repeat in Odin, so they are never dropped.

  • enable_checker_vet_shadowing: Pass -vet-shadowing to odin check and report shadowed declarations as warnings. Defaults to true.

  • enable_checker_vet_unused_variables: Pass -vet-unused-variables to odin check. Report variables that are declared but never used, as warnings. Odin rejects a variable without this flag when it is the only statement of an if, else or for body, for example if c { x := 1 }; that one stays an error. Defaults to true.

  • enable_checker_vet_cast: Pass -vet-cast to odin check. Report casts and transmutes to a type the value already has. Defaults to true.

  • enable_checker_vet_style: Pass -vet-style to odin check. Report style violations, such as a missing trailing comma before a closing brace on its own line. Defaults to true. Odin reports such a violation as a Syntax Error that stops checking the package, and so do -vet-semicolon and -strict-style. Odin reports a -vet-tabs finding on its own as well. When a check with any of these flags reports a Syntax Error or a -vet-tabs finding, rols runs the package a second time without those flags. The errors of the first run that the second run does not report show as warnings, and the rest of the diagnostics come from the second run, so a type error shows next to a missing trailing comma. The second run happens only after such an error, and not when a file that a Syntax Error names fails rols' own parser too, since the second run would stop at that syntax error as well. It doubles the time limit of the whole check from 20 to 40 seconds, shared by all second runs. The ols query commands with --apply check without these flags, but a style flag in checker_args stays and can start the second run.

  • enable_checker_vet_semicolon: Pass -vet-semicolon to odin check. Report unneeded semicolons. Defaults to true.

  • enable_checker_vet_tabs: Pass -vet-tabs to odin check. Report source lines that are not indented with tabs. Defaults to true.

  • enable_checker_strict_style: Pass -strict-style to odin check. Report style violations as hard errors; subsumes -vet-style and -vet-semicolon. Defaults to false.

  • enable_workspace_gitignore: Skip paths that git reports as ignored when walking the workspace. Does nothing outside a git repository or when git is not on PATH. Defaults to true. Workspace walks feed workspace symbols; references, rename, change signature, incoming calls and code lens; the CLI find, refs, rename and callers queries; and the package list for workspace diagnostics from odin check. Workspace symbols filter directories only and index whole packages, so a file glob such as *_gen.odin has no effect there. Imported packages and collections are never filtered. Rename and change signature do not edit git-ignored files either, so list ignored code that still compiles in workspace_include.

  • enable_excluded_file_targets: In a file that the host does not build, such as socket_linux.odin on macOS, resolve names against the files of a target that builds it, so hover, go to definition and completion reach errors_linux.odin and not the host's errors_posix.odin. The server keeps one extra symbol index per such target and fills each package of it on the first lookup from such a file. Turn it off to save that memory and the time of that first lookup; names in those files then resolve through the host index, as in upstream OLS, and can point at the host's declaration or at nothing. Defaults to true.

  • workspace_exclude: Globs relative to each workspace root. Workspace walks skip matching files and directories, and everything below a matching directory. *, ? and [...] match within one path segment, ** spans any number of segments, a glob without / matches a name at any depth, and a leading / anchors a glob to the root. Defaults to empty.

  • workspace_include: Globs relative to each workspace root, with the same syntax. Workspace walks keep matching paths even when git ignores them. workspace_exclude wins over workspace_include. Defaults to empty.

  • modernize_recipes: Your own rewrite rules for ols query modernize. Each recipe becomes the rule recipe/<name> of family recipe, which is in the default set. Editors never show them. Defaults to empty. Example:

    "modernize_recipes": [
      {"name": "sort-slice", "match": "sort.quick_sort($s)", "replace": "slice.sort($s)",
       "imports": ["core:slice"], "where": [{"var": "s", "kind": "slice"}]}
    ]
    • name: letters, digits, -, _ and .; unique.
    • match: Odin code. $name is a metavariable that matches any expression; a second $name matches only the same text, spaces ignored. One expression matches any expression in the code. Anything else, such as several statements, matches that many consecutive statements of a block. Parentheses never matter. Other names must be the same in the code. A plain pkg.name means a package: it matches only code whose pkg part names an import, under any alias, with an import path that ends in pkg, and only where no local declaration shadows that import. Use $x.name for a field of any value. A metavariable cannot stand for a field name, as in $x.$f or .$f, and a lone name or metavariable is not a valid match. A match that uses a construct the matcher does not handle, such as a procedure literal, a switch or a typed declaration, is reported and skipped.
    • replace: Odin code with the $name metavariables of match. Each one becomes the code it matched, in parentheses when it is a compound expression used as an operand. When match is one expression, replace must be one expression too. Lines after the first take the indentation of the matched code, so a string literal in replace must not span lines. $ in strings, runes and comments stays as is.
    • imports: import paths the replacement needs. A missing one is added. When the file imports the path under an alias, a pkg. qualifier of replace is written with the alias, and a qualifier of match keeps the name the code used. A fix whose package name means something else in the file is skipped.
    • where: {"var": "s", "kind": "slice"} entries. kind is slice, dynamic_array, fixed_array, map, string or pointer. Only a metavariable that matched a name or a selector such as a.b has a resolved type; any other match, such as xs[:] or a call, fails the constraint.

    A metavariable that matched an expression with a call, or_return, or_break or or_continue is rewritten only when match and replace each use it once, and only one metavariable of a match may contain one. Any other case could change how often or in which order the calls run or the control flow happens. A match is also skipped when a comment inside the matched code lies outside every metavariable that replace writes, because the rewrite would delete it. A recipe with a parse error, an unknown where kind, a $name in replace or where that match does not bind, or a repeated name is printed on stderr as recipe <name>: <problem>; skipped. The other rules still run. The match is syntactic apart from where, so check the result with odin check, which --apply does.

  • enable_lint_self_assignment: Warn when a variable is assigned to itself. Defaults to true.

  • enable_lint_identical_branches: Warn when the if and else branches, or both ternary branches, are identical. Defaults to true.

  • enable_lint_unreachable_code: Mark statements after return, break, continue, fallthrough, panic or unreachable as unnecessary. Defaults to true.

  • enable_lint_simplify: Mark code that has a shorter equivalent (array literal with identical elements, x == true, if c { return true } else { return false }, redundant parentheses, s[0:len(s)], C-style counting loops, nested ifs, manual or_else/or_return/or_break/or_continue patterns) as unnecessary and offer the rewrite as a quick fix. Defaults to true.

  • enable_lint_float_equality: Report == and != comparisons on floats. A comparison with the literal 0, 0.0, 1 or 1.0 is not reported. Defaults to true.

  • enable_lint_printf: Check fmt and log format strings: unknown verbs, argument count, argument type, and format directives passed to the non-formatting print procedures. Defaults to true.

  • enable_lint_ignored_result: Warn when a call statement discards the result of a procedure marked @(require_results), the calls the compiler rejects. Defaults to true.

  • enable_lint_unused_parameter: Mark procedure parameters that are never used in the body as unnecessary. A procedure that its package uses as a value (an argument, an assignment, a composite literal element or a parameter default) is skipped, and so is a procedure literal passed to a call, stored in a composite literal, assigned, or declared with an explicit type. Other files of the package are matched by name, and a workspace package that imports the package counts a value use through its import alias (register(a.handler)). A package outside the workspace is not read. Defaults to true.

  • enable_lint_unused_variable: Mark local variables and constants that are declared but never used as unnecessary. Defaults to true.

  • enable_lint_naming: Report names that do not follow Odin conventions: snake_case procedures and variables, Ada_Case types and enum members, SCREAMING_SNAKE_CASE constants. A true or false constant may be snake_case or SCREAMING_SNAKE_CASE. Constants inside a procedure, declarations in foreign blocks and with @(link_name) or @(export), struct fields with a tag string, and parameters of a procedure type with a calling convention other than "odin" or "contextless" are not checked. In a package with a foreign import or an import of core:dynlib, type, field, enum member and constant names are not checked either, because they may mirror C names. Defaults to true.

  • enable_lint_bool_logic: Report boolean and comparison mistakes: identical operands, conditions that are always true or false, and if or switch branches that repeat an earlier one. Defaults to true.

  • enable_lint_no_op: Report code that does nothing: arithmetic with an identity operand (x + 0, x * 1), integer division of literals that is always 0, comparing an address to nil, empty if or loop bodies, and append with no values. Defaults to true.

  • enable_lint_loops: Report loop mistakes: a body that always exits on the first iteration, a condition nothing in the body changes, an empty infinite loop (for {}), a range that runs one past the end (0 ..= len(x)), and a range over a map lookup whose value is a dynamic array, map or fixed array (for x in m[k]), which reads through a nil slot for a missing key. Defaults to true.

  • enable_lint_dead_store: Report a value stored in a variable that is overwritten before anything reads it, and writes to fields of a struct copy taken from an index, selector or range value. Defaults to true.

  • enable_lint_allocator: Report a value allocated with an explicit allocator and then freed with the context allocator, and make([dynamic]T, n), or make(Array, n) for a named dynamic array type, whose elements append adds after. Defaults to true.

  • enable_lint_sync: Report synchronisation mistakes: a lock released on the next line, a deferred lock, an atomic result assigned back to its own target, a lock struct passed or copied by value, and cleanup deferred before the error is checked. Defaults to true.

  • enable_lint_deprecated: Report uses of a declaration marked with the @(deprecated) attribute. Defaults to true.

  • enable_lint_core_misuse: Report misuses of core procedures: time.sleep with a bare integer, strings.replace with n = 0 or n = -1, a math rounding procedure on a converted integer, and an invalid regex pattern literal. Defaults to true.

  • enable_lint_integer_range: Report integer range mistakes: a shift by at least the operand's bit width, an unsigned value compared against a negative literal or zero, and an integer division converted to a float afterwards. Defaults to true.

  • enable_lint_recursion: Report a procedure whose body calls itself before any branch, loop or early return. Defaults to true.

  • enable_lint_test_attribute: Report a procedure taking ^testing.T without an @(test) attribute, and an @(test) procedure whose signature is not proc(t: ^testing.T). The signature is checked only in a file that imports core:testing, under any alias, because another test runner may define its own T. Defaults to true.

  • enable_lint_unused_declaration: On save, mark private declarations that nothing in their package references as unnecessary. Defaults to true.

  • enable_lint_imports: Report an import repeated in the same file, and an import whose package directory does not exist. Defaults to true.

  • enable_lint_invisible_characters: Report a string literal containing a literal zero-width, bidirectional or control character. Defaults to true.

  • enable_lint_triple_quote: Report a multiline raw string (`…` with a newline) that can use triple quotes (```…```), with a quick fix that keeps its value. Defaults to true.

  • enable_lint_result_order: Report a procedure whose error-like result is followed by another result, so or_return cannot be used. A bool counts as an error result only when unnamed or named ok. An enum with a None member counts as an error only when its name contains Err or another member name contains err, fail, invalid or bad. Defaults to true.

  • enable_lint_switch: Report a #partial switch that already lists every case, and a break at the end of a case. Defaults to true.

  • enable_lint_redundant_type_assertion: Report s.(T) inside case T: of switch _ in s, where s is a name or a chain of . selectors such as x.shape, which repeats the assertion the switch already made. The quick fix "Bind the switch variant" binds the variant in the switch (switch &v in s), replaces each assertion with the binding and removes local aliases such as c := &s.(T). Defaults to true.

  • enable_lint_call_arity: Report a call that passes too few or too many arguments to a resolved procedure. Defaults to true.

  • enable_lint_struct_literal: Report a struct literal that sets the same field twice or names a field the struct does not have. Defaults to true.

  • enable_lint_pure_call: Report a call to a core package procedure, such as strings.to_upper, whose result is discarded. A procedure with a pointer parameter is skipped, because it may write its output through it, except known accessors such as bytes.buffer_to_string. Defaults to true.

  • enable_lint_use_stdlib: Mark hand-written loops and comparisons that a core library procedure or builtin already does (slice.contains, slice.linear_search, strings.contains, strings.has_prefix/has_suffix, min/max/abs/clamp, copy, slice.fill, math.sum) as unnecessary and offer the rewrite as a quick fix. A fill of a fixed array becomes an array assignment (arr = v) where Odin broadcasts the value, and an untyped {…} or .Name value is written with its element type. Defaults to true.

  • enable_code_lens_references: Show a reference count above every top-level declaration. Defaults to true.

  • enable_selection_range: Expand the selection outwards through the syntax tree. Defaults to true.

  • checker_targets: Odin targets that the compile gate of ols query … --apply always checks besides the current one, such as ["windows_amd64", "js_wasm32"], or a bare OS name such as "windows" for its default architecture. A name that is not one of the gate's known targets is skipped with a warning:. The gate also adds the targets that the touched files need. See "Command line queries".

  • checker_variants: Extra odin check arguments for the compile gate of ols query … --apply, one string per extra check on the current target, such as ["-define:SIM=true"] for code that only builds with that define. Each string is split like checker_args and added after it. A string with a -target: value, such as "-define:SIM=true -target:linux_amd64", checks on that target instead and is named as written. Defaults to empty. See "Command line queries".

  • 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.

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.

  • tabs: Tabs or spaces.

  • tabs_width: How many characters one tab represents.

  • convert_do: Convert all do statements to brace blocks.

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

  • 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 statement in the clause contains one simple statement, it will inline the case and statement in one line.

  • 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 }

  • 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. On an import alias, or on the x of a qualifier x.y or alias :: x that resolves to an import, rename renames that import in the current file only: the alias, or a new alias before the path of an import without one, and every qualifier of the file that resolves to it. It is refused when the new name is not a valid identifier, is a keyword or a builtin name, names another import of the file, is declared at file scope or elsewhere in the package, or is a local visible at a qualifier, which would capture it. On the name of a package clause, rename renames the package as ols query rename-package does: every package clause of the directory, the import paths and unaliased qualifiers of its importers, and the directory itself, since Odin names an unaliased import after its directory. It needs a client that can rename files (resourceOperations with rename) and sends workspaceFolders, since the search for importers walks those folders. Without either, and for each cause that rename-package lists below, the rename is refused. The editor rename does not show the warnings that rename-package prints, such as a qualifier it could not resolve, so run the command line to see them.
  • References
  • Signature help
  • Hover

Command line queries

ols query <command> prints one line per result as file:line:col: text; --json prints the LSP objects instead. Positions are file:line:col, 1-based, columns in bytes, in both input and output. --root DIR sets the workspace, default: the nearest directory with an ols.json above the file, else the cwd. Every path argument, --root and move --to included, is relative to the cwd; the symlinks of the existing part of a path are resolved. --help or -h, alone or with any command, prints the usage text on stdout and exits 0.

  • def, refs, hover, impl FILE:LINE:COL
  • callers, callees FILE:LINE:COL: the call hierarchy of the procedure at the position, as [{name, uri, range, fromRanges}]
  • symbols FILE: the outline of the file, one file:line:col: Kind name line per symbol, by position, with the members of a struct, enum or bit_field indented by two spaces below it. The order is the same on every run, and --json lists the same order. A file without declarations prints nothing ([] with --json) and exits 0
  • actions FILE:LINE:COL[-LINE:COL] [--apply TITLE [--no-check]]: a range of one character on one line counts as a cursor, and a cursor in a line's indentation counts as a cursor on its first token. An inexact selection means the smallest expression around it, or for Extract procedure the whole statements it touches. --apply picks one action by its exact title; a file that cannot be read is a refusal like for rename, with the actions: refused, nothing written summary. Two actions at one position that share a title get the first line of the code they change in parentheses, such as Merge nested if (if a {), and a numeric suffix like #2 when that does not tell them apart. Titles that occur once stay unchanged.
  • rename TARGET NEW [--apply [--no-check]]: refused, before any edit is computed, when NEW is not a valid identifier, is a keyword, or a builtin name such as len or int (fields and enum members may use builtin names, which Odin allows); when NEW is already declared in the declaring scope (the package, the type, or the local scope; a package declaration in a when branch counts, and its cause says so); when a reference would resolve to another declaration named NEW, or a use of NEW would resolve to the renamed local, each with its file:line:col; when the declaration is in core:, vendor:, base: or outside the workspace folders; and on an import path or the name of a package clause, which rename-package renames. On an import alias or a package qualifier that resolves to an import, rename renames that import in the target's file only, with the refusals that the Rename entry under Features lists. NEW equal to the old name exits 3. A warning: line names up to 10 workspace files, then a count, that the gitignore, workspace_exclude or workspace_include filter skipped but that contain the old name as a whole word, since the rename does not change them. A package-level declaration is renamed together with its platform variants, and so are their references, in the files that the current target does not build too. A variant is another declaration of the same name at file scope (under when and in foreign blocks included) in a file of the same directory with the same package clause, except a #+build ignore file. Two declarations that every build includes together are duplicates, not variants: both outside any when in files that the current target builds, or both in the same when branch of one file. when conditions are not evaluated, so two declarations in different when statements count as variants. NEW declared in the file of the declaration, in the file of a variant, or in another file of the package is refused only when some OS, architecture and #+build-project-name project builds it and takes its when branch together with the renamed declaration or a variant. NEW in another file is also not refused when it is private to that file. Two arms of one when statement never build together, whatever their condition. Otherwise only comparisons of ODIN_OS or ODIN_ARCH with a value such as .Linux, true, false, !, &&, || and parentheses are evaluated there; any other condition can go either way. refs on such a declaration lists the references of its variants too. A field or member of a struct, enum or bit_field type with platform variants is renamed in each variant that has a member of that name, and NEW already a member of any of them is refused. The field rename is also refused when a variant of the type is an alias or another type that is no struct, enum or bit_field, or lacks the member but has a using field.
  • reorder-params TARGET --order 2,0,1 [--apply [--no-check]]: position on a procedure name; --order lists the new parameter order by old index. Callers are updated. Refused with the one cause that applies: the position is not on the name of a top-level procedure; the procedure has no body, is polymorphic or has a where clause, has an attribute that fixes its signature (export, link_name, deferred_*), has a parameter without a name, with flags such as #any_int or using, with a default value, or is variadic; --order does not list each parameter index once; the procedure is used as a value; or a caller names, spreads or omits arguments. The platform variants of the procedure, as rename finds them, are reordered too, with the calls in the files of other targets. The reorder is refused when a variant is not a single procedure declaration, cannot change for one of the causes above, or has other parameter names or types, with the error "the variant of f at FILE:LINE:COL has different parameters"
  • move TARGET --to FILE.odin [--apply [--no-check]]: position on a top-level declaration name; --to names a file of the same directory, created when missing. A relative --to is relative to the cwd, like every other path (before, it was relative to the directory of the declaration, so --to b.odin from another directory now names ./b.odin and is refused unless the cwd is the declaration's directory). The directories compare with symlinks resolved, so an absolute path through a symlink such as macOS /tmp works. The target gains the imports the declaration needs, each sorted among the target's imports of the same collection, or in a new group after the last import when the target has none of that collection; the source loses each import that only the declaration used; an import that was already unused stays. Refused when the target imports one of those packages under another name, or another package under the same name. A created target starts with the #+ tag lines of the source file, such as #+build and #+private. Refused for a created target whose name lacks the OS and architecture suffix of the source file's name, or adds one, as in --to helper.odin from main_windows.odin. Also refused for file-private declarations and those using file-private symbols, and for an existing target whose #+private tag differs from the source file's, such as a public target for a declaration in a #+private file, with the error "b.odin is public but the file of the declaration is #+private"
  • rename-package DIR NEW [--apply [--no-check]]: renames the package in DIR, a directory or a collection path like shared:util, to NEW. It rewrites the package clause of every .odin file in DIR, for every platform, with package old_test becoming package NEW_test; every import path in the workspace that steps into DIR or a package below it, keeping its collection prefix or relative form and each / or \ separator (a relative path inside DIR that leaves it with .. stays as it is); the old.x qualifiers, alias :: old values and #defined(old) arguments that resolve to the package in each importer that imports it without an alias (an aliased import, import old "…" included, only changes its path); and finally renames DIR to the sibling directory NEW. Odin names an unaliased import after its directory, not its package clause. Refused, with one error: line per cause, when DIR is not a directory of .odin files, is the workspace root, lies outside the workspace folders or in core:, vendor: or base:, or holds the root of a collection; when a file's package clause, ignoring _test, differs from the directory name; when NEW is not a valid identifier, is a keyword or a builtin name; when the sibling NEW exists; when an importer already binds NEW, through another import, a declaration in its package, or a local visible at a rewritten qualifier, each as file:line:col; and when an import resolves into DIR, symlinks resolved, but no segment of its path names DIR, such as a path through a symlink, which it cannot rewrite; a relative path from a file in DIR is exempt only when its segments, followed without resolving symlinks, stay in DIR. NEW equal to the current name exits 3. warning: lines name the files the workspace filter skipped that mention the old import path or qualifier, up to 10 comments, foreign import paths (in when blocks too) and #load, #load_hash, #load_directory or #config strings that mention the old name, then a count, and each old.x in an unaliased importer that does not resolve, since the rename does not change them. The dry-run diff of rename-package is a git-style preview for reading: it is not guaranteed to work with git apply. The check after the write matches an existing error whose message names the old package against the same message with the new name, so such an error does not roll the rename back
  • attr add TARGET KEY[=VALUE], attr remove TARGET KEY, attr remove --all KEY [DIR] and attr rename OLD NEW [DIR], each with [--apply [--no-check]]: edit @(…) attributes where the source writes them. A declaration is a value declaration, a foreign block, a foreign import or an import, at any depth: in when blocks, foreign blocks and procedure bodies too. TARGET names the declaration by a position in its attributes, names or type, or by a symbol path; a struct field, enum member or bit_field field is refused, since attributes go on declarations. add appends KEY[=VALUE] to the last group (@(a) becomes @(a, KEY), and @a becomes @(a, KEY)), or inserts @(KEY) on its own line above a declaration without attributes, at its indentation. It is refused when KEY is not an identifier, when the declaration already has KEY in any group, and when VALUE does not parse as one Odin expression. remove drops each KEY element with its comma, keeping the comments of the elements that stay; an emptied group goes, with its line when the line holds nothing else; a missing KEY exits 3. remove --all removes KEY from every declaration in DIR, a directory or a collection path, or in the workspace, which is walked with the workspace filter; rename renames the key and keeps its value across the same scope, and is refused at each declaration that already has NEW, as file:line:col. DIR in core:, vendor: or base:, or outside the workspace folders, is refused, and so is a TARGET there. A file that mentions KEY but does not parse is skipped with a warning:, as are the files below DIR, or in the workspace, that the workspace filter skipped and that mention it. --all on any other command is a usage error. The compile gate of --apply rolls back an attribute that odin check rejects, such as an unknown key
  • api PKG [NAME]: the exported symbols of a package, one per line with the first line of the doc comment, sorted by name. PKG is a directory or a collection path like core:strings. With NAME, the full signature and doc comment of one symbol
  • find QUERY: fuzzy symbol search over the workspace, as file:line:col: Kind name. It reads every .odin file that the workspace filter keeps, outside hidden directories, so it also finds private declarations (@(private), #+private), marked (private), and the declarations of files that another target builds, marked (other platform). A file that no target builds (#+build ignore) or that does not parse is left out. With --json each match is the LSP WorkspaceSymbol plus the booleans private and otherPlatform
  • check [DIR…]: odin check errors and the lints below, without building or running, of each DIR together. Without DIR it checks the package in the cwd when the cwd holds .odin files, else every package below the workspace root (the directories with .odin files that the workspace filter keeps, hidden directories such as .snapshots left out), but only when an ols.json or --root defines that root. A DIR, cwd or root without a package is an error: no package in DIR and exits 1. It exits 1 when any reported diagnostic has the error severity, 0 otherwise, warnings included. When odin does not start, times out, exits with an error and no output, or prints something other than its JSON error list, it prints error: … on stderr and exits 1, so a check that did not run is not a clean check. When there is no package to check (the directory is in checker_skip_packages, which also matches the path with symlinks resolved, such as /private/var/… for /var/… on macOS), odin does not start, and check prints the lints and exits 0
  • lint FILE|DIR… [--fail-on CODE,…]: per-file lints, unused imports and unused private declarations, without running the compiler. A DIR covers itself and every package directory below it that check would walk: the workspace filter, .gitignore included, and the exclude_path profile select the directories, hidden directories such as .git or .claude are skipped, and within a kept directory the same filter selects the files, so a gitignored file is not linted. A DIR or FILE named on the command line is never filtered itself, and a DIR that the filter skips, such as a gitignored build/, covers every package directory below it, hidden ones and exclude_path aside; check filters the files it lints the same way; a DIR without a package below it is an error: no package in DIR and exits 1, as for check. Several paths print their results in the order given, and a file that two paths share is reported once. --fail-on exits 1 when any listed code is reported for any path, for CI gates. A file that does not parse is still linted on what the parser recovered, as the editor does: FILE: the file does not parse, its lints may be incomplete goes to stderr, its lints are reported and count for --fail-on, and the parse error itself does not change the exit code
  • tests [DIR|FILE…]: the @(test) procedures, as file:line:col: name, that odin test would run on this target: a file with #+build ignore, or one that its name or #+build tags exclude from the target (the host, or the -target: of checker_args), is left out. A FILE named on the command line is read as odin test FILE -file builds it: its name does not exclude it, only its #+build tags. Without an argument it covers the same packages as check. --json lists name, file, line, col and the package name pkg
  • test DIR [NAME,…]: runs odin test DIR with the collections, defines and checker_args of ols.json and plain output; names select tests as -define:ODIN_TEST_NAMES does, pkg.name or name; a name that no test of DIR has is an error: no test NAME in DIR and exits 1, since odin test itself exits 0 after "No tests to run"
  • modernize [PATH…] [--rule ID,…] [--list] [--diff] [--apply [--no-check]]: rewrites each file with the quick fixes of the simplify, use_stdlib and lint rules, pass after pass until nothing changes (at most 8 passes). Without PATH it walks the workspace with the workspace filter, .gitignore included; a directory PATH is walked with the same filter. Hidden directories below the walked directory, such as .git or .snapshots, are skipped, as for lint. The default rules are the exact, behavior-preserving ones (families idiom and migration) and your own recipe/<name> rules from the modernize_recipes config key. The migration rules rewrite deprecated or removed Odin forms into the current ones with the same meaning: base-imports (core:runtime, core:intrinsics and core:builtin to base:), os2-import (core:os/os2 to os2 "core:os", skipped when the file already imports core:os), field-align (#field_align to #min_field_align), align-parens (#align N, #min_field_align N and #max_field_align N to #align(N) and so on), for-blank (for in x to for _ in x), switch-blank (switch in u to switch _ in u), partial-dup (#partial #partial switch to one #partial), optimization-mode ("minimal" to "none", "size" and "speed" to "favor_size", as the compiler messages name them), proc-do-body (proc() do stmt to a braced body), strconv-itoa and strconv-ftoa (deprecated strconv.itoa(buf, i) to strconv.write_int(buf, i64(i), 10) and ftoa to write_float, through any import alias), and feature-tags (adds #+feature using-stmt for a using statement or parameter, and #+feature dynamic-literals for a typed map or [dynamic] literal with elements). file-tags turns //+build, //+private and the other old tag comments into #+ tags; it is a review rule because the compiler ignores the comment form, so the rewrite brings back the build filter and changes which files build. triple-quote is an idiom rule: it turns a multiline raw string into a triple-quoted raw string (```…```) and indents the content to the line where the literal starts, so a leading or trailing newline stays as a blank line and the value is unchanged. Rules that delete code or can change behavior (family review, such as unused-variable/remove, use-stdlib/copy-loop, use-stdlib/clamp-if and the max, min and abs rules, which differ on floats) run only when --rule names them or their family. redundant-else is an idiom rule because it fires only when the if-branch ends in return, break or continue, the if has no label, is not part of an else if chain, and is a statement of a block that is not a when body. The else must also declare no name that another statement of that block mentions, except as a field name after a selector or an enum member after a dot. When statements follow the if, the else must not end in return, break, continue, fallthrough, panic or unreachable and must hold no defer of its own. --list prints every rule with its family and whether it is a default. The default output is file:line:col: [rule] title per fix; a fix from a later pass is marked (pass N) and its position is in the text the previous pass left. --diff and --apply treat every changed file as one edit and behave as for rename below, except that the summary line counts the fixes the list prints, such as modernize: 14 edits in 7 files: --diff prints the unified diff and summary line, --apply writes every file or none after odin check, and --json prints the same object. All modes use the refactor exit codes below: 0 when there are fixes (listed, previewed or applied), 3 when nothing changes, 2 for an unknown rule, and 1 refused, with nothing written, when a file cannot be read or a pass was undone because its result did not parse; each cause is an error: line. A file still changing after 8 passes, or one whose remaining fixes all span the place where imports go, is reported on stderr without changing the exit code. A file that does not parse is skipped with a note on stderr. A rule runs only while its lint is enabled in the config; the migration rules have no lint and always run. Imports the fixes need are added, sorted among the imports of the same collection; nothing is reformatted

TARGET is FILE:LINE:COL or a symbol path PKG.Name or PKG.Name.Member. PKG is a directory, relative to the cwd, or a collection path like core:strings: the longest prefix before a . that is a directory of .odin files, so core:path/slashpath.join and directories with dots work. .Name and ./Name name a symbol of the package in the cwd. Member is a struct field, an enum member or a bit_field field. A symbol path that is not found, is declared more than once (in when branches, say) or names a member of a type without members is refused, for example ols query rename src/game.Player.hp health.

Without --apply, rename, reorder-params, move, rename-package and attr print a dry run: a unified diff of every changed file (--- a/PATH, +++ b/PATH, paths relative to the root, a created file diffed from /dev/null) and a summary line such as rename: 7 edits in 3 files. A renamed directory gets a git-style header first (diff --git a/OLD b/NEW, rename from OLD, rename to NEW), and the files in it are diffed from their old path to their new one. --apply, there and on actions, writes every file or none:

  1. Every new file text is computed in memory first. An invalid or overlapping edit range refuses the edit.
  2. odin check runs on each package directory the edit touches and on each workspace package that imports one, directly or through other importers, found with the workspace filter. The check passes the collections, defines, -file or -no-entry-point, -json-errors and your checker_args, but none of the enable_checker_vet_* and enable_checker_strict_style flags: -vet-style turns a missing trailing comma into a Syntax Error that stops checking, which would blind the gate. It also passes -max-error-count:100000, unless checker_args has its own -max-error-count, because Odin otherwise stops at 36 errors and reports a different subset on each run. Then the files are written, and odin check runs again. The summary line ends with the number of packages checked, such as rename: 7 edits in 3 files written, 4 packages checked, and, when the gate also checked other targets (see below), with those targets, such as , also on windows_amd64; a target on which every package was dropped as not building there is not named. The JSON summary reads the same. Each odin check run of the gate has 20 seconds for each batch of packages as large as the core count (the editor check keeps one 20-second budget), capped at 10 minutes, and a run that exceeds it refuses the edit; --no-check skips the check. The gate also checks other build targets. A touched file that #+build or a file name suffix such as _windows.odin or _js.odin excludes from the current target adds one -target: value on which it builds, chosen from windows_amd64, linux_amd64, darwin_arm64, freebsd_amd64, openbsd_amd64, netbsd_amd64, js_wasm32, wasi_wasm32, orca_wasm32, freestanding_wasm32, freestanding_amd64_sysv and then the other architectures. The same goes for every other file in the directory of a touched file, such as lib_windows.odin next to an edited lib.odin, and for every file of an importer directory. Such a target checks the directories of the files that need it and their importers, directly or through other importers, not every package. A when condition adds no target: a branch under when ODIN_OS == .Windows in a file the current target builds is checked on windows_amd64 only when another file needs that target or checker_targets names it. A touched file that builds on none of the candidate targets and is not #+build ignore gets a warning: and is not checked. The current target is the host, or the -target: of checker_args. The targets in checker_targets in ols.json (windows_amd64, or a bare OS name such as windows for its default architecture) are always added to those and check every package, and a name outside the gate's known targets is skipped with a warning:. Each entry of checker_variants, such as -define:SIM=true, adds one more check of every package on the current target with those arguments after checker_args, and the summary names it after also on, such as , also on -define:SIM=true. An entry with a -target: value, such as -define:SIM=true -target:linux_amd64, runs on that target and is named as written. The packages are checked for every target before and after the write. On a target other than the current one, and in a checker_variants check, a package whose check before the write reports an error in a file outside the workspace does not build there, such as a package that imports core:os, which panics on js_wasm32: a warning: names it, and the gate runs that check without it, before and after the write. A package whose errors on that target are all in workspace files stays checked there. A target-only file needs no SDK: odin check does not link. Since Odin dev-2026-10, odin check refuses a Windows target on another host: it asks for -windows-sdk-root, which only odin build accepts. The gate then skips that Windows check with a warning: and keeps checking the other targets. A Windows -target: in checker_args makes every check fail, with a hint to drop it; the gate refuses the edit, and the editor shows the failure once in a message.
  3. A file that changed on disk between the edit's computation and the write refuses the edit.
  4. An error that was not there before restores every file byte for byte and deletes the files the edit created. Errors are matched by the first line of their message, in any of the checked packages, and a Different package name, expected … error is keyed by its two names in sorted order, since Odin swaps the names by parse order: a swap is the same error and a third name is a new one. For rename and rename-package, an existing error that is not matched as it is also matches with the old name replaced by the new one as a whole word, but only when it lies on a line that the edit changes, so an error that names the renamed symbol or package is not new and an error about another symbol of the same name stays as it is. Odin can report a different set of errors on each run, so before the edit counts as failed, the gate restores the files and checks the original code once more, only in the checks and packages whose errors after the write name the file of a new error. An error that this check of the original code reports as often as the check after the write is not new: the first check missed it. Then the edit is written again, after the same check that no file changed on disk, and when new errors remain, every check runs once more on the written code; the second check covers every package, as the first one did. An error is new only when both checks after the write report it, so an error that one run after the write reports by chance is not new. When no new error remains, a warning: says so and the edit stays written. A check of the original code or a second check after the write that cannot run keeps the new errors, with a warning:. The summary still counts the packages of the first check.
  5. A check that cannot run (no odin, a timeout, output that is not its JSON, a failing exit with no output) refuses the edit. A package check that a signal kills before it prints anything is logged and runs once more within the same time limit, and only a second such crash refuses the edit. A failed write restores the files it wrote, including the one that failed.
  6. A directory rename (an LSP RenameFile) runs after every file is written, and the check after it runs on the new path. A directory that disappeared, or a target that appeared, since the edit was computed refuses the edit. A rollback renames the directory back first, then restores the files; a rename that fails restores every file F6B7 .

When every package to check is missing or listed in checker_skip_packages, a warning: line on stderr (a reasons entry in JSON) says so and the edit is written without a check. When the check before the write already reports errors in a directory, a warning: line names it: a parse error stops odin check there, and so does a -max-error-count in checker_args, so the check cannot see new errors that hide behind them. --no-check skips both checks. With --json these commands print one object, {"status", "edit", "summary", "reasons"}, where status is applied, dry_run, refused, noop or check_failed and edit is the LSP WorkspaceEdit. In text mode each refusal cause is an error: … line on stderr.

Exit codes of the refactor commands: 0 applied or previewed, 1 refused with nothing written, 2 usage error, 3 nothing to change, 4 rolled back after odin check reported new errors. When a rollback cannot restore a file or rename a directory back, the command exits 1 with status refused, and each file that remains modified or directory that remains renamed gets its own error: line. Read-only queries keep their own codes. Every command exits 2 with the usage text when it gets more positional arguments than it takes: check, lint, tests and modernize take several paths, test takes several names after DIR, and every other command takes the arguments it lists.

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"
}

Claude Code

misc/claude-plugin is a Claude Code plugin: it registers ols as the LSP server for .odin files and ships the ols skill, which tells the agent to find code through the LSP tool, learn packages with ols query api, run ols query check after edits and apply refactorings and tests with ols query. Add the directory holding it as a local marketplace, or copy it to ~/.claude/local-plugins/odin-lsp as install.sh does.

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