Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
bung87 committed Sep 16, 2023
1 parent 4c66dfb commit 84ceb8c
Show file tree
Hide file tree
Showing 7 changed files with 6 additions and 210 deletions.
6 changes: 1 addition & 5 deletions compiler/tools/suggest.nim
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,7 @@ proc symToSuggest(g: ModuleGraph; s: PSym, isLocal: bool, section: IdeCmd, info:
else:
result.forth = ""
when defined(nimsuggest) and not defined(noDocgen) and not defined(leanCompiler):
<<<<<<< HEAD
if section in {ideSug, ideCon, ideDef, ideChk}:
=======
if section in {ideCon, ideDef, ideChk}:
>>>>>>> 19a04042ad (tool: LSP support)
result.doc = extractDocComment(g, s)
let infox =
if useSuppliedInfo or section in {ideUse, ideHighlight, ideOutline}:
Expand Down Expand Up @@ -468,7 +464,7 @@ proc inCheckpoint*(current, trackPos: TLineInfo): TCheckPointResult =

proc isTracked*(current, trackPos: TLineInfo, tokenLen: int): bool =
if current.fileIndex == trackPos.fileIndex and
current.line == trackPos.line:
current.line == trackPos.line:
let col = trackPos.col
if col >= current.col and col <= current.col + tokenLen - 1:
return true
Expand Down
156 changes: 2 additions & 154 deletions nimlsp/nimlsp.nim
Original file line number Diff line number Diff line change
@@ -1,46 +1,15 @@
import std/[algorithm, hashes, os, osproc, sets,
<<<<<<< HEAD
streams, strformat, strutils, tables]
=======
streams, strformat, strutils, tables, uri]
>>>>>>> 19a04042ad (tool: LSP support)

import nimlsppkg/[baseprotocol, logger, suggestlib, utfmapping]
include nimlsppkg/[messages, messageenums]


const
<<<<<<< HEAD
# This is used to explicitly set the default source path
explicitSourcePath {.strdefine.} = getCurrentCompilerExe().parentDir.parentDir

var nimpath = explicitSourcePath
=======
version = block:
var version = "0.0.0"
let nimbleFile = staticRead(currentSourcePath().parentDir / "nimlsp.nimble")
for line in nimbleFile.splitLines:
let keyval = line.split('=')
if keyval.len == 2:
if keyval[0].strip == "version":
version = keyval[1].strip(chars = Whitespace + {'"'})
break
version
# This is used to explicitly set the default source path
explicitSourcePath {.strdefine.} = getCurrentCompilerExe().parentDir.parentDir

type
UriParseError* = object of Defect
uri: string

var nimpath = explicitSourcePath

infoLog("Version: ", version)
infoLog("explicitSourcePath: ", explicitSourcePath)
for i in 1..paramCount():
infoLog("Argument ", i, ": ", paramStr(i))

>>>>>>> 19a04042ad (tool: LSP support)
var
gotShutdown = false
initialized = false
Expand Down Expand Up @@ -84,58 +53,6 @@ template textDocumentNotification(message: typed; kind: typed; name, body: untyp
else:
debugLog("Unable to parse data as ", kind)

<<<<<<< HEAD
=======
proc pathToUri(path: string): string =
# This is a modified copy of encodeUrl in the uri module. This doesn't encode
# the / character, meaning a full file path can be passed in without breaking
# it.
result = newStringOfCap(path.len + path.len shr 2) # assume 12% non-alnum-chars
when defined(windows):
result.add '/'
for c in path:
case c
# https://tools.ietf.org/html/rfc3986#section-2.3
of 'a'..'z', 'A'..'Z', '0'..'9', '-', '.', '_', '~', '/': result.add c
of '\\':
when defined(windows):
result.add '/'
else:
result.add '%'
result.add toHex(ord(c), 2)
else:
result.add '%'
result.add toHex(ord(c), 2)

proc uriToPath(uri: string): string =
## Convert an RFC 8089 file URI to a native, platform-specific, absolute path.
#let startIdx = when defined(windows): 8 else: 7
#normalizedPath(uri[startIdx..^1])
let parsed = uri.parseUri
if parsed.scheme != "file":
var e = newException(UriParseError, &"Invalid scheme: {parsed.scheme}, only \"file\" is supported")
e.uri = uri
raise e
if parsed.hostname != "":
var e = newException(UriParseError, &"Invalid hostname: {parsed.hostname}, only empty hostname is supported")
e.uri = uri
raise e
return normalizedPath(
when defined(windows):
parsed.path[1..^1]
else:
parsed.path).decodeUrl

proc parseId(node: JsonNode): string =
if node == nil: return
if node.kind == JString:
node.getStr
elif node.kind == JInt:
$node.getInt
else:
""

>>>>>>> 19a04042ad (tool: LSP support)
proc respond(outs: Stream, request: JsonNode, data: JsonNode) =
let resp = create(ResponseMessage, "2.0", parseId(request["id"]), some(data), none(ResponseError)).JsonNode
outs.sendJson resp
Expand Down Expand Up @@ -192,29 +109,6 @@ proc getProjectFile(file: string): string =
template getNimsuggest(fileuri: string): Nimsuggest =
projectFiles[openFiles[fileuri].projectFile].nimsuggest

<<<<<<< HEAD
=======
if paramCount() == 1:
case paramStr(1):
of "--help":
echo "Usage: nimlsp [OPTION | PATH]\n"
echo "--help, shows this message"
echo "--version, shows only the version"
echo "PATH, path to the Nim source directory, defaults to \"", nimpath, "\""
quit 0
of "--version":
echo "nimlsp v", version
when defined(debugLogging): echo "Compiled with debug logging"
when defined(debugCommunication): echo "Compiled with communication logging"
quit 0
else: nimpath = expandFilename(paramStr(1))
if not fileExists(nimpath / "config/nim.cfg"):
stderr.write &"""Unable to find "config/nim.cfg" in "{nimpath
}". Supply the Nim project folder by adding it as an argument.
"""
quit 1

>>>>>>> 19a04042ad (tool: LSP support)
proc checkVersion(outs: Stream) =
let
nimoutputTuple =
Expand All @@ -229,7 +123,6 @@ proc checkVersion(outs: Stream) =
if version != NimVersion:
outs.notify("window/showMessage", create(ShowMessageParams, MessageType.Warning.int, message = "Current Nim version does not match the one NimLSP is built against " & version & " != " & NimVersion).JsonNode)

<<<<<<< HEAD
proc createMarkupContent(label: string; content: string): MarkupContent =
let label = "```nim\n" & label & "\n```\n"
var
Expand Down Expand Up @@ -269,8 +162,6 @@ proc createMarkupContent(label: string; content: string): MarkupContent =
)
result = create(MarkupContent, "markdown", label & c)

=======
>>>>>>> 19a04042ad (tool: LSP support)
proc main(ins: Stream, outs: Stream) =
checkVersion(outs)
var message: JsonNode
Expand Down Expand Up @@ -403,24 +294,9 @@ proc main(ins: Stream, outs: Stream) =
create(Position, req.rawLine, req.rawChar),
create(Position, req.rawLine, req.rawChar + suggestions[0].qualifiedPath[^1].len)
))
<<<<<<< HEAD
markupContent = createMarkupContent(label, suggestions[0].doc)
resp = create(Hover, markupContent, rangeopt).JsonNode
outs.respond(message, resp)
=======
markedString = create(MarkedStringOption, "nim", label)
if suggestions[0].doc != "":
resp = create(Hover,
@[
markedString,
create(MarkedStringOption, "", suggestions[0].doc),
],
rangeopt
).JsonNode
else:
resp = create(Hover, markedString, rangeopt).JsonNode;
outs.respond(message, resp)
>>>>>>> 19a04042ad (tool: LSP support)
of "textDocument/references":
textDocumentRequest(message, ReferenceParams, req):
debugLog "Running equivalent of: use ", req.fileuri, " ", req.filestash, "(",
Expand Down Expand Up @@ -517,18 +393,14 @@ proc main(ins: Stream, outs: Stream) =
debugLog "Found outlines: ", syms[0..<min(syms.len, 10)],
if syms.len > 10: &" and {syms.len-10} more" else: ""
var resp: JsonNode
<<<<<<< HEAD
var flags = newSeq[int]()
=======
>>>>>>> 19a04042ad (tool: LSP support)
if syms.len == 0:
resp = newJNull()
else:
resp = newJarray()
for sym in syms.sortedByIt((it.line,it.column,it.quality)):
if sym.qualifiedPath.len != 2:
continue
<<<<<<< HEAD
flags.setLen(0)
for f in sym.flags:
flags.add f.int
Expand All @@ -545,25 +417,8 @@ proc main(ins: Stream, outs: Stream) =
create(Position, sym.line-1, sym.column),
create(Position, sym.line-1, sym.column + sym.tokenLen)
),
none(seq[DocumentSymbol])
=======
resp.add create(
SymbolInformation,
sym.qualifiedPath[^1],
nimSymToLSPKind(sym.symKind).int,
some(false),
create(Location,
"file://" & pathToUri(sym.filepath),
create(Range,
create(Position, sym.line-1, sym.column),
create(Position, sym.line-1, sym.column + sym.qualifiedPath[^1].len)
)
),
none(string)
>>>>>>> 19a04042ad (tool: LSP support)
).JsonNode
outs.respond(message, resp)
of "textDocument/signatureHelp":
none(seq[DocumentSymbol])).JsonNode
outs.respond(message, resp)
textDocumentRequest(message, TextDocumentPositionParams, req):
debugLog "Running equivalent of: con ", req.filePath, " ", req.filestash, "(",
req.rawLine + 1, ":",
Expand Down Expand Up @@ -753,7 +608,6 @@ proc main(ins: Stream, outs: Stream) =
warnLog "Got exception: ", e.msg
continue

<<<<<<< HEAD
when isMainModule:
infoLog("explicitSourcePath: ", explicitSourcePath)
for i in 1..paramCount():
Expand All @@ -777,9 +631,3 @@ when isMainModule:
ins = newFileStream(stdin)
outs = newFileStream(stdout)
main(ins, outs)
=======
var
ins = newFileStream(stdin)
outs = newFileStream(stdout)
main(ins, outs)
>>>>>>> 19a04042ad (tool: LSP support)
7 changes: 0 additions & 7 deletions nimlsp/nimlsppkg/baseprotocol.nim
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import std/[json, parseutils, streams, strformat,
<<<<<<< HEAD
strutils, os]
from std/uri import decodeUrl, parseUri
=======
strutils]
>>>>>>> 19a04042ad (tool: LSP support)
when defined(debugCommunication):
import logger

Expand All @@ -14,7 +10,6 @@ type
MalformedFrame* = object of BaseProtocolError
UnsupportedEncoding* = object of BaseProtocolError

<<<<<<< HEAD
UriParseError* = object of Defect
uri*: string

Expand Down Expand Up @@ -67,8 +62,6 @@ proc parseId*(node: JsonNode): string =
else:
""

=======
>>>>>>> 19a04042ad (tool: LSP support)
proc skipWhitespace(x: string, pos: int): int =
result = pos
while result < x.len and x[result] in Whitespace:
Expand Down
3 changes: 0 additions & 3 deletions nimlsp/nimlsppkg/messageenums.nim
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,6 @@ type
Text = 1,
Read = 2,
Write = 3
<<<<<<< HEAD

SymbolTag* {.pure.} = enum
Deprecated = 1
=======
>>>>>>> 19a04042ad (tool: LSP support)
7 changes: 0 additions & 7 deletions nimlsp/nimlsppkg/messages.nim
Original file line number Diff line number Diff line change
Expand Up @@ -468,11 +468,7 @@ jsonSchema:
triggerCharacters ?: string[]
resolveProvider ?: bool

<<<<<<< HEAD
MarkedStringOption: # deprecated
=======
MarkedStringOption:
>>>>>>> 19a04042ad (tool: LSP support)
language: string
value: string

Expand Down Expand Up @@ -517,7 +513,6 @@ jsonSchema:
location: Location
containerName ?: string

<<<<<<< HEAD
DocumentSymbol:
name: string
detail ?: string
Expand All @@ -527,8 +522,6 @@ jsonSchema:
selectionRange: Range
children ?: DocumentSymbol[]

=======
>>>>>>> 19a04042ad (tool: LSP support)
CodeActionParams:
textDocument: TextDocumentIdentifier
"range": Range
Expand Down
34 changes: 3 additions & 31 deletions nimlsp/nimlsppkg/nimsuggest.nim
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,11 @@ import
compiler/front/[
options,
optionsprocessor,
# commands,
msgs,
cmdlinehelper,
cli_reporter
],
compiler/utils/[
# prefixmatches,
pathutils
],
compiler/sem/[
Expand All @@ -42,7 +40,7 @@ from compiler/ast/reports import Report,

from compiler/front/main import customizeForBackend

from compiler/tools/suggest import isTracked, listUsages, suggestSym, `$`
from compiler/tools/suggest import findTrackedSym, executeCmd, listUsages, suggestSym, `$`

export Suggest
export IdeCmd
Expand Down Expand Up @@ -126,19 +124,6 @@ proc initNimSuggest*(project: string, nimPath: string = ""): NimSuggest =
retval.doStopCompile = proc (): bool = false
return NimSuggest(graph: retval, idle: 0, cachedMsgs: @[])

proc findNode(n: PNode; trackPos: TLineInfo): PSym =
if n.kind == nkSym:
if isTracked(n.info, trackPos, n.sym.name.s.len): return n.sym
else:
for i in 0 ..< safeLen(n):
let res = findNode(n[i], trackPos)
if res != nil: return res

proc symFromInfo(graph: ModuleGraph; trackPos: TLineInfo; moduleIdx: FileIndex): PSym =
let m = graph.getModule(moduleIdx)
if m != nil and m.ast != nil:
result = findNode(m.ast, trackPos)

proc getSymNode(node: ParsedNode): ParsedNode =
result = node
if result.kind == pnkPostfix:
Expand Down Expand Up @@ -262,22 +247,9 @@ proc executeNoHooks(cmd: IdeCmd, file, dirtyfile: AbsoluteFile, line, col: int,
needCompile = false

if needCompile:
if not isKnownFile:
moduleIdx = dirtyIdx
# stderr.writeLine "Compile unknown module: " & toFullPath(conf, moduleIdx)
discard graph.compileModule(moduleIdx, {})
else:
moduleIdx = graph.parentModule(dirtyIdx)
# stderr.writeLine "Compile known module: " & toFullPath(conf, moduleIdx)
graph.markDirty dirtyIdx
graph.markClientsDirty dirtyIdx
# partially recompiling the project means that that VM and JIT state
# would become stale, which we prevent by discarding all of it:
graph.vm = nil
if conf.ideCmd != ideMod:
discard graph.compileModule(moduleIdx, {})
executeCmd(cmd, file, dirtyfile, line, col, graph)
if conf.ideCmd in {ideUse, ideDus}:
let u = graph.symFromInfo(conf.m.trackPos, moduleIdx)
let u = graph.findTrackedSym()
if u != nil:
listUsages(graph, u)
else:
Expand Down
Loading

0 comments on commit 84ceb8c

Please sign in to comment.