Skip to content

Commit f616a11

Browse files
committed
refactor
1 parent 4c66dfb commit f616a11

File tree

7 files changed

+4
-207
lines changed

7 files changed

+4
-207
lines changed

compiler/tools/suggest.nim

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -194,11 +194,7 @@ proc symToSuggest(g: ModuleGraph; s: PSym, isLocal: bool, section: IdeCmd, info:
194194
else:
195195
result.forth = ""
196196
when defined(nimsuggest) and not defined(noDocgen) and not defined(leanCompiler):
197-
<<<<<<< HEAD
198197
if section in {ideSug, ideCon, ideDef, ideChk}:
199-
=======
200-
if section in {ideCon, ideDef, ideChk}:
201-
>>>>>>> 19a04042ad (tool: LSP support)
202198
result.doc = extractDocComment(g, s)
203199
let infox =
204200
if useSuppliedInfo or section in {ideUse, ideHighlight, ideOutline}:
@@ -468,7 +464,7 @@ proc inCheckpoint*(current, trackPos: TLineInfo): TCheckPointResult =
468464

469465
proc isTracked*(current, trackPos: TLineInfo, tokenLen: int): bool =
470466
if current.fileIndex == trackPos.fileIndex and
471-
current.line == trackPos.line:
467+
current.line == trackPos.line:
472468
let col = trackPos.col
473469
if col >= current.col and col <= current.col + tokenLen - 1:
474470
return true

nimlsp/nimlsp.nim

Lines changed: 0 additions & 151 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,15 @@
11
import std/[algorithm, hashes, os, osproc, sets,
2-
<<<<<<< HEAD
32
streams, strformat, strutils, tables]
4-
=======
5-
streams, strformat, strutils, tables, uri]
6-
>>>>>>> 19a04042ad (tool: LSP support)
73

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

117

128
const
13-
<<<<<<< HEAD
14-
# This is used to explicitly set the default source path
15-
explicitSourcePath {.strdefine.} = getCurrentCompilerExe().parentDir.parentDir
16-
17-
var nimpath = explicitSourcePath
18-
=======
19-
version = block:
20-
var version = "0.0.0"
21-
let nimbleFile = staticRead(currentSourcePath().parentDir / "nimlsp.nimble")
22-
for line in nimbleFile.splitLines:
23-
let keyval = line.split('=')
24-
if keyval.len == 2:
25-
if keyval[0].strip == "version":
26-
version = keyval[1].strip(chars = Whitespace + {'"'})
27-
break
28-
version
299
# This is used to explicitly set the default source path
3010
explicitSourcePath {.strdefine.} = getCurrentCompilerExe().parentDir.parentDir
3111

32-
type
33-
UriParseError* = object of Defect
34-
uri: string
35-
3612
var nimpath = explicitSourcePath
37-
38-
infoLog("Version: ", version)
39-
infoLog("explicitSourcePath: ", explicitSourcePath)
40-
for i in 1..paramCount():
41-
infoLog("Argument ", i, ": ", paramStr(i))
42-
43-
>>>>>>> 19a04042ad (tool: LSP support)
4413
var
4514
gotShutdown = false
4615
initialized = false
@@ -84,58 +53,6 @@ template textDocumentNotification(message: typed; kind: typed; name, body: untyp
8453
else:
8554
debugLog("Unable to parse data as ", kind)
8655

87-
<<<<<<< HEAD
88-
=======
89-
proc pathToUri(path: string): string =
90-
# This is a modified copy of encodeUrl in the uri module. This doesn't encode
91-
# the / character, meaning a full file path can be passed in without breaking
92-
# it.
93-
result = newStringOfCap(path.len + path.len shr 2) # assume 12% non-alnum-chars
94-
when defined(windows):
95-
result.add '/'
96-
for c in path:
97-
case c
98-
# https://tools.ietf.org/html/rfc3986#section-2.3
99-
of 'a'..'z', 'A'..'Z', '0'..'9', '-', '.', '_', '~', '/': result.add c
100-
of '\\':
101-
when defined(windows):
102-
result.add '/'
103-
else:
104-
result.add '%'
105-
result.add toHex(ord(c), 2)
106-
else:
107-
result.add '%'
108-
result.add toHex(ord(c), 2)
109-
110-
proc uriToPath(uri: string): string =
111-
## Convert an RFC 8089 file URI to a native, platform-specific, absolute path.
112-
#let startIdx = when defined(windows): 8 else: 7
113-
#normalizedPath(uri[startIdx..^1])
114-
let parsed = uri.parseUri
115-
if parsed.scheme != "file":
116-
var e = newException(UriParseError, &"Invalid scheme: {parsed.scheme}, only \"file\" is supported")
117-
e.uri = uri
118-
raise e
119-
if parsed.hostname != "":
120-
var e = newException(UriParseError, &"Invalid hostname: {parsed.hostname}, only empty hostname is supported")
121-
e.uri = uri
122-
raise e
123-
return normalizedPath(
124-
when defined(windows):
125-
parsed.path[1..^1]
126-
else:
127-
parsed.path).decodeUrl
128-
129-
proc parseId(node: JsonNode): string =
130-
if node == nil: return
131-
if node.kind == JString:
132-
node.getStr
133-
elif node.kind == JInt:
134-
$node.getInt
135-
else:
136-
""
137-
138-
>>>>>>> 19a04042ad (tool: LSP support)
13956
proc respond(outs: Stream, request: JsonNode, data: JsonNode) =
14057
let resp = create(ResponseMessage, "2.0", parseId(request["id"]), some(data), none(ResponseError)).JsonNode
14158
outs.sendJson resp
@@ -192,29 +109,6 @@ proc getProjectFile(file: string): string =
192109
template getNimsuggest(fileuri: string): Nimsuggest =
193110
projectFiles[openFiles[fileuri].projectFile].nimsuggest
194111

195-
<<<<<<< HEAD
196-
=======
197-
if paramCount() == 1:
198-
case paramStr(1):
199-
of "--help":
200-
echo "Usage: nimlsp [OPTION | PATH]\n"
201-
echo "--help, shows this message"
202-
echo "--version, shows only the version"
203-
echo "PATH, path to the Nim source directory, defaults to \"", nimpath, "\""
204-
quit 0
205-
of "--version":
206-
echo "nimlsp v", version
207-
when defined(debugLogging): echo "Compiled with debug logging"
208-
when defined(debugCommunication): echo "Compiled with communication logging"
209-
quit 0
210-
else: nimpath = expandFilename(paramStr(1))
211-
if not fileExists(nimpath / "config/nim.cfg"):
212-
stderr.write &"""Unable to find "config/nim.cfg" in "{nimpath
213-
}". Supply the Nim project folder by adding it as an argument.
214-
"""
215-
quit 1
216-
217-
>>>>>>> 19a04042ad (tool: LSP support)
218112
proc checkVersion(outs: Stream) =
219113
let
220114
nimoutputTuple =
@@ -229,7 +123,6 @@ proc checkVersion(outs: Stream) =
229123
if version != NimVersion:
230124
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)
231125

232-
<<<<<<< HEAD
233126
proc createMarkupContent(label: string; content: string): MarkupContent =
234127
let label = "```nim\n" & label & "\n```\n"
235128
var
@@ -269,8 +162,6 @@ proc createMarkupContent(label: string; content: string): MarkupContent =
269162
)
270163
result = create(MarkupContent, "markdown", label & c)
271164

272-
=======
273-
>>>>>>> 19a04042ad (tool: LSP support)
274165
proc main(ins: Stream, outs: Stream) =
275166
checkVersion(outs)
276167
var message: JsonNode
@@ -403,24 +294,9 @@ proc main(ins: Stream, outs: Stream) =
403294
create(Position, req.rawLine, req.rawChar),
404295
create(Position, req.rawLine, req.rawChar + suggestions[0].qualifiedPath[^1].len)
405296
))
406-
<<<<<<< HEAD
407297
markupContent = createMarkupContent(label, suggestions[0].doc)
408298
resp = create(Hover, markupContent, rangeopt).JsonNode
409299
outs.respond(message, resp)
410-
=======
411-
markedString = create(MarkedStringOption, "nim", label)
412-
if suggestions[0].doc != "":
413-
resp = create(Hover,
414-
@[
415-
markedString,
416-
create(MarkedStringOption, "", suggestions[0].doc),
417-
],
418-
rangeopt
419-
).JsonNode
420-
else:
421-
resp = create(Hover, markedString, rangeopt).JsonNode;
422-
outs.respond(message, resp)
423-
>>>>>>> 19a04042ad (tool: LSP support)
424300
of "textDocument/references":
425301
textDocumentRequest(message, ReferenceParams, req):
426302
debugLog "Running equivalent of: use ", req.fileuri, " ", req.filestash, "(",
@@ -517,21 +393,16 @@ proc main(ins: Stream, outs: Stream) =
517393
debugLog "Found outlines: ", syms[0..<min(syms.len, 10)],
518394
if syms.len > 10: &" and {syms.len-10} more" else: ""
519395
var resp: JsonNode
520-
<<<<<<< HEAD
521396
var flags = newSeq[int]()
522-
=======
523-
>>>>>>> 19a04042ad (tool: LSP support)
524397
if syms.len == 0:
525398
resp = newJNull()
526399
else:
527400
resp = newJarray()
528401
for sym in syms.sortedByIt((it.line,it.column,it.quality)):
529402
if sym.qualifiedPath.len != 2:
530403
continue
531-
<<<<<<< HEAD
532404
flags.setLen(0)
533405
for f in sym.flags:
534-
flags.add f.int
535406
resp.add create(DocumentSymbol,
536407
sym.qualifiedPath[^1],
537408
some(symKindToString(sym.symKind)),
@@ -549,21 +420,6 @@ proc main(ins: Stream, outs: Stream) =
549420
=======
550421
resp.add create(
551422
SymbolInformation,
552-
sym.qualifiedPath[^1],
553-
nimSymToLSPKind(sym.symKind).int,
554-
some(false),
555-
create(Location,
556-
"file://" & pathToUri(sym.filepath),
557-
create(Range,
558-
create(Position, sym.line-1, sym.column),
559-
create(Position, sym.line-1, sym.column + sym.qualifiedPath[^1].len)
560-
)
561-
),
562-
none(string)
563-
>>>>>>> 19a04042ad (tool: LSP support)
564-
).JsonNode
565-
outs.respond(message, resp)
566-
of "textDocument/signatureHelp":
567423
textDocumentRequest(message, TextDocumentPositionParams, req):
568424
debugLog "Running equivalent of: con ", req.filePath, " ", req.filestash, "(",
569425
req.rawLine + 1, ":",
@@ -753,7 +609,6 @@ proc main(ins: Stream, outs: Stream) =
753609
warnLog "Got exception: ", e.msg
754610
continue
755611

756-
<<<<<<< HEAD
757612
when isMainModule:
758613
infoLog("explicitSourcePath: ", explicitSourcePath)
759614
for i in 1..paramCount():
@@ -777,9 +632,3 @@ when isMainModule:
777632
ins = newFileStream(stdin)
778633
outs = newFileStream(stdout)
779634
main(ins, outs)
780-
=======
781-
var
782-
ins = newFileStream(stdin)
783-
outs = newFileStream(stdout)
784-
main(ins, outs)
785-
>>>>>>> 19a04042ad (tool: LSP support)

nimlsp/nimlsppkg/baseprotocol.nim

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
import std/[json, parseutils, streams, strformat,
2-
<<<<<<< HEAD
32
strutils, os]
43
from std/uri import decodeUrl, parseUri
5-
=======
6-
strutils]
7-
>>>>>>> 19a04042ad (tool: LSP support)
84
when defined(debugCommunication):
95
import logger
106

@@ -14,7 +10,6 @@ type
1410
MalformedFrame* = object of BaseProtocolError
1511
UnsupportedEncoding* = object of BaseProtocolError
1612

17-
<<<<<<< HEAD
1813
UriParseError* = object of Defect
1914
uri*: string
2015

@@ -67,8 +62,6 @@ proc parseId*(node: JsonNode): string =
6762
else:
6863
""
6964

70-
=======
71-
>>>>>>> 19a04042ad (tool: LSP support)
7265
proc skipWhitespace(x: string, pos: int): int =
7366
result = pos
7467
while result < x.len and x[result] in Whitespace:

nimlsp/nimlsppkg/messageenums.nim

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,6 @@ type
112112
Text = 1,
113113
Read = 2,
114114
Write = 3
115-
<<<<<<< HEAD
116115

117116
SymbolTag* {.pure.} = enum
118117
Deprecated = 1
119-
=======
120-
>>>>>>> 19a04042ad (tool: LSP support)

nimlsp/nimlsppkg/messages.nim

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -468,11 +468,7 @@ jsonSchema:
468468
triggerCharacters ?: string[]
469469
resolveProvider ?: bool
470470

471-
<<<<<<< HEAD
472471
MarkedStringOption: # deprecated
473-
=======
474-
MarkedStringOption:
475-
>>>>>>> 19a04042ad (tool: LSP support)
476472
language: string
477473
value: string
478474

@@ -517,7 +513,6 @@ jsonSchema:
517513
location: Location
518514
containerName ?: string
519515

520-
<<<<<<< HEAD
521516
DocumentSymbol:
522517
name: string
523518
detail ?: string
@@ -527,8 +522,6 @@ jsonSchema:
527522
selectionRange: Range
528523
children ?: DocumentSymbol[]
529524

530-
=======
531-
>>>>>>> 19a04042ad (tool: LSP support)
532525
CodeActionParams:
533526
textDocument: TextDocumentIdentifier
534527
"range": Range

nimlsp/nimlsppkg/nimsuggest.nim

Lines changed: 3 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,11 @@ import
2020
compiler/front/[
2121
options,
2222
optionsprocessor,
23-
# commands,
2423
msgs,
2524
cmdlinehelper,
2625
cli_reporter
2726
],
2827
compiler/utils/[
29-
# prefixmatches,
3028
pathutils
3129
],
3230
compiler/sem/[
@@ -42,7 +40,7 @@ from compiler/ast/reports import Report,
4240

4341
from compiler/front/main import customizeForBackend
4442

45-
from compiler/tools/suggest import isTracked, listUsages, suggestSym, `$`
43+
from compiler/tools/suggest import findTrackedSym, executeCmd, listUsages, suggestSym, `$`
4644

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

129-
proc findNode(n: PNode; trackPos: TLineInfo): PSym =
130-
if n.kind == nkSym:
131-
if isTracked(n.info, trackPos, n.sym.name.s.len): return n.sym
132-
else:
133-
for i in 0 ..< safeLen(n):
134-
let res = findNode(n[i], trackPos)
135-
if res != nil: return res
136-
137-
proc symFromInfo(graph: ModuleGraph; trackPos: TLineInfo; moduleIdx: FileIndex): PSym =
138-
let m = graph.getModule(moduleIdx)
139-
if m != nil and m.ast != nil:
140-
result = findNode(m.ast, trackPos)
141-
142127
proc getSymNode(node: ParsedNode): ParsedNode =
143128
result = node
144129
if result.kind == pnkPostfix:
@@ -262,22 +247,9 @@ proc executeNoHooks(cmd: IdeCmd, file, dirtyfile: AbsoluteFile, line, col: int,
262247
needCompile = false
263248

264249
if needCompile:
265-
if not isKnownFile:
266-
moduleIdx = dirtyIdx
267-
# stderr.writeLine "Compile unknown module: " & toFullPath(conf, moduleIdx)
268-
discard graph.compileModule(moduleIdx, {})
269-
else:
270-
moduleIdx = graph.parentModule(dirtyIdx)
271-
# stderr.writeLine "Compile known module: " & toFullPath(conf, moduleIdx)
272-
graph.markDirty dirtyIdx
273-
graph.markClientsDirty dirtyIdx
274-
# partially recompiling the project means that that VM and JIT state
275-
# would become stale, which we prevent by discarding all of it:
276-
graph.vm = nil
277-
if conf.ideCmd != ideMod:
278-
discard graph.compileModule(moduleIdx, {})
250+
executeCmd(cmd, file, dirtyfile, line, col, graph)
279251
if conf.ideCmd in {ideUse, ideDus}:
280-
let u = graph.symFromInfo(conf.m.trackPos, moduleIdx)
252+
let u = graph.findTrackedSym()
281253
if u != nil:
282254
listUsages(graph, u)
283255
else:

0 commit comments

Comments
 (0)