Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
b1b4b54
nimsuggest2 poc
nitely Oct 13, 2026
fe81d9e
chk from root
nitely Oct 17, 2026
de9eed6
nif freshness check
nitely Oct 17, 2026
289651e
support unknown files
nitely Oct 21, 2026
5a77a64
add `--parallelBuild` flag
nitely Oct 22, 2026
73548ac
nimbus-eth2 speed ups
nitely Oct 26, 2026
dec4bfe
chk unknown files support
nitely Oct 26, 2026
e0d8a81
check cache moved first
nitely Oct 26, 2026
6451bfa
suffix ns report file
nitely Oct 26, 2026
c8497b4
stale NIFs after a failed nim ns
nitely Oct 26, 2026
dd0f83b
more unknown files / multi root fixes
nitely Oct 28, 2026
00a7d77
icfailed report
nitely Nov 10, 2026
eddd344
define nimsuggest in `nim ns`
nitely Nov 13, 2026
25f1dbf
rebase fixups
nitely Nov 13, 2026
1580723
pin last nimony
nitely Nov 13, 2026
80c0ec3
collectBifStrLits -> loadSemDeps
nitely Nov 16, 2026
35e71a6
support multiple projects cmd args
nitely Nov 19, 2026
1029782
search field uses in all modules
nitely Nov 19, 2026
9dd645c
fix find-usages
nitely Nov 20, 2026
e32e76c
use nimsuggest2 working dir for nim ns
nitely Nov 20, 2026
4d025dd
fix find usages
nitely Nov 20, 2026
2c1d1ff
comment clean up
nitely Nov 25, 2026
77b0490
sort find use result
nitely Nov 25, 2026
4a65663
fix find usage in dirty file
nitely Nov 25, 2026
24d3547
use sighash
nitely Nov 25, 2026
dccc801
make chk return full stack trace error lines for unhandled exceptions
nitely Dec 3, 2026
f9fde24
oops
nitely Dec 3, 2026
81096c1
chk includes import modules with errors
nitely Dec 3, 2026
7bdc03b
more tests
nitely Dec 3, 2026
a05fc3f
fix
nitely Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion compiler/ast2nif.nim
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,13 @@ proc stripFieldMarker(rawName: string): string {.inline.} =
else:
rawName[0 ..< rawName.len - FieldMarker.len]

proc fieldNifName*(field: PSym): string =
## The NIF name `toNifSymName` gives the object field `field`.
result = field.name.s
result.add (if sfCursor in field.flagsImpl: CursorFieldMarker else: FieldMarker)
result.add '.'
result.addInt field.positionImpl

proc isFieldNifName*(name: string): bool {.inline.} =
## True for an object field's local NIF name `<ident>`f.<disamb>` (see
## `FieldMarker`): no module suffix, marker on the ident.
Expand Down Expand Up @@ -3308,6 +3315,7 @@ proc loadSymFromCursor(c: var DecodeContext; s: PSym; n: var Cursor; thisModule:
localSyms: var Table[string, PSym]) =
## Loads a symbol definition. The cursor must be positioned AT the opening
## `(sd` TagLit; `into` consumes the whole sdef including its closing `)`.
s.infoImpl = c.infos.oldLineInfo(n.info, cursorPool(n))
n.into:
expect n, SymbolDef
# ignore the symbol's name, we have already used it to create this PSym instance!
Expand Down Expand Up @@ -3448,7 +3456,6 @@ proc loadSym*(c: var DecodeContext; s: PSym) =
extractLocalSymsFromTree(c, scanCursor, c.mods[symsModule].suffix, localSyms)

# Now parse the symbol definition with all local symbols pre-registered
s.infoImpl = c.infos.oldLineInfo(n.info, cursorPool(n))
# The `##` doc comment (if any) rides as a NIF comment on the sym def token;
# capture it before advancing, then restore it onto the loaded AST so that
# suggest's `extractDocComment` (findDocComment on `s.ast`) finds it.
Expand Down Expand Up @@ -4157,6 +4164,25 @@ proc tryResolveCompilerProc*(c: var DecodeContext; name: string; moduleFileIdx:
if sfCompilerProc in sym.flagsImpl:
return sym

proc nifSymsNamed*(c: var DecodeContext; module: FileIndex; ident: string): seq[PSym] =
## The symbols called `ident` that `module`'s NIF indexes, loaded; none
## when it has no NIF.
result = @[]
let suffix = moduleSuffix(c.infos.config, module)
if not fileExists(semanticFile(c.infos.config, suffix, ".s.bif").string): return
let m = c.mods[moduleId(c, suffix)]
let prefix = ident & "."
var names: seq[string] = @[]
for key, _ in m.index.pairs(m.buf):
if key.len > prefix.len and key.startsWith(prefix) and parseSymName(key).name == ident:
names.add key
# the loads below can grow `c.mods`, so resolve after the iteration
for name in names:
let sym = resolveSym(c, name, true)
if sym != nil:
loadSym(c, sym)
result.add sym

proc loadLogOp(c: var DecodeContext; logOps: var seq[LogEntry]; cur: var Cursor;
kind: LogEntryKind; op: TTypeAttachedOp; module: int) =
## Step 2 phase 2: read one `(rep* "key" sym)` from the resident-buffer cursor.
Expand Down
8 changes: 8 additions & 0 deletions compiler/commands.nim
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,7 @@ proc parseCommand*(command: string): Command =
of "ic": cmdIc # generate .build.nif for nifmake
of "icconfig": cmdIcConfig # produce the precompiled config artifact
of "track": cmdTrack # IDE goto-def / find-usages over `nim ic`'s NIF output
of "ns": cmdNs # IC frontend for nimsuggest2
else: cmdUnknown

proc setCmd*(conf: ConfigRef, cmd: Command) =
Expand Down Expand Up @@ -1008,6 +1009,13 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
let dir = processPath(conf, arg, info, notRelativeToProj=true)
if switch.normalize == "icsemdir": conf.icSemDir = dir
else: conf.icMainSemDir = dir
of "nsroot":
# `nim ns` only: another module to build as a root (ie: unknow file), like the project file.
# One that no longer exists is dropped.
expectArg(conf, switch, arg, pass, info)
if pass in {passCmd2, passPP} and fileExists(arg):
let root = canonicalizePath(conf, AbsoluteFile arg).string
if root notin conf.nsRoots: conf.nsRoots.add root
of "icmainmodule":
expectArg(conf, switch, arg, pass, info)
if arg notin conf.icMainModules: conf.icMainModules.add arg
Expand Down
83 changes: 74 additions & 9 deletions compiler/deps.nim
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ type
implicitNodeIds: seq[int] # node IDs of `--import`ed modules (conf.implicitImports);
# every ordinary module implicitly imports these, so each
# gets a dependency edge on them, exactly like system.nim
nsRootIds: seq[int] # `nim ns`: node IDs of the `--nsRoot` modules; unknown files support
scanningMain: bool # currently scanning the project main module's deps;
# makes `when isMainModule` conditions evaluate true
# only there (every other module is imported)
Expand Down Expand Up @@ -164,6 +165,11 @@ proc programStamp(file: string): string =
result = $info.lastWriteTime.toUnix & "." & $info.lastWriteTime.nanosecond &
" " & $info.size

proc projectError(c: DepContext; msg: string) =
## An error in the project. `nim ns` keeps going: nimsuggest2 reports those.
if c.config.cmd == cmdNs: localError(c.config, unknownLineInfo, msg)
else: rawMessage(c.config, errGenerated, msg)

proc runNifler(c: DepContext; nimFile: string): bool =
## Run nifler deps on a file if needed. Returns true on success.
## NOTE: the `setLastModificationTime` coordination below is a known hack; its
Expand Down Expand Up @@ -636,7 +642,7 @@ proc readDepsFile(c: var DepContext; pair: FilePair; current: Node) =
# `current.id == 0` is the project main (rootNode); restored on exit so the
# flag is correct for each parent frame between its child recursions.
let prevScanningMain = c.scanningMain
c.scanningMain = current.id == 0
c.scanningMain = current.id == 0 and c.config.cmd != cmdNs
defer: c.scanningMain = prevScanningMain

var s = nifstreams.open(depsPath)
Expand Down Expand Up @@ -819,8 +825,9 @@ proc includerSbifs*(conf: ConfigRef; targetFile: AbsoluteFile): seq[string] =
proc traverseDeps(c: var DepContext; pair: FilePair; current: Node) =
## Process a module: run nifler and read deps
if not runNifler(c, pair.nimFile):
rawMessage(c.config, errGenerated, "nifler failed for: " & pair.nimFile)
return
c.projectError("nifler failed for: " & pair.nimFile)
# `nim ns` keeps the imports of the module's last version that parsed.
if c.config.cmd != cmdNs or not fileExists(c.depsFile(pair)): return
readDepsFile(c, pair, current)

proc importPathsOf(n: PNode; res: var seq[string]) =
Expand Down Expand Up @@ -958,7 +965,7 @@ proc pruneDeadSpeculative(c: var DepContext) =
let n = c.nodes.len
if n == 0: return

var roots = @[0]
var roots = @[0] & c.nsRootIds
if c.systemNodeId >= 0: roots.add c.systemNodeId
for i in c.implicitNodeIds: roots.add i

Expand Down Expand Up @@ -995,7 +1002,7 @@ proc pruneDeadSpeculative(c: var DepContext) =
for i in 0 ..< n:
if hard[i] and c.nodes[i].missingHardImport.len > 0 and
not isCompilesProbe(c, c.nodes[i], c.nodes[i].missingHardImport):
rawMessage(c.config, errGenerated,
c.projectError(
c.nodes[i].files[0].nimFile & ": cannot open file: " &
c.nodes[i].missingHardImport)
reported = true
Expand Down Expand Up @@ -1087,6 +1094,7 @@ proc selectMainSemanticModules(c: DepContext) =
## An import cycle containing main is compiled together with its main role.
## Keep the whole group separate from imported versions shared by other programs.
c.config.icMainModules = @[]
if c.config.cmd == cmdNs: return
for comp in computeSCCs(c):
if 0 in comp:
for i in comp: c.config.icMainModules.add c.nodes[i].files[0].modname
Expand Down Expand Up @@ -1180,7 +1188,7 @@ proc computeForwardedArgs(c: DepContext): seq[string] =
"incremental", "ic", "symbolfiles", "genbif",
"icproject", "icpreparsedconfig", "icconfigout", "icgroup",
"icsemdir", "icmainsemdir", "icmainmodule",
"icbackendstage", "icbackendmodule", "ismainmodule",
"icbackendstage", "icbackendmodule", "ismainmodule", "nsroot",
"help", "h", "fullhelp", "version", "v", "advanced"]
var positionalArgs = 0
for a in commandLineParams():
Expand Down Expand Up @@ -1348,7 +1356,7 @@ proc generateFrontendBuildFile(c: DepContext; forwardedArgs: seq[string]): strin
# The root module (node 0) is the program's real entry point; mark it so
# `isMainModule` resolves to true only for it (every module otherwise gets
# `sfMainModule` for NIF writing under `nim m`).
if members[0] == 0:
if members[0] == 0 and c.config.cmd != cmdNs:
b.addStrLit "--isMainModule:on"
b.addStrLit "--nimcache:" & c.config.icMainSemDir.string
# For a real cycle, tell the compiler which modules form the group so it
Expand Down Expand Up @@ -2018,13 +2026,51 @@ proc allSemmed(c: DepContext): bool =
result = true
for _ in unsemmed(c): return false

proc failedToBuild(c: DepContext; node: Node): bool =
## Whether the module's rule failed: its `.edges.bif` stamp is missing or
## older than its source or one of the files it includes.
let stamp = c.edgesFile(node.files[0])
if not fileExists(stamp): return true
let written = getLastModificationTime(stamp)
for f in node.files:
if fileExists(f.nimFile) and written < getLastModificationTime(f.nimFile):
return true
false

proc reportToNimsuggest(c: DepContext; cacheDir: string; started: Time) =
## `nim ns`: writes the project's `nsReportName` in `cacheDir`, one line each
## for where the semantic NIFs are, the precompiled config, every module this
## run built (`icmodule:`), failed to build (`icfailed:`) or could not check
## (`icdeferred:`), so nimsuggest2 loads only NIFs nifmake built, the files
## each of those modules includes (`icinclude:`, after the module) and the
## `--nsRoot` modules (`icroot:`), so the next run builds them again. Its
## modification time is when this run started: a source newer than it changed
## after this run read it.
var lines = @["icsemdir:" & c.config.icSemDir.string,
"icconfig:" & c.config.icPreparsedConfig]
for node in c.nodes:
let kind =
if node.deferred: "icdeferred:"
elif c.failedToBuild(node): "icfailed:"
else: "icmodule:"
lines.add kind & node.files[0].nimFile
for i in 1 ..< node.files.len:
lines.add "icinclude:" & node.files[i].nimFile
for root in c.config.nsRoots:
if fileExists(root): lines.add "icroot:" & root
let report = cacheDir / nsReportName(c.config.projectFull.string)
writeFile(report & ".tmp", lines.join("\n"))
setLastModificationTime(report & ".tmp", started)
moveFile(report & ".tmp", report)

proc commandIc*(conf: ConfigRef; frontendOnly = false) =
## Main entry point for `nim ic`. With `frontendOnly` (used by `nim track` for
## IDE queries) it runs only Phase 1 — the incremental nifler + `nim m`
## frontend that writes every module's `.s.bif` — and skips the whole-program
## backend (`nim nifc` -> C -> link), which a goto-def / find-usages scan does
## not need.
when not defined(nimKochBootstrap):
let started = getTime()
let nifler = findNifler()
if nifler.len == 0:
rawMessage(conf, errGenerated, "nifler tool not found. Install nimony or add nifler to PATH.")
Expand Down Expand Up @@ -2164,6 +2210,22 @@ proc commandIc*(conf: ConfigRef; frontendOnly = false) =

# Process dependencies
traverseDeps(c, rootPair, rootNode)
# `nim ns`: the other roots are built like the project file, as ordinary
# modules nothing imports.
for root in conf.nsRoots:
if not fileExists(root): continue
let pair = c.toPair(root)
var id = c.processedModules.getOrDefault(pair.modname, -1)
if id == -1:
let node = Node(files: @[pair], id: c.nodes.len)
if c.systemNodeId >= 0: node.deps.add c.systemNodeId
if getsImplicitImports(c, pair.nimFile):
for impId in c.implicitNodeIds: node.deps.add impId
c.nodes.add node
c.processedModules[pair.modname] = node.id
id = node.id
traverseDeps(c, pair, node)
c.nsRootIds.add id
selectMainSemanticModules(c)

# Cached imports belong to this configuration, including when returning to
Expand Down Expand Up @@ -2237,7 +2299,8 @@ proc commandIc*(conf: ConfigRef; frontendOnly = false) =
if progress: " --progress:" & $frontendLo & ":" & $frontendHi
else: ""
inc round
let cmd = quoteShell(nifmake) & " run" & parallel & frontendProgress & " " &
let keepGoing = if conf.cmd == cmdNs: " --keepgoing" else: ""
let cmd = quoteShell(nifmake) & " run" & parallel & keepGoing & frontendProgress & " " &
quoteShell(buildFile)
rawMessage(conf, hintExecuting, cmd)
let exitCode = execShellCmd(cmd)
Expand Down Expand Up @@ -2277,7 +2340,7 @@ proc commandIc*(conf: ConfigRef; frontendOnly = false) =
var names: seq[string] = @[]
for m in unsemmed(c): names.add m
names.sort()
rawMessage(conf, errGenerated,
c.projectError(
"ic: modules stopped for imports discovered during sem, but " &
"rescheduling made no progress: " & names.join(", "))
break
Expand All @@ -2296,6 +2359,8 @@ proc commandIc*(conf: ConfigRef; frontendOnly = false) =
inc conf.errorCounter
break

if conf.cmd == cmdNs: c.reportToNimsuggest(cacheDir, started)

# Phase 2 — backend (whole-program `nim nifc`), run once over the now-final
# graph. Kept a separate nifmake run so backend rebuilds are decided purely
# by nifmake's input mtimes, independent of frontend discovery.
Expand Down
5 changes: 5 additions & 0 deletions compiler/icmodnames.nim
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,8 @@ proc moduleSuffix*(path: string; searchPaths: openArray[string]): string =
while id > 0'u32:
result.add Base36[int(id mod 36'u32)]
id = id div 36'u32

proc nsReportName*(projectFull: string): string =
## `nim ns`'s report to nimsuggest2 about the project `projectFull`. Named
## after it, as projects can share a nimcache.
"nimsuggest_" & moduleSuffix(projectFull, []) & ".txt"
Loading
Loading