diff --git a/Cargo.lock b/Cargo.lock index 5a81a988b1..309629e00b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4672,6 +4672,7 @@ dependencies = [ "tree-sitter-css", "tree-sitter-dart", "tree-sitter-elixir", + "tree-sitter-fsharp", "tree-sitter-gdscript", "tree-sitter-go", "tree-sitter-graphql", @@ -10395,6 +10396,16 @@ dependencies = [ "tree-sitter-language", ] +[[package]] +name = "tree-sitter-fsharp" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "248fccdffd6f029b4932cf2c619b0a40ccaeab3c32764c237316a717c0c72aa2" +dependencies = [ + "cc", + "tree-sitter-language", +] + [[package]] name = "tree-sitter-gdscript" version = "6.1.0" diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index 0f6ac946e2..13d0ca768f 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -288,6 +288,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +## tree-sitter-fsharp queries + +`crates/ide-language/queries/fsharp_signature/highlights.scm` is the signature grammar's +`highlights.scm` from [tree-sitter-fsharp](https://github.com/ionide/tree-sitter-fsharp) +0.3.13 (the grammar itself is a Cargo dependency). + +### MIT License (tree-sitter-fsharp) + +Copyright (c) 2023 Nikolaj Sidorenco + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + ## nvim-treesitter queries `crates/ide-syntax/queries//locals.scm` are derived from the `locals.scm` diff --git a/crates/ide-language/Cargo.toml b/crates/ide-language/Cargo.toml index 835cca5702..446497d502 100644 --- a/crates/ide-language/Cargo.toml +++ b/crates/ide-language/Cargo.toml @@ -34,6 +34,7 @@ tree-sitter-c = "0.24.2" tree-sitter-cpp = "0.23.4" tree-sitter-objc = "3.0.2" tree-sitter-c-sharp = "0.23.5" +tree-sitter-fsharp = "0.3.13" tree-sitter-ruby = "0.23.1" tree-sitter-php = "0.25.1" tree-sitter-json = "0.24.8" diff --git a/crates/ide-language/queries/fsharp/outline.scm b/crates/ide-language/queries/fsharp/outline.scm new file mode 100644 index 0000000000..5aa473ff7d --- /dev/null +++ b/crates/ide-language/queries/fsharp/outline.scm @@ -0,0 +1,43 @@ +(namespace name: (_) @name) @def.namespace +(named_module name: (_) @name) @def.module +(module_defn . (identifier) @name) @def.module +(module_defn (access_modifier) . (identifier) @name) @def.module + +(record_type_defn (type_name type_name: (_) @name)) @def.struct +(union_type_defn (type_name type_name: (_) @name)) @def.enum +(enum_type_defn (type_name type_name: (_) @name)) @def.enum +(interface_type_defn (type_name type_name: (_) @name)) @def.interface +(anon_type_defn (type_name type_name: (_) @name)) @def.class +(type_abbrev_defn (type_name type_name: (_) @name)) @def.type +(delegate_type_defn (type_name type_name: (_) @name)) @def.type +(type_declaration (type_name type_name: (_) @name)) @def.type +(type_extension (type_name type_name: (_) @name)) @outline.extension +(exception_definition exception_name: (_) @name) @def.class + +(additional_constr_defn "new" @name) @def.constructor + +(union_type_case (identifier) @name) @def.enum_member +(enum_type_case . (identifier) @name) @def.enum_member +(record_field (identifier) @name) @def.field + +; Members: `member this.Add`, `static member Zero`, `abstract Area`, `val X`, `member val Auto`. +(method_or_prop_defn name: (property_or_ident method: (identifier) @name) args: (_)) @def.method +(method_or_prop_defn name: (property_or_ident . (identifier) @name .) args: (_)) @def.method +(method_or_prop_defn name: (property_or_ident method: (identifier) @name)) @def.property +(method_or_prop_defn name: (property_or_ident . (identifier) @name .)) @def.property +(member_defn (property_or_ident (identifier) @name)) @def.property +(member_defn (member_signature . (identifier) @name (curried_spec (arguments_spec)))) @def.method +(member_defn (member_signature . (identifier) @name)) @def.property +(member_defn . (identifier) @name) @def.field + +; `let` bindings of a module, namespace or type; locals stay out of the outline. +(file (declaration_expression (function_or_value_defn (function_declaration_left [(identifier) (op_identifier) (active_pattern)] @name)) @def.function)) +(namespace (declaration_expression (function_or_value_defn (function_declaration_left [(identifier) (op_identifier) (active_pattern)] @name)) @def.function)) +(named_module (declaration_expression (function_or_value_defn (function_declaration_left [(identifier) (op_identifier) (active_pattern)] @name)) @def.function)) +(module_defn (declaration_expression (function_or_value_defn (function_declaration_left [(identifier) (op_identifier) (active_pattern)] @name)) @def.function)) +(type_extension_elements (function_or_value_defn (function_declaration_left [(identifier) (op_identifier) (active_pattern)] @name)) @def.function) +(type_extension_elements (function_or_value_defn (value_declaration_left (identifier_pattern . (long_identifier_or_op) @name .))) @def.variable) +(file (declaration_expression (function_or_value_defn (value_declaration_left (identifier_pattern . (long_identifier_or_op) @name .))) @def.variable)) +(namespace (declaration_expression (function_or_value_defn (value_declaration_left (identifier_pattern . (long_identifier_or_op) @name .))) @def.variable)) +(named_module (declaration_expression (function_or_value_defn (value_declaration_left (identifier_pattern . (long_identifier_or_op) @name .))) @def.variable)) +(module_defn (declaration_expression (function_or_value_defn (value_declaration_left (identifier_pattern . (long_identifier_or_op) @name .))) @def.variable)) diff --git a/crates/ide-language/queries/fsharp_signature/highlights.scm b/crates/ide-language/queries/fsharp_signature/highlights.scm new file mode 100644 index 0000000000..583e6a3bca --- /dev/null +++ b/crates/ide-language/queries/fsharp_signature/highlights.scm @@ -0,0 +1,279 @@ +; Copied from tree-sitter-fsharp 0.3.13 (fsharp_signature/queries/highlights.scm), MIT licence, +; see THIRD_PARTY_LICENSES.md. The crate exports no constant for it. + +;; Highlights for the fsharp_signature grammar (.fsi files). +;; Derived from queries/highlights.scm, restricted to nodes the signature +;; grammar actually produces (it narrows the expression layer and declares +;; its own supertypes, so `_type`/`_pattern`/expression nodes are absent). + +;; ---------------------------------------------------------------------------- +;; Literals and comments + +;; `@spell` first: the colour capture, listed last, is the one that wins. +[ + (line_comment) + (xml_doc) + (block_comment) +] @spell @comment + +(xml_doc) @spell @comment.documentation + +(const + [ + (_) @constant + (unit) @constant.builtin + ]) + +(primary_constr_args (_) @variable.parameter) + +(class_as_reference + (_) @variable.parameter.builtin) + +;; ---------------------------------------------------------------------------- +;; Types + +(type_name type_name: (_) @type.definition) +(exception_definition exception_name: (_) @type.definition) + +[ + (atomic_type) + (simple_type) + (generic_type) + (function_type) + (compound_type) + (postfix_type) + (list_type) + (static_type) + (constrained_type) + (flexible_type) + (byref_type) + (paren_type) + (struct_type) + (nullable_type) +] @type + +(member_signature + . + (identifier) @function.member) + +;; Named arguments of a member, a constructor or a `val`. The `*` between +;; them is coloured by the operator list below. +(curried_spec + (arguments_spec + (argument_spec + (argument_name_spec + "?"? @character.special + name: (_) @variable.parameter)))) + +(union_type_case (identifier) @constant) + +(wildcard_pattern) @character.special + +(identifier_pattern + . + (_) @constant + . + (_) @variable) + +(optional_pattern + "?" @character.special) + +(import_decl . (_) @module) +(named_module + name: (_) @module) +(namespace + name: (_) @module) +;; The name is the identifier child, not the first child: a nested module may +;; carry attributes (`[] module Inner = ...`). +(module_defn + (identifier) @module) + +(record_fields + (record_field + . + (identifier) @property)) + +(value_declaration_left . (_) @variable) + +(typed_pattern + . (_) @variable.parameter) + +[ + (xint) + (int) + (int16) + (uint16) + (int32) + (uint32) + (int64) + (uint64) + (nativeint) + (unativeint) +] @number + +[ + (ieee32) + (ieee64) + (float) + (decimal) +] @number.float + +(bool) @boolean + +([ + (string) + (triple_quoted_string) + (verbatim_string) + (char) + (format_string) + (format_triple_quoted_string) +] @spell @string) + +(compiler_directive_decl) @keyword.directive + +(preproc_line + "#line" @keyword.directive) + +(attribute + target: (identifier)? @keyword + (simple_type) @attribute) + +[ + "(" + ")" + "{" + "}" + "[" + "]" + "[|" + "|]" + "{|" + "|}" +] @punctuation.bracket + +[ + "[<" + ">]" +] @punctuation.special + +[ + "," + ":" + "." +] @punctuation.delimiter + +[ + "|" + "=" + "->" + "*" + (op_identifier) +] @operator + +(generic_type + [ + "<" + ">" + ] @punctuation.bracket) + +[ + "when" + "then" +] @keyword.conditional + +[ + "and" + "or" + "not" +] @keyword.operator + +[ + "open" +] @keyword.import + +[ + "abstract" + "delegate" + "static" + "inline" + "mutable" + "override" + "rec" + "global" + (access_modifier) +] @keyword.modifier + +[ + "member" +] @keyword.function + +[ + "enum" + "type" + "exception" + "inherit" + "interface" + "and" + "class" + "struct" +] @keyword.type + +[ + "as" + "begin" + "end" + "default" + "get" + "set" + "new" + "of" + "struct" + "val" + "module" + "namespace" + "with" +] @keyword + +[ + "null" +] @constant.builtin + + +(preproc_if + [ + "#if" @keyword.directive + "#endif" @keyword.directive + ] + condition: (_)? @keyword.directive) + +(preproc_else + "#else" @keyword.directive) + +(preproc_inactive) @comment + +((long_identifier + (identifier)+ @variable.member + . + (identifier))) + +;; Every segment of a module path (`namespace Company.Product`, +;; `open System.IO`), a type path or an attribute path is part of that name, +;; not a member access; re-capture the segments the rule above marked as +;; members (the last capture of a node wins). @type.builtin follows so it +;; still wins over the plain @type. +(namespace name: (long_identifier (identifier) @module)) +(named_module name: (long_identifier (identifier) @module)) +(import_decl (long_identifier (identifier) @module)) +(module_abbrev (long_identifier (identifier) @module)) +(simple_type (long_identifier (identifier) @type)) +;; Exception abbreviation: `exception E = Other.Exn`. +(exception_definition "=" (long_identifier (identifier) @type)) +(attribute (simple_type (long_identifier (identifier) @attribute))) + +((simple_type + (long_identifier + (identifier) @type.builtin)) + (#any-of? @type.builtin "bool" "byte" "sbyte" "int16" "uint16" "int" "uint" "int64" "uint64" "nativeint" "unativeint" "decimal" "float" "double" "float32" "single" "char" "string" "unit")) + +((identifier) @module.builtin + (#any-of? @module.builtin "Array" "Async" "Directory" "File" "List" "Option" "Path" "Map" "Set" "Lazy" "Seq" "Task" "String" "Result" )) diff --git a/crates/ide-language/queries/fsharp_signature/outline.scm b/crates/ide-language/queries/fsharp_signature/outline.scm new file mode 100644 index 0000000000..56f552cbcd --- /dev/null +++ b/crates/ide-language/queries/fsharp_signature/outline.scm @@ -0,0 +1,25 @@ +(namespace name: (_) @name) @def.namespace +(named_module name: (_) @name) @def.module +(module_defn . (identifier) @name) @def.module +(module_defn (access_modifier) . (identifier) @name) @def.module + +(record_type_defn (type_name type_name: (_) @name)) @def.struct +(union_type_defn (type_name type_name: (_) @name)) @def.enum +(enum_type_defn (type_name type_name: (_) @name)) @def.enum +(interface_type_defn (type_name type_name: (_) @name)) @def.interface +(anon_type_defn (type_name type_name: (_) @name)) @def.class +(type_abbrev_defn (type_name type_name: (_) @name)) @def.type +(delegate_type_defn (type_name type_name: (_) @name)) @def.type +(type_declaration (type_name type_name: (_) @name)) @def.type +(exception_definition exception_name: (_) @name) @def.class + +(member_defn "new" @name (curried_spec)) @def.constructor + +(union_type_case (identifier) @name) @def.enum_member +(enum_type_case . (identifier) @name) @def.enum_member +(record_field (identifier) @name) @def.field + +(value_definition (value_declaration_left (identifier_pattern . (long_identifier_or_op) @name)) (curried_spec (arguments_spec))) @def.function +(value_definition (value_declaration_left (identifier_pattern . (long_identifier_or_op) @name))) @def.variable +(member_defn (member_signature . (identifier) @name (curried_spec (arguments_spec)))) @def.method +(member_defn (member_signature . (identifier) @name)) @def.property diff --git a/crates/ide-language/src/registry.rs b/crates/ide-language/src/registry.rs index ac1d8fbb09..a93f5a4699 100644 --- a/crates/ide-language/src/registry.rs +++ b/crates/ide-language/src/registry.rs @@ -32,6 +32,7 @@ const BUILTIN: &[(&str, &str)] = &[ ("erlang", include_str!("../../../languages/erlang.toml")), ("freemarker", include_str!("../../../languages/freemarker.toml")), ("fsharp", include_str!("../../../languages/fsharp.toml")), + ("fsharp-signature", include_str!("../../../languages/fsharp-signature.toml")), ("gitattributes", include_str!("../../../languages/gitattributes.toml")), ("gdscript", include_str!("../../../languages/gdscript.toml")), ("gdshader", include_str!("../../../languages/gdshader.toml")), @@ -1479,6 +1480,9 @@ mod tests { ("Main.hs", "haskell"), ("a.ml", "ocaml"), ("a.mli", "ocaml.interface"), + ("Program.fs", "fsharp"), + ("build.fsx", "fsharp"), + ("Library.fsi", "fsharp.signature"), ("analysis.R", "r"), ("a.jl", "julia"), ("deploy.sh", "shellscript"), diff --git a/crates/ide-language/src/syntax/grammars.rs b/crates/ide-language/src/syntax/grammars.rs index ecab0b5302..24da8d82e2 100644 --- a/crates/ide-language/src/syntax/grammars.rs +++ b/crates/ide-language/src/syntax/grammars.rs @@ -328,6 +328,40 @@ pub(crate) static SPECS: &[Spec] = &[ imports: &["open_module"], constructors: NONE, }, + Spec { + name: "fsharp", + language: tree_sitter_fsharp::LANGUAGE_FSHARP, + outline: outline!("fsharp"), + highlights: Some(Highlights { query: tree_sitter_fsharp::HIGHLIGHTS_QUERY, first_wins: false }), + // Layout blocks have no brackets: fold the declarations and multi-line expressions. + fold_nodes: &[ + "module_defn", + "type_definition", + "function_or_value_defn", + "member_defn", + "interface_implementation", + "ce_expression", + "match_expression", + "if_expression", + "for_expression", + "while_expression", + "try_expression", + "fun_expression", + ], + fold_bodies: NONE, + imports: &["import_decl"], + constructors: NONE, + }, + Spec { + name: "fsharp_signature", + language: tree_sitter_fsharp::LANGUAGE_SIGNATURE, + outline: outline!("fsharp_signature"), + highlights: Some(Highlights { query: highlights!("fsharp_signature"), first_wins: false }), + fold_nodes: &["module_defn", "type_definition", "value_definition"], + fold_bodies: NONE, + imports: &["import_decl"], + constructors: NONE, + }, Spec { name: "bash", language: tree_sitter_bash::LANGUAGE, diff --git a/crates/ide-language/src/syntax/outline.rs b/crates/ide-language/src/syntax/outline.rs index ec79ad2146..e6fe49b02e 100644 --- a/crates/ide-language/src/syntax/outline.rs +++ b/crates/ide-language/src/syntax/outline.rs @@ -618,6 +618,8 @@ fn name_text(n: &Node, text: &str) -> String { } else { t }; + // F# quoted identifiers: ``has spaces`` -> `has spaces`. + let t = t.strip_prefix("``").and_then(|t| t.strip_suffix("``")).unwrap_or(t); clean(t, 120) } diff --git a/crates/ide-language/src/syntax/tests.rs b/crates/ide-language/src/syntax/tests.rs index 971e3a97b8..3f3e8a0ff7 100644 --- a/crates/ide-language/src/syntax/tests.rs +++ b/crates/ide-language/src/syntax/tests.rs @@ -2172,3 +2172,257 @@ fn merge_impl_traits_marks_server_impls_by_their_self_type() { assert_eq!(lsp[0].self_type, ts_impl.self_type); assert_eq!(lsp[0].self_type.unwrap().start, Pos::new(2, 4)); } + +// ---- F# ---- + +const FSHARP: &str = r#"namespace Company.Product + +open System +open System.IO + +module Math = + /// Shapes. + type Shape = + | Circle of radius: float + | Square of float + + type Point = { X: int; Y: int } + + let (|Even|Odd|) n = if n % 2 = 0 then Even else Odd + + let (|Positive|_|) n = if n > 0 then Some n else None + + let add x y = + let sum = x + y + sum + + let fetch url = + async { + let! data = download url + do! Async.Sleep 10 + return! parse data + } + + let squares = + seq { + for i in 1 .. 10 do + yield i * 2 + } + + type Calc(seed: int) = + let mutable total = seed + member this.Add(n) = total <- total + n + member _.Total = total + static member Zero = Calc 0 + interface IDisposable with + member this.Dispose() = () + + type IShape = + abstract Area: unit -> float + + exception Bad of string + + module Inner = + let (+++) a b = a + b + + [] + let Max = 10 +"#; + +#[test] +fn fsharp_outline_follows_namespaces_modules_and_types() { + check_outline( + "fsharp", + FSHARP, + " + Namespace Company.Product + Module Math + Enum Shape + EnumMember Circle + EnumMember Square + Struct Point + Field X + Field Y + Function (|Even|Odd|) + Function (|Positive|_|) + Function add + Function fetch + Variable squares + Class Calc + Variable total + Method Add + Property Total + Property Zero + Method Dispose + Class IShape + Method Area + Class Bad + Module Inner + Function (+++) + Variable Max + ", + ); +} + +#[test] +fn fsharp_outline_of_a_top_level_module_and_other_type_forms() { + check_outline( + "fsharp", + "module Top\n\nlet mutable count = 0\n\ntype Color =\n | Red = 0\n | Green = 1\n\ntype Alias = int list\n\n\ + []\ntype V =\n val X: int\n new(x) = { X = x }\n\ntype Builder() =\n member val Auto = 1 with get, set\n\ + \nand Other = { Z: int }\n\ntype String with\n member this.Shout() = this.ToUpper()\n\nlet main () =\n let local = 1\n local\n", + " + Module Top + Variable count + Enum Color + EnumMember Red + EnumMember Green + TypeAlias Alias + Class V + Field X + Constructor new + Class Builder + Property Auto + Struct Other + Field Z + Namespace String + Method Shout + Function main + ", + ); +} + +const FSHARP_SIGNATURE: &str = r#"namespace Company.Product + +module Math = + /// Adds. + val add: x: int -> y: int -> int + val mutable counter: int + + type Shape = + | Circle of radius: float + | Square of float + + type Point = { X: int; Y: int } + + [] + type Calc = + new: seed: int -> Calc + member Add: int -> int + member Total: int + static member Zero: Calc + + exception Bad of string + + module Inner = + val pi: float +"#; + +#[test] +fn fsharp_signature_files_use_the_signature_grammar() { + check_outline( + "fsharp.signature", + FSHARP_SIGNATURE, + " + Namespace Company.Product + Module Math + Function add + Variable counter + Enum Shape + EnumMember Circle + EnumMember Square + Struct Point + Field X + Field Y + Class Calc + Constructor new + Method Add + Property Total + Property Zero + Class Bad + Module Inner + Variable pi + ", + ); + let g = syntax().grammar(&lang("fsharp.signature")).unwrap(); + assert!(!parse(&g.language, FSHARP_SIGNATURE, None).unwrap().root_node().has_error()); +} + +#[test] +fn fsharp_scripts_with_directives_parse_cleanly() { + let src = "#r \"nuget: Newtonsoft.Json, 13.0.3\"\n#load \"helpers.fsx\"\n#I \"lib\"\n\nopen Newtonsoft.Json\n\n\ + let greet name = printfn \"Hello %s\" name\n\ngreet \"world\"\n"; + let g = syntax().grammar(&lang("fsharp")).unwrap(); + assert!(!parse(&g.language, src, None).unwrap().root_node().has_error()); + check_outline("fsharp", src, "Function greet"); +} + +#[test] +fn fsharp_symbols_carry_their_container() { + let t = tags("fsharp", FSHARP); + assert!(has_tag(&t, "Math", SymbolKind::Module, Some("Company.Product")), "{t:?}"); + assert!(has_tag(&t, "add", SymbolKind::Function, Some("Math")), "{t:?}"); + assert!(has_tag(&t, "(|Even|Odd|)", SymbolKind::Function, Some("Math")), "{t:?}"); + assert!(has_tag(&t, "Add", SymbolKind::Method, Some("Calc")), "{t:?}"); + assert!(has_tag(&t, "Circle", SymbolKind::EnumMember, Some("Shape")), "{t:?}"); + // Locals are not symbols. + assert!(!t.iter().any(|(n, ..)| n == "sum" || n == "data"), "{t:?}"); + let t = tags("fsharp.signature", FSHARP_SIGNATURE); + assert!(has_tag(&t, "add", SymbolKind::Function, Some("Math")), "{t:?}"); +} + +#[test] +fn fsharp_folds_layout_blocks_computation_expressions_and_comments() { + let src = "open System\nopen System.IO\n\n(*\n header\n*)\nmodule M =\n type R =\n { X: int\n Y: int }\n\n \ + let fetch url =\n async {\n let! d = download url\n return d\n }\n\n \ + let pick x =\n match x with\n | 1 -> \"a\"\n | _ -> \"b\"\n"; + let f = folds("fsharp", src); + assert!(f.contains(&(0, 1, FoldKind::Imports)), "{f:?}"); + assert!(f.contains(&(3, 5, FoldKind::Comment)), "{f:?}"); + for start in [6, 7, 11, 12, 17, 18] { + assert!(f.iter().any(|(s, ..)| *s == start), "no fold at line {start}: {f:?}"); + } + let f = folds("fsharp.signature", FSHARP_SIGNATURE); + for start in [2, 7, 13] { + assert!(f.iter().any(|(s, ..)| *s == start), "no fold at line {start}: {f:?}"); + } +} + +#[test] +fn fsharp_highlights_declarations_in_sources_and_signatures() { + for (id, src) in [("fsharp", FSHARP), ("fsharp.signature", FSHARP_SIGNATURE)] { + let h = syntax().highlights(&lang(id), src).unwrap_or_else(|| panic!("no highlights for {id}")); + assert!(!h.data.is_empty(), "{id}"); + } +} + +#[test] +fn fsharp_incomplete_and_unicode_code_stays_usable() { + // While typing: an unfinished binding must not lose the declarations before it. + let outline = render(&syntax().outline(&lang("fsharp"), "module M\n\nlet done_ x = x\n\nlet unfinished =\n")); + assert!(outline.contains("Function done_"), "{outline}"); + // UTF-16 columns after a surrogate pair, CRLF line endings, backticked names. + let items = + syntax().outline(&lang("fsharp"), "module M\r\n\r\nlet (* 😀 *) after x = x\r\nlet ``has spaces`` () = 1\r\n"); + let module = &items[0]; + assert_eq!(module.children[0].name, "after"); + assert_eq!(module.children[0].selection_range.start, Pos::new(2, 13)); + assert_eq!(module.children[1].name, "has spaces"); +} + +#[test] +fn fsharp_large_file_stays_responsive() { + let mut src = String::from("module Big\n\n"); + for i in 0..4000 { + src.push_str(&format!("let f{i} x =\n match x with\n | 0 -> {i}\n | n -> n + 1\n\n")); + } + let started = std::time::Instant::now(); + let outline = syntax().outline(&lang("fsharp"), &src); + let folds = folds("fsharp", &src); + let elapsed = started.elapsed(); + assert_eq!(outline[0].children.len(), 4000); + assert!(folds.len() >= 4000); + println!("fsharp large file: {} bytes, outline + folding in {elapsed:?}", src.len()); + // Debug builds on a loaded CI machine; the point is that it is not quadratic. + assert!(elapsed < std::time::Duration::from_secs(20), "{elapsed:?}"); +} diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index cecf213632..ee8e80b901 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -5194,3 +5194,27 @@ mod external_go_routing_tests { assert_eq!(manager.servers.lock().len(), 2); } } + +#[cfg(test)] +mod fsharp_signature_routing_tests { + use super::*; + + // `.fsi` files are their own language (own grammar) but belong to the same F# server. + #[tokio::test] + async fn signature_files_share_the_source_server_and_are_opened_as_fsharp() { + let workspace = tempfile::tempdir().unwrap(); + let languages = Arc::new(LanguageRegistry::load(None).unwrap()); + let manager = LspManager::new(workspace.path().to_owned(), languages, Arc::new(|_: ide_core::IdeEvent| {})); + let route = |id: &str, file: &str| { + let language = LanguageId::new(id); + let config = manager.languages.get(&language).unwrap(); + manager.server_for(&config.language_servers[0], &language, &workspace.path().join(file)) + }; + + let source = route("fsharp", "Library.fs"); + let signature = route("fsharp.signature", "Library.fsi"); + + assert_eq!(source.id, signature.id); + assert_eq!(manager.languages.server_language_id(&LanguageId::new("fsharp.signature"), &source.name), "fsharp"); + } +} diff --git a/docs/en/languages/adding.mdx b/docs/en/languages/adding.mdx index 7eb266015f..efb00c53a6 100644 --- a/docs/en/languages/adding.mdx +++ b/docs/en/languages/adding.mdx @@ -68,7 +68,7 @@ All keys are kebab-case. Only `id` and `name` are required; a definition with no | `scratch-template` | string | Content of a new scratch file of this language. `$END$` marks where the caret goes. | | `rainbow-brackets` | table | Syntax nodes whose angle brackets rainbow brackets colour; see below. | -Bundled tree-sitter grammars: `bash`, `c`, `cmake`, `cpp`, `csharp`, `css`, `dart`, `elixir`, `gdscript`, `go`, `graphql`, `haskell`, `hcl`, `html`, `java`, `javascript`, `json`, `kotlin`, `lua`, `make`, `markdown`, `nix`, `ocaml`, `ocaml_interface`, `php`, `prisma`, `proto`, `python`, `ruby`, `rust`, `scala`, `swift`, `toml`, `tsx`, `typescript`, `xml`, `yaml`, `zig`. A new grammar has to be compiled into the IDE; a plugin can provide highlighting and structure for a language without a grammar instead (see [Language features](/en/plugins/guides/language-features)). +Bundled tree-sitter grammars: `bash`, `c`, `cmake`, `cpp`, `csharp`, `css`, `dart`, `elixir`, `fsharp`, `fsharp_signature`, `gdscript`, `go`, `graphql`, `haskell`, `hcl`, `html`, `java`, `javascript`, `json`, `kotlin`, `lua`, `make`, `markdown`, `nix`, `ocaml`, `ocaml_interface`, `php`, `prisma`, `proto`, `python`, `ruby`, `rust`, `scala`, `swift`, `toml`, `tsx`, `typescript`, `xml`, `yaml`, `zig`. A new grammar has to be compiled into the IDE; a plugin can provide highlighting and structure for a language without a grammar instead (see [Language features](/en/plugins/guides/language-features)). ### `[[framework-ui-modes]]` diff --git a/docs/en/languages/csharp.mdx b/docs/en/languages/csharp.mdx index a04ffa32ee..4853a462f0 100644 --- a/docs/en/languages/csharp.mdx +++ b/docs/en/languages/csharp.mdx @@ -12,6 +12,8 @@ OpenIDEA supports C# (`.cs`, `.csx`) through Microsoft's [Roslyn language server | C# | roslyn-language-server or csharp-ls | `*.sln`, `*.slnx`, `*.csproj`, `global.json`, `Directory.Build.props`, `ProjectSettings/ProjectVersion.txt` | | F# | fsautocomplete | `*.sln`, `*.fsproj`, `global.json` | +Highlighting, folding, the outline and project symbols for F# work without a language server. Source files and scripts (`.fs`, `.fsx`) and signature files (`.fsi`, the language **F# Signature**) have their own grammars and share one FsAutoComplete. An interface written without `interface … end` is listed as a class in the outline. + For C#, the IDE uses the Roslyn language server when it is installed and csharp-ls otherwise. Roslyn is the server of the VS Code C# extension. It needs the .NET 10 SDK or newer; csharp-ls also runs on older SDKs. With Roslyn, completion also lists types from namespaces the file doesn't import yet (shown with their namespace), and accepting one adds the `using` directive. Roslyn starts with `--autoLoadProjects`, so it finds and opens the solution or projects itself. On macOS and Linux it loads SDK-style projects only: .NET Framework projects need Mono MSBuild, which it doesn't use. Unity's Visual Studio Editor package generates SDK-style `.csproj` files. With Roslyn, the editor shows inlay hints: parameter names before literals, `new` objects and indexer arguments (not before variables or other expressions, and not where the method or argument name already says it), and the types of `var` and lambda parameters. Turn them off in **Settings › Editor › Inlay Hints** (types, parameter names, or C# altogether). The server's own options win over these defaults: set them in **Settings › Languages & Frameworks › Language Servers** › Roslyn (C#) › settings, for example `{"csharp|inlay_hints": {"dotnet_enable_inlay_hints_for_other_parameters": true}}`. csharp-ls sends its own inlay hints. Parameter info opens after `(` and `,` and with ⌘P / Ctrl+P, with the current parameter in bold. diff --git a/docs/en/languages/index.mdx b/docs/en/languages/index.mdx index dcc29defb3..87a1b74dab 100644 --- a/docs/en/languages/index.mdx +++ b/docs/en/languages/index.mdx @@ -113,7 +113,8 @@ The table lists every built-in language definition. Server and debugger names in | Elixir | `elixir` | `.ex`, `.exs` | Yes | Yes | **elixir-ls** | **elixir-ls-debugger** | | ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | Yes | — | — | — | | Erlang | `erlang` | `.erl`, `.hrl`, `.escript`, `.app.src` | Yes | — | elp | — | -| F# | `fsharp` | `.fs`, `.fsi`, `.fsx` | Yes | — | **fsautocomplete** | **netcoredbg** | +| F# | `fsharp` | `.fs`, `.fsx` | Yes | Yes | **fsautocomplete** | **netcoredbg** | +| F# Signature | `fsharp.signature` | `.fsi` | Yes | Yes | **fsautocomplete** | — | | FreeMarker | `freemarker` | `.ftl`, `.ftlh`, `.ftlx` | Yes | — | — | — | | GDScript | `gdscript` | `.gd` | Yes | Yes | godot | godot | | Git Attributes | `gitattributes` | `.gitattributes` | — | — | — | — | diff --git a/docs/zh/languages/adding.mdx b/docs/zh/languages/adding.mdx index 700a0073a9..6b2e0a9e82 100644 --- a/docs/zh/languages/adding.mdx +++ b/docs/zh/languages/adding.mdx @@ -68,7 +68,7 @@ install-hint = "Install CodeLLDB in Settings › Languages & Frameworks › Lang | `scratch-template` | 字符串 | 新建该语言草稿文件时的内容,`$END$` 表示光标位置。 | | `rainbow-brackets` | 表 | 彩虹括号为其尖括号着色的语法节点,见下文。 | -内置的 tree-sitter 语法:`bash`、`c`、`cmake`、`cpp`、`csharp`、`css`、`dart`、`elixir`、`gdscript`、`go`、`graphql`、`haskell`、`hcl`、`html`、`java`、`javascript`、`json`、`kotlin`、`lua`、`make`、`markdown`、`nix`、`ocaml`、`ocaml_interface`、`php`、`prisma`、`proto`、`python`、`ruby`、`rust`、`scala`、`swift`、`toml`、`tsx`、`typescript`、`xml`、`yaml`、`zig`。新的语法需要编译进 IDE;没有语法的语言可以改由插件提供高亮和结构(见 [语言功能](/zh/plugins/guides/language-features))。 +内置的 tree-sitter 语法:`bash`、`c`、`cmake`、`cpp`、`csharp`、`css`、`dart`、`elixir`、`fsharp`、`fsharp_signature`、`gdscript`、`go`、`graphql`、`haskell`、`hcl`、`html`、`java`、`javascript`、`json`、`kotlin`、`lua`、`make`、`markdown`、`nix`、`ocaml`、`ocaml_interface`、`php`、`prisma`、`proto`、`python`、`ruby`、`rust`、`scala`、`swift`、`toml`、`tsx`、`typescript`、`xml`、`yaml`、`zig`。新的语法需要编译进 IDE;没有语法的语言可以改由插件提供高亮和结构(见 [语言功能](/zh/plugins/guides/language-features))。 ### `[[framework-ui-modes]]` diff --git a/docs/zh/languages/csharp.mdx b/docs/zh/languages/csharp.mdx index 4f8c6bd04c..669e9886db 100644 --- a/docs/zh/languages/csharp.mdx +++ b/docs/zh/languages/csharp.mdx @@ -12,6 +12,8 @@ OpenIDEA 通过微软的 [Roslyn 语言服务器](https://github.com/dotnet/rosl | C# | roslyn-language-server 或 csharp-ls | `*.sln`、`*.slnx`、`*.csproj`、`global.json`、`Directory.Build.props`、`ProjectSettings/ProjectVersion.txt` | | F# | fsautocomplete | `*.sln`、`*.fsproj`、`global.json` | +F# 的语法高亮、折叠、结构视图和项目符号无需语言服务器即可使用。源文件和脚本(`.fs`、`.fsx`)与签名文件(`.fsi`,语言名 **F# Signature**)使用各自的语法,并共用一个 FsAutoComplete。没有写 `interface … end` 的接口在结构视图中显示为类。 + C# 在装了 Roslyn 语言服务器时用它,否则用 csharp-ls。Roslyn 是 VS Code C# 扩展使用的服务器,需要 .NET 10 或更新的 SDK;csharp-ls 在较旧的 SDK 上也能运行。用 Roslyn 时,补全还会列出当前文件尚未导入的命名空间里的类型(附带命名空间),选中后自动加上 `using` 指令。Roslyn 以 `--autoLoadProjects` 启动,会自己找到并打开解决方案或项目。在 macOS 和 Linux 上它只加载 SDK 风格的项目:.NET Framework 项目需要 Mono MSBuild,它不使用。Unity 的 Visual Studio Editor 包生成的就是 SDK 风格的 `.csproj`。 使用 Roslyn 时,编辑器显示内联提示:字面量、`new` 对象和索引器实参前的参数名(变量和其他表达式前不显示,方法名或实参名已经说明含义时也不显示),以及 `var` 和 lambda 参数的类型。可在 **Settings › Editor › Inlay Hints** 中关闭(类型、参数名,或整个 C#)。服务器自身的选项优先于这些默认值:在 **Settings › Languages & Frameworks › Language Servers** › Roslyn (C#) › settings 中设置,例如 `{"csharp|inlay_hints": {"dotnet_enable_inlay_hints_for_other_parameters": true}}`。csharp-ls 发送它自己的内联提示。输入 `(` 和 `,` 之后或按 ⌘P / Ctrl+P 会弹出参数信息,当前参数以粗体显示。 diff --git a/docs/zh/languages/index.mdx b/docs/zh/languages/index.mdx index 81113e5fb5..102c4af847 100644 --- a/docs/zh/languages/index.mdx +++ b/docs/zh/languages/index.mdx @@ -108,7 +108,8 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自 | Elixir | `elixir` | `.ex`, `.exs` | 是 | 是 | **elixir-ls** | **elixir-ls-debugger** | | ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | 是 | — | — | — | | Erlang | `erlang` | `.erl`, `.hrl`, `.escript`, `.app.src` | 是 | — | elp | — | -| F# | `fsharp` | `.fs`, `.fsi`, `.fsx` | 是 | — | **fsautocomplete** | **netcoredbg** | +| F# | `fsharp` | `.fs`, `.fsx` | 是 | 是 | **fsautocomplete** | **netcoredbg** | +| F# Signature | `fsharp.signature` | `.fsi` | 是 | 是 | **fsautocomplete** | — | | FreeMarker | `freemarker` | `.ftl`, `.ftlh`, `.ftlx` | 是 | — | — | — | | GDScript | `gdscript` | `.gd` | 是 | 是 | godot | godot | | Git Attributes | `gitattributes` | `.gitattributes` | — | — | — | — | diff --git a/languages/fsharp-signature.toml b/languages/fsharp-signature.toml new file mode 100644 index 0000000000..eea80583fb --- /dev/null +++ b/languages/fsharp-signature.toml @@ -0,0 +1,17 @@ +id = "fsharp.signature" +name = "F# Signature" +extensions = ["fsi"] +line-comment = "//" +block-comment = ["(*", "*)"] +indent = { tab-size = 4, insert-spaces = true } +ui-mode = "F#" +# Signature files have their own grammar. +tree-sitter = "fsharp_signature" + +[[language-servers]] +name = "fsautocomplete" +command = "fsautocomplete" +root-markers = ["*.sln", "*.fsproj", "global.json"] +install-hint = "dotnet tool install --global fsautocomplete" +language-id = "fsharp" +initialization-options = { AutomaticWorkspaceInit = true } diff --git a/languages/fsharp.toml b/languages/fsharp.toml index d9c80d9979..89d07b13e3 100644 --- a/languages/fsharp.toml +++ b/languages/fsharp.toml @@ -1,10 +1,11 @@ id = "fsharp" name = "F#" -extensions = ["fs", "fsi", "fsx"] +extensions = ["fs", "fsx"] line-comment = "//" block-comment = ["(*", "*)"] indent = { tab-size = 4, insert-spaces = true } ui-mode = "F#" +tree-sitter = "fsharp" [[language-servers]] name = "fsautocomplete" diff --git a/src/editor/core/cm/comments.ts b/src/editor/core/cm/comments.ts index df0fd06764..3dac5b40ff 100644 --- a/src/editor/core/cm/comments.ts +++ b/src/editor/core/cm/comments.ts @@ -505,7 +505,7 @@ function lineCommentStart(state: EditorState, pos: number, token: string): numbe * new line that continues the comment (with the comment's own spacing). */ /** Languages whose `///` (and Rust's `//!`) line comments are documentation. */ -const DOC_LINE_COMMENT_LANGS = new Set(["rust", "csharp", "dart", "swift", "fsharp"]); +const DOC_LINE_COMMENT_LANGS = new Set(["rust", "csharp", "dart", "swift", "fsharp", "fsharp.signature"]); /** * Enter at the end of a `///` / `//!` documentation line continues the documentation on the diff --git a/src/editor/core/cm/editing.ts b/src/editor/core/cm/editing.ts index 76bcc51e1f..0f08d6c60c 100644 --- a/src/editor/core/cm/editing.ts +++ b/src/editor/core/cm/editing.ts @@ -673,6 +673,7 @@ export const KEYWORD_BLOCK_LANGS = new Set([ "julia", "erlang", "fsharp", + "fsharp.signature", "ocaml", "ocaml.interface", "yaml", diff --git a/src/editor/core/model/document.ts b/src/editor/core/model/document.ts index 3ae947e4b9..9823dfe00d 100644 --- a/src/editor/core/model/document.ts +++ b/src/editor/core/model/document.ts @@ -148,9 +148,10 @@ export const useOutline = create>(() => ({})); const REFRESH_DELAY = 450; /** * Languages whose stream mode works from word lists, so the grammar's highlights are drawn - * over it: Kotlin declaration roles, Shell commands, function names and `local`. + * over it: Kotlin declaration roles, Shell commands, function names and `local`, F# + * functions, types and members. */ -const GRAMMAR_SUPPLEMENTED = new Set(["kotlin", "shellscript"]); +const GRAMMAR_SUPPLEMENTED = new Set(["kotlin", "shellscript", "fsharp", "fsharp.signature"]); function bannerFor(info: DocumentInfo): Banner { // Virtual documents (library classes) get their own notice from the editor area. if (info.uri) return null;