From e4d65418fc011a9586d664b0cfe1009d1c4ca51d Mon Sep 17 00:00:00 2001 From: davidanthoff Date: Sun, 20 Mar 2022 03:40:57 +0000 Subject: [PATCH] Format files using DocumentFormat --- docs/make.jl | 6 +-- src/document.jl | 24 +++++------ src/extensions/messagedefs.jl | 2 +- src/languageserverinstance.jl | 16 ++++---- src/multienv.jl | 8 ++-- src/protocol/basic.jl | 24 +++++------ src/protocol/completion.jl | 60 +++++++++++++-------------- src/protocol/configuration.jl | 12 +++--- src/protocol/document.jl | 8 ++-- src/protocol/features.jl | 22 +++++----- src/protocol/goto.jl | 2 +- src/protocol/highlight.jl | 8 ++-- src/protocol/initialize.jl | 43 ++++++++++---------- src/protocol/messagedefs.jl | 30 +++++++------- src/protocol/signature.jl | 6 +-- src/protocol/symbols.jl | 52 ++++++++++++------------ src/requests/actions.jl | 42 +++++++++---------- src/requests/completions.jl | 48 +++++++++++----------- src/requests/features.jl | 36 ++++++++--------- src/requests/hover.jl | 2 +- src/requests/init.jl | 76 +++++++++++++++++------------------ src/requests/misc.jl | 11 ++--- src/requests/signatures.jl | 2 +- src/requests/textdocument.jl | 37 +++++++++-------- src/runserver.jl | 8 ++-- src/utilities.jl | 36 ++++++++--------- test/requests/actions.jl | 16 ++++---- test/requests/completions.jl | 3 +- test/requests/misc.jl | 3 +- test/runtests.jl | 6 +-- test/test_document.jl | 6 +-- test/test_intellisense.jl | 2 +- 32 files changed, 325 insertions(+), 332 deletions(-) diff --git a/docs/make.jl b/docs/make.jl index 0d0d456b2..39c20b725 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -7,16 +7,16 @@ makedocs(; repo="https://github.com/julia-vscode/LanguageServer.jl/blob/{commit}{path}#L{line}", sitename="LanguageServer.jl", format=Documenter.HTML(; - prettyurls=prettyurls = get(ENV, "CI", nothing) == "true", + prettyurls=prettyurls = get(ENV, "CI", nothing) == "true" # canonical="https://www.julia-vscode.org/LanguageServer.jl", # assets=String[], ), pages=[ "Home" => "index.md", "Syntax Reference" => "syntax.md", - ], + ] ) deploydocs(; - repo="github.com/julia-vscode/LanguageServer.jl", + repo="github.com/julia-vscode/LanguageServer.jl" ) diff --git a/src/document.jl b/src/document.jl index fd7fd78c7..121d36e1c 100644 --- a/src/document.jl +++ b/src/document.jl @@ -77,7 +77,7 @@ function get_offset(doc::Document, line::Integer, character::Integer) line_offsets = get_line_offsets(doc) io = IOBuffer(get_text(doc)) try - seek(io, line_offsets[line + 1]) + seek(io, line_offsets[line+1]) while character > 0 c = read(io, Char) character -= 1 @@ -102,7 +102,7 @@ get_offset(doc, p::Position) = get_offset(doc, p.line, p.character) get_offset(doc, r::Range) = get_offset(doc, r.start):get_offset(doc, r.stop) # 1-based. Basically the index at which (line, character) can be found in the document. -get_offset2(doc::Document, p::Position, forgiving_mode=false) = get_offset2(doc, p.line, p.character, forgiving_mode) +get_offset2(doc::Document, p::Position, forgiving_mode=false) = get_offset2(doc, p.line, p.character, forgiving_mode) function get_offset2(doc::Document, line::Integer, character::Integer, forgiving_mode=false) line_offsets = get_line_offsets2!(doc) text = get_text(doc) @@ -114,9 +114,9 @@ function get_offset2(doc::Document, line::Integer, character::Integer, forgiving throw(LSOffsetError("get_offset2 crashed. More diagnostics:\nline=$line\nline_offsets='$line_offsets'")) end - line_offset = line_offsets[line + 1] + line_offset = line_offsets[line+1] - next_line_offset = line + 1 < length(line_offsets) ? line_offsets[line + 2] : nextind(text, lastindex(text)) + next_line_offset = line + 1 < length(line_offsets) ? line_offsets[line+2] : nextind(text, lastindex(text)) pos = line_offset @@ -177,16 +177,16 @@ function get_line_offsets(doc::Document, force=false) doc._line_offsets = Int[0] text = get_text(doc) ind = firstindex(text) - while ind <= lastindex(text) + while ind <= lastindex(text) c = text[ind] nl = c == '\n' || c == '\r' - if c == '\r' && ind + 1 <= lastindex(text) && text[ind + 1] == '\n' + if c == '\r' && ind + 1 <= lastindex(text) && text[ind+1] == '\n' ind += 1 end nl && push!(doc._line_offsets, ind) ind = nextind(text, ind) end -end + end return doc._line_offsets end @@ -195,10 +195,10 @@ function get_line_offsets2!(doc::Document, force=false) doc._line_offsets2 = Int[1] text = get_text(doc) ind = firstindex(text) - while ind <= lastindex(text) + while ind <= lastindex(text) c = text[ind] if c == '\n' || c == '\r' - if c == '\r' && ind + 1 <= lastindex(text) && text[ind + 1] == '\n' + if c == '\r' && ind + 1 <= lastindex(text) && text[ind+1] == '\n' ind += 1 end push!(doc._line_offsets2, ind + 1) @@ -218,12 +218,12 @@ function get_line_of(line_offsets::Vector{Int}, offset::Integer) else line = 1 while line < nlines - if line_offsets[line] <= offset < line_offsets[line + 1] + if line_offsets[line] <= offset < line_offsets[line+1] break end line += 1 end -end + end return line, line_offsets[line] end @@ -244,7 +244,7 @@ function get_position_at(doc::Document, offset::Integer) c = read(io, Char) character += 1 if UInt32(c) >= 0x010000 - character += 1 + character += 1 end end close(io) diff --git a/src/extensions/messagedefs.jl b/src/extensions/messagedefs.jl index dd8bca291..212dd7a0d 100644 --- a/src/extensions/messagedefs.jl +++ b/src/extensions/messagedefs.jl @@ -1,4 +1,4 @@ const julia_getModuleAt_request_type = JSONRPC.RequestType("julia/getModuleAt", VersionedTextDocumentPositionParams, String) -const julia_getCurrentBlockRange_request_type = JSONRPC.RequestType("julia/getCurrentBlockRange", VersionedTextDocumentPositionParams, Tuple{Position, Position, Position}) +const julia_getCurrentBlockRange_request_type = JSONRPC.RequestType("julia/getCurrentBlockRange", VersionedTextDocumentPositionParams, Tuple{Position,Position,Position}) const julia_getDocAt_request_type = JSONRPC.RequestType("julia/getDocAt", VersionedTextDocumentPositionParams, String) const julia_getDocFromWord_request_type = JSONRPC.RequestType("julia/getDocFromWord", NamedTuple{(:word,),Tuple{String}}, String) diff --git a/src/languageserverinstance.jl b/src/languageserverinstance.jl index 09f09e83e..d5f7971b7 100644 --- a/src/languageserverinstance.jl +++ b/src/languageserverinstance.jl @@ -63,14 +63,14 @@ mutable struct LanguageServerInstance shutdown_requested::Bool - function LanguageServerInstance(pipe_in, pipe_out, env_path="", depot_path="", err_handler=nothing, symserver_store_path=nothing, download=true, symbolcache_upstream = nothing) + function LanguageServerInstance(pipe_in, pipe_out, env_path="", depot_path="", err_handler=nothing, symserver_store_path=nothing, download=true, symbolcache_upstream=nothing) new( JSONRPC.JSONRPCEndpoint(pipe_in, pipe_out, err_handler), Set{String}(), Dict{URI2,Document}(), env_path, depot_path, - SymbolServer.SymbolServerInstance(depot_path, symserver_store_path; symbolcache_upstream = symbolcache_upstream), + SymbolServer.SymbolServerInstance(depot_path, symserver_store_path; symbolcache_upstream=symbolcache_upstream), Channel(Inf), StaticLint.ExternalEnv(deepcopy(SymbolServer.stdlibs), SymbolServer.collect_extended_methods(SymbolServer.stdlibs), collect(keys(SymbolServer.stdlibs))), Dict(), @@ -179,7 +179,7 @@ function trigger_symbolstore_reload(server::LanguageServerInstance) ssi_ret, payload = SymbolServer.getstore( server.symbol_server, server.env_path, - function (msg, percentage = missing) + function (msg, percentage=missing) if server.clientcapability_window_workdoneprogress && server.current_symserver_progress_token !== nothing msg = ismissing(percentage) ? msg : string(msg, " ($percentage%)") JSONRPC.send( @@ -193,7 +193,7 @@ function trigger_symbolstore_reload(server::LanguageServerInstance) end end, server.err_handler, - download = server.symserver_use_download + download=server.symserver_use_download ) server.number_of_outstanding_symserver_requests -= 1 @@ -269,7 +269,7 @@ function Base.run(server::LanguageServerInstance) @debug "LS: Starting client listener task." while true msg = JSONRPC.get_next_message(server.jr_endpoint) - put!(server.combined_msg_queue, (type = :clientmsg, msg = msg)) + put!(server.combined_msg_queue, (type=:clientmsg, msg=msg)) end catch err bt = catch_backtrace() @@ -282,7 +282,7 @@ function Base.run(server::LanguageServerInstance) end finally if isopen(server.combined_msg_queue) - put!(server.combined_msg_queue, (type = :close,)) + put!(server.combined_msg_queue, (type=:close,)) close(server.combined_msg_queue) end @debug "LS: Client listener task done." @@ -292,7 +292,7 @@ function Base.run(server::LanguageServerInstance) @debug "LS: Starting symbol server listener task." while true msg = take!(server.symbol_results_channel) - put!(server.combined_msg_queue, (type = :symservmsg, msg = msg)) + put!(server.combined_msg_queue, (type=:symservmsg, msg=msg)) end catch err bt = catch_backtrace() @@ -305,7 +305,7 @@ function Base.run(server::LanguageServerInstance) end finally if isopen(server.combined_msg_queue) - put!(server.combined_msg_queue, (type = :close,)) + put!(server.combined_msg_queue, (type=:close,)) close(server.combined_msg_queue) end @debug "LS: Symbol server listener task done." diff --git a/src/multienv.jl b/src/multienv.jl index c49cbef6d..fbc011ba5 100644 --- a/src/multienv.jl +++ b/src/multienv.jl @@ -10,7 +10,7 @@ const project_names = ("JuliaProject.toml", "Project.toml") const manifest_names = ("JuliaManifest.toml", "Manifest.toml") # return nothing or the project file at env -function env_file(env::String, names = project_names)::Union{Nothing,String} +function env_file(env::String, names=project_names)::Union{Nothing,String} if isdir(env) for proj in names project_file = joinpath(env, proj) @@ -49,7 +49,7 @@ function get_env_for_root(doc::Document, server::LanguageServerInstance) (safe_isfile(env_proj_file) && safe_isfile(env_manifest_file)) || return # Find which workspace folder the doc is in. - parent_workspaceFolders = sort(filter(f->startswith(doc._path, f), collect(server.workspaceFolders)), by = length, rev = true) + parent_workspaceFolders = sort(filter(f -> startswith(doc._path, f), collect(server.workspaceFolders)), by=length, rev=true) isempty(parent_workspaceFolders) && return # arbitrarily pick one @@ -94,11 +94,11 @@ function get_env_for_root(doc::Document, server::LanguageServerInstance) msg )) end - @error msg exception=(err, catch_backtrace()) + @error msg exception = (err, catch_backtrace()) end end -function complete_dep_tree(uuid, env_manifest, alldeps = Dict{Base.UUID,Pkg.Types.PackageEntry}()) +function complete_dep_tree(uuid, env_manifest, alldeps=Dict{Base.UUID,Pkg.Types.PackageEntry}()) haskey(alldeps, uuid) && return alldeps alldeps[uuid] = env_manifest[uuid] for dep_uuid in values(alldeps[uuid].deps) diff --git a/src/protocol/basic.jl b/src/protocol/basic.jl index aa7b5fffa..41aaf35ab 100644 --- a/src/protocol/basic.jl +++ b/src/protocol/basic.jl @@ -63,14 +63,14 @@ end ############################################################################## # Diagnostics const DiagnosticSeverity = Int -const DiagnosticSeverities = (Error = 1, - Warning = 2, - Information = 3, - Hint = 4) +const DiagnosticSeverities = (Error=1, + Warning=2, + Information=3, + Hint=4) const DiagnosticTag = Int -const DiagnosticTags = (Unnecessary = 1, - Deprecated = 2) +const DiagnosticTags = (Unnecessary=1, + Deprecated=2) @dict_readable struct DiagnosticRelatedInformation location::Location @@ -104,8 +104,8 @@ end ############################################################################## # Markup const MarkupKind = String -const MarkupKinds = (PlainText = "plaintext", - Markdown = "markdown") +const MarkupKinds = (PlainText="plaintext", + Markdown="markdown") mutable struct MarkupContent kind::MarkupKind @@ -126,10 +126,10 @@ Base.hash(x::MarkedString) = hash(x.value) # for unique ############################################################################## # Window const MessageType = Int -const MessageTypes = (Error = 1, - Warning = 2, - Info = 3, - Log = 4) +const MessageTypes = (Error=1, + Warning=2, + Info=3, + Log=4) struct ShowMessageParams <: Outbound type::MessageType diff --git a/src/protocol/completion.jl b/src/protocol/completion.jl index f60fac806..12dad3bd8 100644 --- a/src/protocol/completion.jl +++ b/src/protocol/completion.jl @@ -1,41 +1,41 @@ const CompletionItemKind = Int -const CompletionItemKinds = (Text = 1, - Method = 2, - Function = 3, - Constructor = 4, - Field = 5, - Variable = 6, - Class = 7, - Interface = 8, - Module = 9, - Property = 10, - Unit = 11, - Value = 12, - Enum = 13, - Keyword = 14, - Snippet = 15, - Color = 16, - File = 17, - Reference = 18, - Folder = 19, - EnumMember = 20, - Constant = 21, - Struct = 22, - Event = 23, - Operator = 24, - TypeParameter = 25) +const CompletionItemKinds = (Text=1, + Method=2, + Function=3, + Constructor=4, + Field=5, + Variable=6, + Class=7, + Interface=8, + Module=9, + Property=10, + Unit=11, + Value=12, + Enum=13, + Keyword=14, + Snippet=15, + Color=16, + File=17, + Reference=18, + Folder=19, + EnumMember=20, + Constant=21, + Struct=22, + Event=23, + Operator=24, + TypeParameter=25) const CompletionItemTag = Int const CompletionItemTags = (Deprecated = 1) const CompletionTriggerKind = Int -const CompletionTriggerKinds = (Invoked = 1, - TriggerCharacter = 2, - TriggerForIncompleteCompletion = 3) +const CompletionTriggerKinds = (Invoked=1, + TriggerCharacter=2, + TriggerForIncompleteCompletion=3) const InsertTextFormat = Int -const InsertTextFormats = (PlainText = 1, - Snippet = 2) +const InsertTextFormats = (PlainText=1, + Snippet=2) @dict_readable struct CompletionTagClientCapabilities valueSet::Vector{CompletionItemTag} diff --git a/src/protocol/configuration.jl b/src/protocol/configuration.jl index 12fa4e264..d0f1e562e 100644 --- a/src/protocol/configuration.jl +++ b/src/protocol/configuration.jl @@ -30,14 +30,14 @@ end ############################################################################## # File watching const FileChangeType = Int -const FileChangeTypes = (Created = 1, - Changed = 2, - Deleted = 3) +const FileChangeTypes = (Created=1, + Changed=2, + Deleted=3) const WatchKind = Int -const WatchKinds = (Create = 1, - Change = 2, - Delete = 4) +const WatchKinds = (Create=1, + Change=2, + Delete=4) @dict_readable struct FileEvent diff --git a/src/protocol/document.jl b/src/protocol/document.jl index ccd3c80a3..0ddb68a21 100644 --- a/src/protocol/document.jl +++ b/src/protocol/document.jl @@ -76,7 +76,7 @@ end textDocument::TextDocumentItem end -@dict_readable struct TextDocumentContentChangeEvent <: Outbound +@dict_readable struct TextDocumentContentChangeEvent <: Outbound range::Union{Range,Missing} rangeLength::Union{Int,Missing} text::String @@ -97,9 +97,9 @@ end end const TextDocumentSaveReason = Int -const TextDocumentSaveReasons = (Manual = 1, - AfterDelay = 2, - FocusOut = 3) +const TextDocumentSaveReasons = (Manual=1, + AfterDelay=2, + FocusOut=3) @dict_readable struct WillSaveTextDocumentParams textDocument::TextDocumentIdentifier diff --git a/src/protocol/features.jl b/src/protocol/features.jl index e2e52daf7..ca29c47ac 100644 --- a/src/protocol/features.jl +++ b/src/protocol/features.jl @@ -11,14 +11,14 @@ import Base.== ############################################################################## # Code Action const CodeActionKind = String -const CodeActionKinds = (Empty = "", - QuickFix = "quickfix", - Refactor = "refactor", - RefactorExtract = "refactor.extract", - RefactorInline = "refactor.inline", - RefactorRewrite = "refactor.rewrite", - Source = "source", - SourceOrganizeImports = "source.organiseImports") +const CodeActionKinds = (Empty="", + QuickFix="quickfix", + Refactor="refactor", + RefactorExtract="refactor.extract", + RefactorInline="refactor.inline", + RefactorRewrite="refactor.rewrite", + Source="source", + SourceOrganizeImports="source.organiseImports") @dict_readable struct CodeActionKindCapabilities valueSet::Vector{CodeActionKind} @@ -209,9 +209,9 @@ end ############################################################################## # Folding const FoldingRangeKind = String -const FoldingRangeKinds = (Comment = "comment", - Imports = "imports", - Region = "region") +const FoldingRangeKinds = (Comment="comment", + Imports="imports", + Region="region") @dict_readable struct FoldingRangeClientCapabilities <: Outbound dynamicRegistration::Union{Bool,Missing} diff --git a/src/protocol/goto.jl b/src/protocol/goto.jl index f043fd15d..3d759dee0 100644 --- a/src/protocol/goto.jl +++ b/src/protocol/goto.jl @@ -117,4 +117,4 @@ end workDoneToken::Union{Int,String,Missing} # ProgressToken partialResultToken::Union{Int,String,Missing} # ProgressToken context::ReferenceContext -end \ No newline at end of file +end diff --git a/src/protocol/highlight.jl b/src/protocol/highlight.jl index ef8e8d2a7..c2fdd396b 100644 --- a/src/protocol/highlight.jl +++ b/src/protocol/highlight.jl @@ -1,7 +1,7 @@ const DocumentHighlightKind = Int -const DocumentHighlightKinds = (Text = 1, - Read = 2, - Write = 3) +const DocumentHighlightKinds = (Text=1, + Read=2, + Write=3) @dict_readable struct DocumentHighlightClientCapabilities <: Outbound dynamicRegistration::Union{Bool,Missing} @@ -26,4 +26,4 @@ end struct DocumentHighlight <: Outbound range::Range kind::Union{DocumentHighlightKind,Missing} -end \ No newline at end of file +end diff --git a/src/protocol/initialize.jl b/src/protocol/initialize.jl index ee73069b3..0ca19ea81 100644 --- a/src/protocol/initialize.jl +++ b/src/protocol/initialize.jl @@ -1,15 +1,15 @@ ############################################################################## # From client const FailureHandlingKind = String -const FailureHandlingKinds = (Abort = "abort", - Transactional = "transactional", - TextOnlyTransactional = "textOnlyTransactional", - Undo = "undo") +const FailureHandlingKinds = (Abort="abort", + Transactional="transactional", + TextOnlyTransactional="textOnlyTransactional", + Undo="undo") const ResourceOperationKind = String -const ResourceOperationKinds = (Create = "create", - Rename = "rename", - Delete = "delete") +const ResourceOperationKinds = (Create="create", + Rename="rename", + Delete="delete") @dict_readable struct WorkspaceEditClientCapabilities <: Outbound documentChanges::Union{Bool,Missing} @@ -109,16 +109,16 @@ end # Requires handwritten implementaiton to account for 3-part Unions function InitializeParams(dict::Dict) InitializeParams(dict["processId"], - haskey(dict, "clientInfo") ? InfoParams(dict["clientInfo"]) : missing, - !haskey(dict, "rootPath") ? missing : dict["rootPath"] === nothing ? nothing : DocumentUri(dict["rootPath"]), - # LS specification says this key should always exist, but neovim 0.5.1 doesn't seem to - # send it (seems fixed in neovim 0.6). For now, just assume it might not exist here. - (rootUri = get(dict, "rootUri", nothing); rootUri === nothing) ? nothing : DocumentUri(rootUri), - get(dict, "initializationOptions", missing), - ClientCapabilities(dict["capabilities"]), - haskey(dict, "trace") ? String(dict["trace"]) : missing , - !haskey(dict, "workspaceFolders") ? missing : dict["workspaceFolders"] === nothing ? nothing : WorkspaceFolder.(dict["workspaceFolders"]), - haskey(dict, "workDoneToken") ? dict["workDoneToken"] : missing) + haskey(dict, "clientInfo") ? InfoParams(dict["clientInfo"]) : missing, + !haskey(dict, "rootPath") ? missing : dict["rootPath"] === nothing ? nothing : DocumentUri(dict["rootPath"]), + # LS specification says this key should always exist, but neovim 0.5.1 doesn't seem to + # send it (seems fixed in neovim 0.6). For now, just assume it might not exist here. + (rootUri = get(dict, "rootUri", nothing); rootUri === nothing) ? nothing : DocumentUri(rootUri), + get(dict, "initializationOptions", missing), + ClientCapabilities(dict["capabilities"]), + haskey(dict, "trace") ? String(dict["trace"]) : missing, + !haskey(dict, "workspaceFolders") ? missing : dict["workspaceFolders"] === nothing ? nothing : WorkspaceFolder.(dict["workspaceFolders"]), + haskey(dict, "workDoneToken") ? dict["workDoneToken"] : missing) end ############################################################################## @@ -134,9 +134,9 @@ end struct ColorProviderOptions <: Outbound end const TextDocumentSyncKind = Int -const TextDocumentSyncKinds = (None = 0, - Full = 1, - Incremental = 2) +const TextDocumentSyncKinds = (None=0, + Full=1, + Incremental=2) struct TextDocumentSyncOptions <: Outbound openClose::Union{Bool,Missing} @@ -194,5 +194,4 @@ struct InitializeResult <: Outbound end ############################################################################## -@dict_readable struct InitializedParams -end +@dict_readable struct InitializedParams end diff --git a/src/protocol/messagedefs.jl b/src/protocol/messagedefs.jl index f244d27d5..65629b194 100644 --- a/src/protocol/messagedefs.jl +++ b/src/protocol/messagedefs.jl @@ -1,26 +1,26 @@ -const textDocument_codeAction_request_type = JSONRPC.RequestType("textDocument/codeAction", CodeActionParams, Union{Vector{Command}, Vector{CodeAction}, Nothing}) -const textDocument_completion_request_type = JSONRPC.RequestType("textDocument/completion", CompletionParams, Union{CompletionList, Vector{CompletionItem}, Nothing}) -const textDocument_signatureHelp_request_type = JSONRPC.RequestType("textDocument/signatureHelp", TextDocumentPositionParams, Union{SignatureHelp, Nothing}) -const textDocument_definition_request_type = JSONRPC.RequestType("textDocument/definition", TextDocumentPositionParams, Union{Location, Vector{Location}, Vector{LocationLink}, Nothing}) -const textDocument_formatting_request_type = JSONRPC.RequestType("textDocument/formatting", DocumentFormattingParams, Union{Vector{TextEdit}, Nothing}) -const textDocument_range_formatting_request_type = JSONRPC.RequestType("textDocument/rangeFormatting", DocumentRangeFormattingParams, Union{Vector{TextEdit}, Nothing}) -const textDocument_references_request_type = JSONRPC.RequestType("textDocument/references", ReferenceParams, Union{Vector{Location}, Nothing}) -const textDocument_rename_request_type = JSONRPC.RequestType("textDocument/rename", RenameParams, Union{WorkspaceEdit, Nothing}) +const textDocument_codeAction_request_type = JSONRPC.RequestType("textDocument/codeAction", CodeActionParams, Union{Vector{Command},Vector{CodeAction},Nothing}) +const textDocument_completion_request_type = JSONRPC.RequestType("textDocument/completion", CompletionParams, Union{CompletionList,Vector{CompletionItem},Nothing}) +const textDocument_signatureHelp_request_type = JSONRPC.RequestType("textDocument/signatureHelp", TextDocumentPositionParams, Union{SignatureHelp,Nothing}) +const textDocument_definition_request_type = JSONRPC.RequestType("textDocument/definition", TextDocumentPositionParams, Union{Location,Vector{Location},Vector{LocationLink},Nothing}) +const textDocument_formatting_request_type = JSONRPC.RequestType("textDocument/formatting", DocumentFormattingParams, Union{Vector{TextEdit},Nothing}) +const textDocument_range_formatting_request_type = JSONRPC.RequestType("textDocument/rangeFormatting", DocumentRangeFormattingParams, Union{Vector{TextEdit},Nothing}) +const textDocument_references_request_type = JSONRPC.RequestType("textDocument/references", ReferenceParams, Union{Vector{Location},Nothing}) +const textDocument_rename_request_type = JSONRPC.RequestType("textDocument/rename", RenameParams, Union{WorkspaceEdit,Nothing}) const textDocument_prepareRename_request_type = JSONRPC.RequestType("textDocument/prepareRename", PrepareRenameParams, Union{Range,Nothing}) -const textDocument_documentSymbol_request_type = JSONRPC.RequestType("textDocument/documentSymbol", DocumentSymbolParams, Union{Vector{DocumentSymbol}, Vector{SymbolInformation}, Nothing}) -const textDocument_documentHighlight_request_type = JSONRPC.RequestType("textDocument/documentHighlight", DocumentHighlightParams, Union{Vector{DocumentHighlight}, Nothing}) -const textDocument_hover_request_type = JSONRPC.RequestType("textDocument/hover", TextDocumentPositionParams, Union{Hover, Nothing}) +const textDocument_documentSymbol_request_type = JSONRPC.RequestType("textDocument/documentSymbol", DocumentSymbolParams, Union{Vector{DocumentSymbol},Vector{SymbolInformation},Nothing}) +const textDocument_documentHighlight_request_type = JSONRPC.RequestType("textDocument/documentHighlight", DocumentHighlightParams, Union{Vector{DocumentHighlight},Nothing}) +const textDocument_hover_request_type = JSONRPC.RequestType("textDocument/hover", TextDocumentPositionParams, Union{Hover,Nothing}) const textDocument_didOpen_notification_type = JSONRPC.NotificationType("textDocument/didOpen", DidOpenTextDocumentParams) const textDocument_didClose_notification_type = JSONRPC.NotificationType("textDocument/didClose", DidCloseTextDocumentParams) const textDocument_didChange_notification_type = JSONRPC.NotificationType("textDocument/didChange", DidChangeTextDocumentParams) const textDocument_didSave_notification_type = JSONRPC.NotificationType("textDocument/didSave", DidSaveTextDocumentParams) const textDocument_willSave_notification_type = JSONRPC.NotificationType("textDocument/willSave", WillSaveTextDocumentParams) -const textDocument_willSaveWaitUntil_request_type = JSONRPC.RequestType("textDocument/willSaveWaitUntil", WillSaveTextDocumentParams, Union{Vector{TextEdit}, Nothing}) +const textDocument_willSaveWaitUntil_request_type = JSONRPC.RequestType("textDocument/willSaveWaitUntil", WillSaveTextDocumentParams, Union{Vector{TextEdit},Nothing}) const textDocument_publishDiagnostics_notification_type = JSONRPC.NotificationType("textDocument/publishDiagnostics", PublishDiagnosticsParams) -const textDocument_selectionRange_request_type = JSONRPC.RequestType("textDocument/selectionRange", SelectionRangeParams, Union{Vector{SelectionRange}, Nothing}) +const textDocument_selectionRange_request_type = JSONRPC.RequestType("textDocument/selectionRange", SelectionRangeParams, Union{Vector{SelectionRange},Nothing}) const workspace_executeCommand_request_type = JSONRPC.RequestType("workspace/executeCommand", ExecuteCommandParams, Any) -const workspace_symbol_request_type = JSONRPC.RequestType("workspace/symbol", WorkspaceSymbolParams, Union{Vector{SymbolInformation}, Nothing}) +const workspace_symbol_request_type = JSONRPC.RequestType("workspace/symbol", WorkspaceSymbolParams, Union{Vector{SymbolInformation},Nothing}) const workspace_didChangeWatchedFiles_notification_type = JSONRPC.NotificationType("workspace/didChangeWatchedFiles", DidChangeWatchedFilesParams) const workspace_didChangeConfiguration_notification_type = JSONRPC.NotificationType("workspace/didChangeConfiguration", DidChangeConfigurationParams) const workspace_didChangeWorkspaceFolders_notification_type = JSONRPC.NotificationType("workspace/didChangeWorkspaceFolders", DidChangeWorkspaceFoldersParams) @@ -42,7 +42,7 @@ const setTraceNotification_notification_type = JSONRPC.NotificationType("\$/setT const window_workDoneProgress_create_request_type = JSONRPC.RequestType("window/workDoneProgress/create", WorkDoneProgressCreateParams, Nothing) const window_showMessage_notification_type = JSONRPC.NotificationType("window/showMessage", ShowMessageParams) -const window_showMessage_request_type = JSONRPC.RequestType("window/showMessageRequest", ShowMessageRequestParams, Union{MessageActionItem, Nothing}) +const window_showMessage_request_type = JSONRPC.RequestType("window/showMessageRequest", ShowMessageRequestParams, Union{MessageActionItem,Nothing}) const progress_notification_type = JSONRPC.NotificationType("\$/progress", ProgressParams) diff --git a/src/protocol/signature.jl b/src/protocol/signature.jl index 2eac2fe73..9450c55af 100644 --- a/src/protocol/signature.jl +++ b/src/protocol/signature.jl @@ -14,9 +14,9 @@ end end const SignatureHelpTriggerKind = Int -const SignatureHelpTriggerKinds = (Invoked = 1, - TriggerCharacter = 2, - ContentChange = 3) +const SignatureHelpTriggerKinds = (Invoked=1, + TriggerCharacter=2, + ContentChange=3) struct SignatureHelpOptions <: Outbound triggerCharacters::Union{Vector{String},Missing} diff --git a/src/protocol/symbols.jl b/src/protocol/symbols.jl index ec3ceb0fe..d34ea2623 100644 --- a/src/protocol/symbols.jl +++ b/src/protocol/symbols.jl @@ -1,30 +1,30 @@ const SymbolKind = Int -const SymbolKinds = (File = 1, - Module = 2, - Namespace = 3, - Package = 4, - Class = 5, - Method = 6, - Property = 7, - Field = 8, - Constructor = 9, - Enum = 10, - Interface = 11, - Function = 12, - Variable = 13, - Constant = 14, - String = 15, - Number = 16, - Boolean = 17, - Array = 18, - Object = 19, - Key = 20, - Null = 21, - EnumMember = 22, - Struct = 23, - Event = 24, - Operator = 25, - TypeParameter = 26) +const SymbolKinds = (File=1, + Module=2, + Namespace=3, + Package=4, + Class=5, + Method=6, + Property=7, + Field=8, + Constructor=9, + Enum=10, + Interface=11, + Function=12, + Variable=13, + Constant=14, + String=15, + Number=16, + Boolean=17, + Array=18, + Object=19, + Key=20, + Null=21, + EnumMember=22, + Struct=23, + Event=24, + Operator=25, + TypeParameter=26) @dict_readable struct SymbolKindCapabilities <: Outbound valueSet::Union{Vector{SymbolKind},Missing} diff --git a/src/requests/actions.jl b/src/requests/actions.jl index 3e012975b..3a4abb598 100644 --- a/src/requests/actions.jl +++ b/src/requests/actions.jl @@ -102,16 +102,16 @@ function expand_inline_func(x, server, conn) if headof(body) == :block && length(body) == 1 file, offset = get_file_loc(func) tde = TextDocumentEdit(VersionedTextDocumentIdentifier(file._uri, file._version), TextEdit[ - TextEdit(Range(file, offset .+ (0:func.fullspan)), string("function ", get_text(file)[offset .+ (1:sig.span)], "\n ", get_text(file)[offset + sig.fullspan + op.fullspan .+ (1:body.span)], "\nend\n")) + TextEdit(Range(file, offset .+ (0:func.fullspan)), string("function ", get_text(file)[offset.+(1:sig.span)], "\n ", get_text(file)[offset+sig.fullspan+op.fullspan.+(1:body.span)], "\nend\n")) ]) JSONRPC.send(conn, workspace_applyEdit_request_type, ApplyWorkspaceEditParams(missing, WorkspaceEdit(missing, TextDocumentEdit[tde]))) elseif (headof(body) === :begin || CSTParser.isbracketed(body)) && - headof(body.args[1]) === :block && length(body.args[1]) > 0 + headof(body.args[1]) === :block && length(body.args[1]) > 0 file, offset = get_file_loc(func) - newtext = string("function ", get_text(file)[offset .+ (1:sig.span)]) + newtext = string("function ", get_text(file)[offset.+(1:sig.span)]) blockoffset = offset + sig.fullspan + op.fullspan + body.trivia[1].fullspan for i = 1:length(body.args[1].args) - newtext = string(newtext, "\n ", get_text(file)[blockoffset .+ (1:body.args[1].args[i].span)]) + newtext = string(newtext, "\n ", get_text(file)[blockoffset.+(1:body.args[1].args[i].span)]) blockoffset += body.args[1].args[i].fullspan end newtext = string(newtext, "\nend\n") @@ -142,9 +142,9 @@ function get_next_line_offset(x) # get next line after using_stmt insertpos = -1 line_offsets = get_line_offsets(file) - for i = 1:length(line_offsets) - 1 - if line_offsets[i] < offset + x.span <= line_offsets[i + 1] - insertpos = line_offsets[i + 1] + for i = 1:length(line_offsets)-1 + if line_offsets[i] < offset + x.span <= line_offsets[i+1] + insertpos = line_offsets[i+1] end end return insertpos @@ -257,12 +257,12 @@ function remove_farg_name(x, server, conn) file, offset = get_file_loc(x1) if CSTParser.isdeclaration(x1) tde = TextDocumentEdit(VersionedTextDocumentIdentifier(file._uri, file._version), TextEdit[ - TextEdit(Range(file, offset .+ (0:x1.args[1].fullspan)), "") - ]) + TextEdit(Range(file, offset .+ (0:x1.args[1].fullspan)), "") + ]) else tde = TextDocumentEdit(VersionedTextDocumentIdentifier(file._uri, file._version), TextEdit[ - TextEdit(Range(file, offset .+ (0:x1.fullspan)), "::Any") - ]) + TextEdit(Range(file, offset .+ (0:x1.fullspan)), "::Any") + ]) end JSONRPC.send(conn, workspace_applyEdit_request_type, ApplyWorkspaceEditParams(missing, WorkspaceEdit(missing, TextDocumentEdit[tde]))) end @@ -272,17 +272,17 @@ end # * a function (.when) called on the currently selected expression and parameters of the CodeAction call; # * a function (.handler) called on three arguments (current expression, server and the jr connection) to implement the command. const LSActions = Dict( - "ExplicitPackageVarImport" => ServerAction(Command("Explicitly import used package variables.", "ExplicitPackageVarImport", missing), - (x, params) -> refof(x) isa StaticLint.Binding && refof(x).val isa SymbolServer.ModuleStore, - explicitly_import_used_variables), + "ExplicitPackageVarImport" => ServerAction(Command("Explicitly import used package variables.", "ExplicitPackageVarImport", missing), + (x, params) -> refof(x) isa StaticLint.Binding && refof(x).val isa SymbolServer.ModuleStore, + explicitly_import_used_variables), "ExpandFunction" => ServerAction(Command("Expand function definition.", "ExpandFunction", missing), - (x, params) -> is_in_fexpr(x, is_single_line_func), - expand_inline_func), + (x, params) -> is_in_fexpr(x, is_single_line_func), + expand_inline_func), "FixMissingRef" => ServerAction(Command("Fix missing reference", "FixMissingRef", missing), - (x, params) -> is_fixable_missing_ref(x, params.context), - applymissingreffix), - "ReexportModule" => ServerAction(Command("Re-export package variables.", "ReexportModule", missing), - (x, params) -> StaticLint.is_in_fexpr(x, x -> headof(x) === :using || headof(x) === :import) && (refof(x) isa StaticLint.Binding && (refof(x).type === StaticLint.CoreTypes.Module || (refof(x).val isa StaticLint.Binding && refof(x).val.type === StaticLint.CoreTypes.Module) || refof(x).val isa SymbolServer.ModuleStore) || refof(x) isa SymbolServer.ModuleStore), - reexport_package), + (x, params) -> is_fixable_missing_ref(x, params.context), + applymissingreffix), + "ReexportModule" => ServerAction(Command("Re-export package variables.", "ReexportModule", missing), + (x, params) -> StaticLint.is_in_fexpr(x, x -> headof(x) === :using || headof(x) === :import) && (refof(x) isa StaticLint.Binding && (refof(x).type === StaticLint.CoreTypes.Module || (refof(x).val isa StaticLint.Binding && refof(x).val.type === StaticLint.CoreTypes.Module) || refof(x).val isa SymbolServer.ModuleStore) || refof(x) isa SymbolServer.ModuleStore), + reexport_package), "DeleteUnusedFunctionArgumentName" => ServerAction(Command("Delete name of unused function argument.", "DeleteUnusedFunctionArgumentName", missing), (x, params) -> StaticLint.is_in_fexpr(x, x -> StaticLint.haserror(x) && StaticLint.errorof(x) == StaticLint.UnusedFunctionArgument), remove_farg_name) ) diff --git a/src/requests/completions.jl b/src/requests/completions.jl index 609913846..d9c6b7f2f 100644 --- a/src/requests/completions.jl +++ b/src/requests/completions.jl @@ -6,7 +6,7 @@ struct CompletionState offset::Int completions::Dict{String,CompletionItem} range::Range - x::Union{Nothing, EXPR} + x::Union{Nothing,EXPR} doc::Document server::LanguageServerInstance using_stmts::Dict{String,Any} @@ -48,7 +48,7 @@ function textDocument_completion_request(params::CompletionParams, server::Langu CompletionState(offset, Dict{String,CompletionItem}(), rng, x, doc, server, using_stmts) end - ppt, pt, t, is_at_end = get_partial_completion(state) + ppt, pt, t, is_at_end = get_partial_completion(state) if pt isa CSTParser.Tokens.Token && pt.kind == CSTParser.Tokenize.Tokens.BACKSLASH latex_completions(string("\\", CSTParser.Tokenize.untokenize(t)), state) @@ -58,9 +58,9 @@ function textDocument_completion_request(params::CompletionParams, server::Langu partial = is_latex_comp(t.val, state.offset - t.startbyte) !isempty(partial) && latex_completions(partial, state) elseif t isa CSTParser.Tokens.Token && (t.kind in (CSTParser.Tokenize.Tokens.STRING, - CSTParser.Tokenize.Tokens.TRIPLE_STRING, - CSTParser.Tokenize.Tokens.CMD, - CSTParser.Tokenize.Tokens.TRIPLE_CMD)) + CSTParser.Tokenize.Tokens.TRIPLE_STRING, + CSTParser.Tokenize.Tokens.CMD, + CSTParser.Tokenize.Tokens.TRIPLE_CMD)) string_completion(t, state) elseif state.x isa EXPR && is_in_import_statement(state.x) import_completions(ppt, pt, t, is_at_end, state.x, state) @@ -157,7 +157,7 @@ const snippet_completions = Dict{String,String}( "try" => "try\n\t\$0\ncatch\nend", "using" => "using ", "while" => "while \$1\n\t\$0\nend" - ) +) function texteditfor(state::CompletionState, partial, n) @@ -243,9 +243,9 @@ end function is_rebinding_of_module(x) x isa EXPR && refof(x).type === StaticLint.CoreTypes.Module && # binding is a Module - refof(x).val isa EXPR && CSTParser.isassignment(refof(x).val) && # binding expr is an assignment - StaticLint.hasref(refof(x).val.args[2]) && refof(refof(x).val.args[2]).type === StaticLint.CoreTypes.Module && - refof(refof(x).val.args[2]).val isa EXPR && CSTParser.defines_module(refof(refof(x).val.args[2]).val)# double check the rhs points to a module + refof(x).val isa EXPR && CSTParser.isassignment(refof(x).val) && # binding expr is an assignment + StaticLint.hasref(refof(x).val.args[2]) && refof(refof(x).val.args[2]).type === StaticLint.CoreTypes.Module && + refof(refof(x).val.args[2]).val isa EXPR && CSTParser.defines_module(refof(refof(x).val.args[2]).val)# double check the rhs points to a module end function _get_dot_completion(px, spartial, state::CompletionState) end @@ -318,7 +318,7 @@ end function string_completion(t, state::CompletionState) path_completion(t, state) # Need to adjust things for quotation marks - if t.kind in (CSTParser.Tokenize.Tokens.STRING,CSTParser.Tokenize.Tokens.CMD) + if t.kind in (CSTParser.Tokenize.Tokens.STRING, CSTParser.Tokenize.Tokens.CMD) t.startbyte + 1 < state.offset <= t.endbyte || return relative_offset = state.offset - t.startbyte - 1 content = t.val[2:prevind(t.val, lastindex(t.val))] @@ -348,18 +348,18 @@ function is_latex_comp_char(u) # latex completions. # from: UInt8.(sort!(unique(prod([k[2:end] for (k,_) in Iterators.flatten((REPL.REPLCompletions.latex_symbols, REPL.REPLCompletions.emoji_symbols))])))) u === 0x21 || - u === 0x28 || - u === 0x29 || - u === 0x2b || - u === 0x2d || - u === 0x2f || - 0x30 <= u <= 0x39 || - u === 0x3a || - u === 0x3d || - 0x41 <= u <= 0x5a || - u === 0x5e || - u === 0x5f || - 0x61 <= u <= 0x7a + u === 0x28 || + u === 0x29 || + u === 0x2b || + u === 0x2d || + u === 0x2f || + 0x30 <= u <= 0x39 || + u === 0x3a || + u === 0x3d || + 0x41 <= u <= 0x5a || + u === 0x5e || + u === 0x5f || + 0x61 <= u <= 0x7a end function path_completion(t, state::CompletionState) @@ -384,7 +384,7 @@ function path_completion(t, state::CompletionState) if isdir(joinpath(dir, f)) f = string(f, "/") end - rng1 = Range(state.doc, state.offset - sizeof(partial):state.offset) + rng1 = Range(state.doc, state.offset-sizeof(partial):state.offset) add_completion_item(state, CompletionItem(f, 17, f, TextEdit(rng1, f))) catch err isa(err, Base.IOError) || isa(err, Base.SystemError) || rethrow() @@ -405,7 +405,7 @@ function import_completions(ppt, pt, t, is_at_end, x, state::CompletionState) import_root = get_import_root(import_statement) if (t.kind == CSTParser.Tokens.WHITESPACE && pt.kind ∈ (CSTParser.Tokens.USING, CSTParser.Tokens.IMPORT, CSTParser.Tokens.IMPORTALL, CSTParser.Tokens.COMMA, CSTParser.Tokens.COLON)) || - (t.kind in (CSTParser.Tokens.COMMA, CSTParser.Tokens.COLON)) + (t.kind in (CSTParser.Tokens.COMMA, CSTParser.Tokens.COLON)) # no partial, no dot if import_root !== nothing && refof(import_root) isa SymbolServer.ModuleStore for (n, m) in refof(import_root).vals diff --git a/src/requests/features.jl b/src/requests/features.jl index dc8aea627..dd6200dd3 100644 --- a/src/requests/features.jl +++ b/src/requests/features.jl @@ -98,7 +98,7 @@ function textDocument_definition_request(params::TextDocumentPositionParams, ser return locations end -function descend(x::EXPR, target::EXPR, offset = 0) +function descend(x::EXPR, target::EXPR, offset=0) for c in x if c == target return true, offset @@ -144,10 +144,10 @@ function get_juliaformatter_config(doc, server) path = get_path(doc) # search through workspace for a `.JuliaFormatter.toml` - workspace_dirs = sort(filter(f -> startswith(path, f), collect(server.workspaceFolders)), by = length, rev = true) + workspace_dirs = sort(filter(f -> startswith(path, f), collect(server.workspaceFolders)), by=length, rev=true) config_path = length(workspace_dirs) > 0 ? - search_file(JuliaFormatter.CONFIG_FILE_NAME, path, workspace_dirs[1]) : - nothing + search_file(JuliaFormatter.CONFIG_FILE_NAME, path, workspace_dirs[1]) : + nothing config_path === nothing && return nothing @@ -157,13 +157,13 @@ end function default_juliaformatter_config(params) return ( - indent = params.options.tabSize, - annotate_untyped_fields_with_any = false, - join_lines_based_on_source = true, - trailing_comma = nothing, - margin = 10_000, - always_for_in = nothing, - whitespace_in_kwargs = false + indent=params.options.tabSize, + annotate_untyped_fields_with_any=false, + join_lines_based_on_source=true, + trailing_comma=nothing, + margin=10_000, + always_for_in=nothing, + whitespace_in_kwargs=false ) end @@ -255,7 +255,7 @@ function textDocument_range_formatting_request(params::DocumentRangeFormattingPa if longest_prefix !== nothing && !isempty(longest_prefix) io = IOBuffer() - for line in eachline(IOBuffer(newcontent), keep = true) + for line in eachline(IOBuffer(newcontent), keep=true) print(io, longest_prefix, line) end newcontent = String(take!(io)) @@ -326,9 +326,9 @@ end is_valid_binding_name(name) = false function is_valid_binding_name(name::EXPR) (headof(name) === :IDENTIFIER && valof(name) isa String && !isempty(valof(name))) || - CSTParser.isoperator(name) || - (headof(name) === :NONSTDIDENTIFIER && length(name.args) == 2 && valof(name.args[2]) isa String && !isempty(valof(name.args[2]))) || - is_callable_object_binding(name) + CSTParser.isoperator(name) || + (headof(name) === :NONSTDIDENTIFIER && length(name.args) == 2 && valof(name.args[2]) isa String && !isempty(valof(name.args[2]))) || + is_callable_object_binding(name) end function get_name_of_binding(name::EXPR) if headof(name) === :IDENTIFIER @@ -353,7 +353,7 @@ end function collect_document_symbols(x::EXPR, server::LanguageServerInstance, doc, pos=0, symbols=DocumentSymbol[]) if bindingof(x) !== nothing - b = bindingof(x) + b = bindingof(x) if b.val isa EXPR && is_valid_binding_name(b.name) ds = DocumentSymbol( get_name_of_binding(b.name), # name @@ -530,8 +530,8 @@ function textDocument_selectionRange_request(params::SelectionRangeParams, serve get_selection_range_of_expr(x) end return ret isa Vector{SelectionRange} ? - ret : - nothing + ret : + nothing end # Just returns a selection for each parent EXPR, should be more selective diff --git a/src/requests/hover.jl b/src/requests/hover.jl index e7678d71b..6a59dddf8 100644 --- a/src/requests/hover.jl +++ b/src/requests/hover.jl @@ -136,7 +136,7 @@ function get_preceding_docs(expr::EXPR, documentation) end end -ensure_ends_with(s, c = "\n") = endswith(s, c) ? s : string(s, c) +ensure_ends_with(s, c="\n") = endswith(s, c) ? s : string(s, c) binding_has_preceding_docs(b::StaticLint.Binding) = expr_has_preceding_docs(b.val) diff --git a/src/requests/init.jl b/src/requests/init.jl index a3d7d1362..e9a3527e8 100644 --- a/src/requests/init.jl +++ b/src/requests/init.jl @@ -2,35 +2,35 @@ function ServerCapabilities(client::ClientCapabilities) prepareSupport = !ismissing(client.textDocument) && !ismissing(client.textDocument.rename) && client.textDocument.rename.prepareSupport === true ServerCapabilities( - TextDocumentSyncOptions(true, - TextDocumentSyncKinds.Full, - false, - false, - SaveOptions(true)), - CompletionOptions(false, [".", "@", "\"", "^"], missing), - true, - SignatureHelpOptions(["(", ","], missing), - false, - true, - false, - false, - true, - true, - true, - true, - missing, - missing, - false, - true, - true, - missing, - RenameOptions(missing, prepareSupport), - false, - ExecuteCommandOptions(missing, collect(keys(LSActions))), - true, - true, - WorkspaceOptions(WorkspaceFoldersOptions(true, true)), - missing) + TextDocumentSyncOptions(true, + TextDocumentSyncKinds.Full, + false, + false, + SaveOptions(true)), + CompletionOptions(false, [".", "@", "\"", "^"], missing), + true, + SignatureHelpOptions(["(", ","], missing), + false, + true, + false, + false, + true, + true, + true, + true, + missing, + missing, + false, + true, + true, + missing, + RenameOptions(missing, prepareSupport), + false, + ExecuteCommandOptions(missing, collect(keys(LSActions))), + true, + true, + WorkspaceOptions(WorkspaceFoldersOptions(true, true)), + missing) end @@ -75,11 +75,11 @@ end function load_rootpath(path) try return isdir(path) && - hasreadperm(path) && - path != "" && - path != homedir() && - !isjuliabasedir(path) && - !has_too_many_files(path) + hasreadperm(path) && + path != "" && + path != homedir() && + !isjuliabasedir(path) && + !has_too_many_files(path) catch err is_walkdir_error(err) || rethrow() return false @@ -142,7 +142,7 @@ function initialize_request(params::InitializeParams, server::LanguageServerInst if !(params.rootUri isa Nothing) push!(server.workspaceFolders, uri2filepath(params.rootUri)) elseif !(params.rootPath isa Nothing) - push!(server.workspaceFolders, params.rootPath) + push!(server.workspaceFolders, params.rootPath) end elseif (params.workspaceFolders !== nothing) & (params.workspaceFolders !== missing) for wksp in params.workspaceFolders @@ -165,9 +165,9 @@ function initialize_request(params::InitializeParams, server::LanguageServerInst end if !ismissing(params.capabilities.workspace) && - !ismissing(params.capabilities.workspace.didChangeConfiguration) && - !ismissing(params.capabilities.workspace.didChangeConfiguration.dynamicRegistration) && - params.capabilities.workspace.didChangeConfiguration.dynamicRegistration + !ismissing(params.capabilities.workspace.didChangeConfiguration) && + !ismissing(params.capabilities.workspace.didChangeConfiguration.dynamicRegistration) && + params.capabilities.workspace.didChangeConfiguration.dynamicRegistration server.clientcapability_workspace_didChangeConfiguration = true end diff --git a/src/requests/misc.jl b/src/requests/misc.jl index 8d76f60f8..4eaac3be8 100644 --- a/src/requests/misc.jl +++ b/src/requests/misc.jl @@ -1,12 +1,9 @@ -function cancel_notification(params::CancelParams, server::LanguageServerInstance, conn) -end +function cancel_notification(params::CancelParams, server::LanguageServerInstance, conn) end -function setTrace_notification(params::SetTraceParams, server::LanguageServerInstance, conn) -end +function setTrace_notification(params::SetTraceParams, server::LanguageServerInstance, conn) end # TODO Provide type for params -function setTraceNotification_notification(params, server::LanguageServerInstance, conn) -end +function setTraceNotification_notification(params, server::LanguageServerInstance, conn) end function julia_getCurrentBlockRange_request(tdpp::VersionedTextDocumentPositionParams, server::LanguageServerInstance, conn) fallback = (Position(0, 0), Position(0, 0), tdpp.position) @@ -35,7 +32,7 @@ function julia_getCurrentBlockRange_request(tdpp::VersionedTextDocumentPositionP thisline, _ = get_position_at(doc, loc + a.span) if tdpp.position.line > thisline || headof(a) === :NOTHING loc += a.fullspan - a = x[i + 1] + a = x[i+1] end end end diff --git a/src/requests/signatures.jl b/src/requests/signatures.jl index a026c6e97..f6e4f489d 100644 --- a/src/requests/signatures.jl +++ b/src/requests/signatures.jl @@ -48,7 +48,7 @@ function get_signatures(b::StaticLint.Binding, tls::StaticLint.Scope, sigs::Vect end end -function get_signatures(b::T, tls::StaticLint.Scope, sigs::Vector{SignatureInformation}, env) where T <: Union{SymbolServer.FunctionStore,SymbolServer.DataTypeStore} +function get_signatures(b::T, tls::StaticLint.Scope, sigs::Vector{SignatureInformation}, env) where {T<:Union{SymbolServer.FunctionStore,SymbolServer.DataTypeStore}} StaticLint.iterate_over_ss_methods(b, tls, env, function (m) push!(sigs, SignatureInformation(string(m), "", (a -> ParameterInformation(string(a[1]), string(a[2]))).(m.sig))) return false diff --git a/src/requests/textdocument.jl b/src/requests/textdocument.jl index e3a3e0155..8f9c6e1e2 100644 --- a/src/requests/textdocument.jl +++ b/src/requests/textdocument.jl @@ -58,8 +58,7 @@ function textDocument_didSave_notification(params::DidSaveTextDocumentParams, se end -function textDocument_willSave_notification(params::WillSaveTextDocumentParams, server::LanguageServerInstance, conn) -end +function textDocument_willSave_notification(params::WillSaveTextDocumentParams, server::LanguageServerInstance, conn) end function textDocument_willSaveWaitUntil_request(params::WillSaveTextDocumentParams, server::LanguageServerInstance, conn) @@ -68,12 +67,12 @@ end comp(x, y) = x == y function comp(x::CSTParser.EXPR, y::CSTParser.EXPR) - comp(x.head, y.head) && - x.span == y.span && - x.fullspan == y.fullspan && - x.val == y.val && - length(x) == length(y) && - all(comp(x[i], y[i]) for i = 1:length(x)) + comp(x.head, y.head) && + x.span == y.span && + x.fullspan == y.fullspan && + x.val == y.val && + length(x) == length(y) && + all(comp(x[i], y[i]) for i = 1:length(x)) end function textDocument_didChange_notification(params::DidChangeTextDocumentParams, server::LanguageServerInstance, conn) @@ -91,16 +90,16 @@ function textDocument_didChange_notification(params::DidChangeTextDocumentParams parse_all(doc, server) else cst0, cst1 = getcst(doc), CSTParser.parse(get_text(doc), true) - r1, r2, r3 = CSTParser.minimal_reparse(s0, get_text(doc), cst0, cst1, inds = true) - for i in setdiff(1:length(cst0.args), r1 , r3) # clean meta from deleted expr + r1, r2, r3 = CSTParser.minimal_reparse(s0, get_text(doc), cst0, cst1, inds=true) + for i in setdiff(1:length(cst0.args), r1, r3) # clean meta from deleted expr StaticLint.clear_meta(cst0[i]) end setcst(doc, EXPR(cst0.head, EXPR[cst0.args[r1]; cst1.args[r2]; cst0.args[r3]], nothing)) comp(cst1, getcst(doc)) || @error "File didn't update properly." # expensive check, remove sizeof(get_text(doc)) == getcst(doc).fullspan || @error "CST does not match input string length." headof(doc.cst) === :file ? set_doc(doc.cst, doc) : @info "headof(doc) isn't :file for $(doc._path)" - - target_exprs = getcst(doc).args[last(r1) .+ (1:length(r2))] + + target_exprs = getcst(doc).args[last(r1).+(1:length(r2))] semantic_pass(getroot(doc), target_exprs) lint!(doc, server) end @@ -165,7 +164,7 @@ function mark_errors(doc, out=Diagnostic[]) while line < nlines seek(io, line_offsets[line]) char = 0 - while line_offsets[line] <= offset < line_offsets[line + 1] + while line_offsets[line] <= offset < line_offsets[line+1] while offset > position(io) c = read(io, Char) if UInt32(c) >= 0x010000 @@ -212,8 +211,8 @@ Is this diagnostic reliant on the current environment being accurately represent """ function is_diag_dependent_on_env(diag::Diagnostic) startswith(diag.message, "Missing reference: ") || - startswith(diag.message, "Possible method call error") || - startswith(diag.message, "An imported") + startswith(diag.message, "Possible method call error") || + startswith(diag.message, "An imported") end @@ -260,14 +259,14 @@ function parse_jmd(ps, str) for (startbyte, b) in blocks if CSTParser.ismacrocall(b) && headof(b.args[1]) === :globalrefcmd && headof(b.args[3]) === :TRIPLESTRING && (startswith(b.args[3].val, "julia") || startswith(b.args[3].val, "{julia")) - + blockstr = b.args[3].val ps = CSTParser.ParseState(blockstr) # skip first line while ps.nt.startpos[1] == 1 CSTParser.next(ps) end - prec_str_size = currentbyte:startbyte + ps.nt.startbyte + 3 + prec_str_size = currentbyte:startbyte+ps.nt.startbyte+3 push!(top, EXPR(:STRING, length(prec_str_size), length(prec_str_size))) @@ -282,14 +281,14 @@ function parse_jmd(ps, str) blockstr = b.args[3].val ps = CSTParser.ParseState(blockstr) CSTParser.next(ps) - prec_str_size = currentbyte:startbyte + ps.nt.startbyte + 1 + prec_str_size = currentbyte:startbyte+ps.nt.startbyte+1 push!(top, EXPR(:STRING, length(prec_str_size), length(prec_str_size))) args, ps = CSTParser.parse(ps, true) for a in args.args push!(top, a) end - + CSTParser.update_span!(top) currentbyte = top.fullspan + 1 end diff --git a/src/runserver.jl b/src/runserver.jl index da5a82cc5..b4c4e6de0 100644 --- a/src/runserver.jl +++ b/src/runserver.jl @@ -35,15 +35,15 @@ julia --project=/path/to/LanguageServer.jl \\ ``` """ function runserver(pipe_in=stdin, pipe_out=stdout, env_path=choose_env(), - depot_path="", err_handler=nothing, symserver_store_path=nothing) + depot_path="", err_handler=nothing, symserver_store_path=nothing) server = LanguageServerInstance(pipe_in, pipe_out, env_path, depot_path, - err_handler, symserver_store_path) + err_handler, symserver_store_path) run(server) end function choose_env() maybe_dirname = x -> x !== nothing ? dirname(x) : nothing something(get(ARGS, 1, nothing), # 1. path passed explicitly - maybe_dirname(Base.current_project(pwd())), # 2. parent project of pwd() - maybe_dirname(Base.load_path_expand("@v#.#"))) # 3. default "global" env + maybe_dirname(Base.current_project(pwd())), # 2. parent project of pwd() + maybe_dirname(Base.load_path_expand("@v#.#"))) # 3. default "global" env end diff --git a/src/utilities.jl b/src/utilities.jl index 7d072ec02..9829d5fc8 100644 --- a/src/utilities.jl +++ b/src/utilities.jl @@ -15,7 +15,7 @@ end # lookup # ------ -traverse_by_name(f, cache = SymbolServer.stdlibs) = traverse_store!.(f, values(cache)) +traverse_by_name(f, cache=SymbolServer.stdlibs) = traverse_store!.(f, values(cache)) traverse_store!(_, _) = return traverse_store!(f, store::SymbolServer.EnvStore) = traverse_store!.(f, values(store)) @@ -49,9 +49,9 @@ function uri2filepath(uri::AbstractString) # unc path: file://shares/c$/far/boo value = "//$host_unescaped$path_unescaped" elseif length(path_unescaped) >= 3 && - path_unescaped[1] == '/' && - isascii(path_unescaped[2]) && isletter(path_unescaped[2]) && - path_unescaped[3] == ':' + path_unescaped[1] == '/' && + isascii(path_unescaped[2]) && isletter(path_unescaped[2]) && + path_unescaped[3] == ':' # windows drive letter: file:///c:/far/boo value = lowercase(path_unescaped[2]) * path_unescaped[3:end] else @@ -143,9 +143,9 @@ function remove_workspace_files(root, server) get_open_in_editor(doc) && continue # If the file is in any other workspace folder, don't delete it any(folder -> startswith(fpath, folder), server.workspaceFolders) && continue - deletedocument!(server, uri) - end + deletedocument!(server, uri) end +end function Base.getindex(server::LanguageServerInstance, r::Regex) @@ -157,7 +157,7 @@ function Base.getindex(server::LanguageServerInstance, r::Regex) end function _offset_unitrange(r::UnitRange{Int}, first=true) - return r.start - 1:r.stop + return r.start-1:r.stop end function get_toks(doc, offset) @@ -260,7 +260,7 @@ function get_expr(x, offset::UnitRange{Int}, pos=0, ignorewhitespace=false) end # full (not only trivia) expr containing rng, modulo whitespace -function get_inner_expr(x, rng::UnitRange{Int}, pos=0, pos_span = 0) +function get_inner_expr(x, rng::UnitRange{Int}, pos=0, pos_span=0) if all(pos .> rng) return nothing end @@ -300,8 +300,8 @@ function get_expr1(x, offset, pos=0) if offset == pos if i == 1 return get_expr1(arg, offset, pos) - elseif headof(x[i - 1]) === :IDENTIFIER - return get_expr1(x[i - 1], offset, pos) + elseif headof(x[i-1]) === :IDENTIFIER + return get_expr1(x[i-1], offset, pos) else return get_expr1(arg, offset, pos) end @@ -312,8 +312,8 @@ function get_expr1(x, offset, pos=0) if offset == pos if i == 1 return get_expr1(arg, offset, pos) - elseif headof(x[i - 1]) === :IDENTIFIER - return get_expr1(x[i - 1], offset, pos) + elseif headof(x[i-1]) === :IDENTIFIER + return get_expr1(x[i-1], offset, pos) else return get_expr1(arg, offset, pos) end @@ -375,7 +375,7 @@ if VERSION < v"1.1" || Sys.iswindows() && VERSION < v"1.3" end return out end - _path_separator = "\\" + _path_separator = "\\" _path_separator_re = r"[/\\]+" function _pathsep(paths::AbstractString...) for path in paths @@ -388,11 +388,11 @@ if VERSION < v"1.1" || Sys.iswindows() && VERSION < v"1.3" isabspath(b) && return b A, a = _splitdrive(a) B, b = _splitdrive(b) - !isempty(B) && A != B && return string(B,b) + !isempty(B) && A != B && return string(B, b) C = isempty(B) ? A : B - isempty(a) ? string(C,b) : - occursin(_path_separator_re, a[end:end]) ? string(C,a,b) : - string(C,a,_pathsep(a,b),b) + isempty(a) ? string(C, b) : + occursin(_path_separator_re, a[end:end]) ? string(C, a, b) : + string(C, a, _pathsep(a, b), b) end joinpath(a::AbstractString, b::AbstractString) = joinpath(String(a), String(b)) joinpath(a, b, c, paths...) = joinpath(joinpath(a, b), c, paths...) @@ -481,7 +481,7 @@ end function is_in_target_dir_of_package(pkgpath, target) try # Safe failure - attempts to read disc. spaths = splitpath(pkgpath) - if (i = findfirst(==(target), spaths)) !== nothing && "src" in readdir(joinpath(spaths[1:i - 1]...)) + if (i = findfirst(==(target), spaths)) !== nothing && "src" in readdir(joinpath(spaths[1:i-1]...)) return true end return false diff --git a/test/requests/actions.jl b/test/requests/actions.jl index 7e7021e6d..dcef1d806 100644 --- a/test/requests/actions.jl +++ b/test/requests/actions.jl @@ -4,7 +4,7 @@ action_request_test(line0, char0, line1=line0, char1=char0; diags=[]) = Language settestdoc("using Base.Meta\n") @test any(c.command == "ReexportModule" for c in action_request_test(0, 15)) c = filter(c -> c.command == "ReexportModule", action_request_test(0, 15))[1] - + LanguageServer.workspace_executeCommand_request(LanguageServer.ExecuteCommandParams(missing, c.command, c.arguments), server, server.jr_endpoint) end @@ -12,13 +12,13 @@ end settestdoc("f(x) = x") @test any(c.command == "ExpandFunction" for c in action_request_test(0, 5)) c = filter(c -> c.command == "ExpandFunction", action_request_test(0, 5))[1] - + LanguageServer.workspace_executeCommand_request(LanguageServer.ExecuteCommandParams(missing, c.command, c.arguments), server, server.jr_endpoint) settestdoc("f(x) = begin x end") @test any(c.command == "ExpandFunction" for c in action_request_test(0, 5)) c = filter(c -> c.command == "ExpandFunction", action_request_test(0, 5))[1] - + LanguageServer.workspace_executeCommand_request(LanguageServer.ExecuteCommandParams(missing, c.command, c.arguments), server, server.jr_endpoint) end @@ -27,25 +27,25 @@ end e = LanguageServer.mark_errors(doc)[1] @test any(c.command == "FixMissingRef" for c in action_request_test(0, 5, diags=[e])) c = filter(c -> c.command == "FixMissingRef", action_request_test(0, 5, diags=[e]))[1] - + LanguageServer.workspace_executeCommand_request(LanguageServer.ExecuteCommandParams(missing, c.command, c.arguments), server, server.jr_endpoint) end @testset "explicit import" begin doc = settestdoc("using Base.Meta\nMeta.quot") @test LanguageServer.find_using_statement(doc.cst.args[2].args[1]) !== nothing - + @test any(c.command == "ExplicitPackageVarImport" for c in action_request_test(1, 1)) c = filter(c -> c.command == "ExplicitPackageVarImport", action_request_test(1, 1))[1] - + LanguageServer.workspace_executeCommand_request(LanguageServer.ExecuteCommandParams(missing, c.command, c.arguments), server, server.jr_endpoint) end @testset "farg unused" begin doc = settestdoc("function f(arg::T) end\n") - + @test any(c.command == "DeleteUnusedFunctionArgumentName" for c in action_request_test(0, 12)) c = filter(c -> c.command == "DeleteUnusedFunctionArgumentName", action_request_test(0, 12))[1] - + LanguageServer.workspace_executeCommand_request(LanguageServer.ExecuteCommandParams(missing, c.command, c.arguments), server, server.jr_endpoint) end diff --git a/test/requests/completions.jl b/test/requests/completions.jl index 2f95372a7..1149f657f 100644 --- a/test/requests/completions.jl +++ b/test/requests/completions.jl @@ -32,8 +32,7 @@ completion_test(line, char) = LanguageServer.textDocument_completion_request(Lan @test completion_test(6, 14).items[1].textEdit.range == LanguageServer.Range(6, 0, 6, 14) end -@testset "path completions" begin -end +@testset "path completions" begin end @testset "import completions" begin settestdoc("import Base: r") diff --git a/test/requests/misc.jl b/test/requests/misc.jl index 357297b6d..30a0a8699 100644 --- a/test/requests/misc.jl +++ b/test/requests/misc.jl @@ -2,11 +2,10 @@ doc = settestdoc("ab") res = (LanguageServer.Position(0, 0), LanguageServer.Position(0, 2), LanguageServer.Position(0, 2)) - + @test LanguageServer.julia_getCurrentBlockRange_request(LanguageServer.VersionedTextDocumentPositionParams(LanguageServer.TextDocumentIdentifier("testdoc"), 0, LanguageServer.Position(0, 0)), server, server.jr_endpoint) == res @test LanguageServer.julia_getCurrentBlockRange_request(LanguageServer.VersionedTextDocumentPositionParams(LanguageServer.TextDocumentIdentifier("testdoc"), 0, LanguageServer.Position(0, 1)), server, server.jr_endpoint) == res @test LanguageServer.julia_getCurrentBlockRange_request(LanguageServer.VersionedTextDocumentPositionParams(LanguageServer.TextDocumentIdentifier("testdoc"), 0, LanguageServer.Position(0, 2)), server, server.jr_endpoint) == res end - diff --git a/test/runtests.jl b/test/runtests.jl index dd6abcd44..06486c18a 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -67,7 +67,7 @@ end empty!(server._documents) LanguageServer.load_folder(dirname(String(first(methods(LanguageServer.eval)).file)), server) on_all_docs(server, doc -> begin - @info "Testing LS functionality at all offsets" file=doc._uri + @info "Testing LS functionality at all offsets" file = doc._uri on_all_offsets(doc, function (doc, offset) tdi = LanguageServer.TextDocumentIdentifier(doc._uri) pos = LanguageServer.Position(LanguageServer.get_position_at(doc, offset)...) @@ -82,8 +82,8 @@ end end) on_all_docs(server, doc -> begin - symbols=length(LanguageServer.textDocument_documentSymbol_request(LanguageServer.DocumentSymbolParams(LanguageServer.TextDocumentIdentifier(doc._uri),missing, missing), server, server.jr_endpoint)) - @info "Found $symbols symbols" file=doc._uri + symbols = length(LanguageServer.textDocument_documentSymbol_request(LanguageServer.DocumentSymbolParams(LanguageServer.TextDocumentIdentifier(doc._uri), missing, missing), server, server.jr_endpoint)) + @info "Found $symbols symbols" file = doc._uri end) LanguageServer.workspace_symbol_request(LanguageServer.WorkspaceSymbolParams("", missing, missing), server, server.jr_endpoint) diff --git a/test/test_document.jl b/test/test_document.jl index 6c8320c68..6574fe69f 100644 --- a/test/test_document.jl +++ b/test/test_document.jl @@ -46,14 +46,14 @@ d5 = Document("untitled", s5, false) s6 = "\n" d6 = Document("untitled", s6, false) -@test get_line_offsets(d6) == [0,1] +@test get_line_offsets(d6) == [0, 1] @testset "applytextdocumentchanges" begin doc = LS.Document("file:///example/path/example.jl", "function foo()", false) c1 = LS.TextDocumentContentChangeEvent(LS.Range(LS.Position(0, 14), LS.Position(0, 14)), - 0, "\n") + 0, "\n") c2 = LS.TextDocumentContentChangeEvent(LS.Range(LS.Position(1, 0), LS.Position(1, 0)), - 0, " ") + 0, " ") c3 = LS.TextDocumentContentChangeEvent(missing, missing, "println(\"Hello World\")") LS.applytextdocumentchanges(doc, c1) diff --git a/test/test_intellisense.jl b/test/test_intellisense.jl index a2e51128b..57b7638ea 100644 --- a/test/test_intellisense.jl +++ b/test/test_intellisense.jl @@ -43,4 +43,4 @@ res = LanguageServer.textDocument_signatureHelp_request(LanguageServer.TextDocum @test res.activeParameter == 1 res = LanguageServer.textDocument_signatureHelp_request(LanguageServer.TextDocumentPositionParams(LanguageServer.TextDocumentIdentifier("testdoc"), LanguageServer.Position(14, 6)), server, nothing) -@test res.activeParameter == 2 \ No newline at end of file +@test res.activeParameter == 2