From 33b69f0ed0272a4792322d9a0fbaffd5bef2f6e9 Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Sat, 21 Apr 2018 08:13:37 +0200 Subject: refactoring: make FileIndex a distinct type; make line information an uint16; fixes #7654 --- compiler/modulepaths.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'compiler/modulepaths.nim') diff --git a/compiler/modulepaths.nim b/compiler/modulepaths.nim index 878c22cf8..1318b67a7 100644 --- a/compiler/modulepaths.nim +++ b/compiler/modulepaths.nim @@ -174,7 +174,7 @@ proc getModuleName*(n: PNode): string = localError(n.info, errGenerated, "invalid module name: '$1'" % n.renderTree) result = "" -proc checkModuleName*(n: PNode; doLocalError=true): int32 = +proc checkModuleName*(n: PNode; doLocalError=true): FileIndex = # This returns the full canonical path for a given module import let modulename = n.getModuleName let fullPath = findModule(modulename, n.info.toFullPath) -- cgit 1.4.1-2-gfad0 From 5bf31fcabe80f9611a3860a1cbab49407269fe66 Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Thu, 10 May 2018 13:39:23 +0200 Subject: big refactoring: mores stuff compiles --- compiler/modulepaths.nim | 26 +++++++++++------------ compiler/nimsets.nim | 55 +++++++++++++++++------------------------------- compiler/passes.nim | 24 +++++++++++---------- compiler/reorder.nim | 13 ++++++------ compiler/rodwrite.nim | 43 +++++++++++++++++++------------------ compiler/semfold.nim | 20 ++++++------------ 6 files changed, 82 insertions(+), 99 deletions(-) (limited to 'compiler/modulepaths.nim') diff --git a/compiler/modulepaths.nim b/compiler/modulepaths.nim index 1318b67a7..c2e349c4e 100644 --- a/compiler/modulepaths.nim +++ b/compiler/modulepaths.nim @@ -113,16 +113,16 @@ when false: localError(pkg.info, "package name must be an identifier or string literal") result = "" -proc getModuleName*(n: PNode): string = +proc getModuleName*(conf: ConfigRef; n: PNode): string = # This returns a short relative module name without the nim extension # e.g. like "system", "importer" or "somepath/module" # The proc won't perform any checks that the path is actually valid case n.kind of nkStrLit, nkRStrLit, nkTripleStrLit: try: - result = pathSubs(n.strVal, n.info.toFullPath().splitFile().dir) + result = pathSubs(conf, n.strVal, n.info.toFullPath().splitFile().dir) except ValueError: - localError(n.info, "invalid path: " & n.strVal) + localError(conf, n.info, "invalid path: " & n.strVal) result = n.strVal of nkIdent: result = n.ident.s @@ -137,7 +137,7 @@ proc getModuleName*(n: PNode): string = n.sons[0] = n.sons[1] n.sons[1] = n.sons[2] n.sons.setLen(2) - return getModuleName(n.sons[0]) + return getModuleName(conf, n.sons[0]) when false: if n1.kind == nkPrefix and n1[0].kind == nkIdent and n1[0].ident.s == "$": if n0.kind == nkIdent and n0.ident.s == "/": @@ -146,7 +146,7 @@ proc getModuleName*(n: PNode): string = localError(n.info, "only '/' supported with $package notation") result = "" else: - let modname = getModuleName(n[2]) + let modname = getModuleName(conf, n[2]) if $n1 == "std": template attempt(a) = let x = addFileExt(a, "nim") @@ -155,7 +155,7 @@ proc getModuleName*(n: PNode): string = attempt(options.libpath / candidate / modname) # hacky way to implement 'x / y /../ z': - result = getModuleName(n1) + result = getModuleName(conf, n1) result.add renderTree(n0, {renderNoComments}) result.add modname of nkPrefix: @@ -169,19 +169,19 @@ proc getModuleName*(n: PNode): string = of nkDotExpr: result = renderTree(n, {renderNoComments}).replace(".", "/") of nkImportAs: - result = getModuleName(n.sons[0]) + result = getModuleName(conf, n.sons[0]) else: - localError(n.info, errGenerated, "invalid module name: '$1'" % n.renderTree) + localError(conf, n.info, "invalid module name: '$1'" % n.renderTree) result = "" -proc checkModuleName*(n: PNode; doLocalError=true): FileIndex = +proc checkModuleName*(conf: ConfigRef; n: PNode; doLocalError=true): FileIndex = # This returns the full canonical path for a given module import - let modulename = n.getModuleName - let fullPath = findModule(modulename, n.info.toFullPath) + let modulename = getModuleName(conf, n) + let fullPath = findModule(conf, modulename, n.info.toFullPath) if fullPath.len == 0: if doLocalError: let m = if modulename.len > 0: modulename else: $n - localError(n.info, errCannotOpenFile, m) + localError(conf, n.info, "cannot open file: " & m) result = InvalidFileIDX else: - result = fullPath.fileInfoIdx + result = fileInfoIdx(conf, fullPath) diff --git a/compiler/nimsets.nim b/compiler/nimsets.nim index 8ec4d3c0d..6cb675ed8 100644 --- a/compiler/nimsets.nim +++ b/compiler/nimsets.nim @@ -12,27 +12,10 @@ import ast, astalgo, trees, nversion, msgs, platform, bitsets, types, renderer -proc toBitSet*(s: PNode, b: var TBitSet) - # this function is used for case statement checking: -proc overlap*(a, b: PNode): bool -proc inSet*(s: PNode, elem: PNode): bool -proc someInSet*(s: PNode, a, b: PNode): bool -proc emptyRange*(a, b: PNode): bool -proc setHasRange*(s: PNode): bool - # returns true if set contains a range (needed by the code generator) - # these are used for constant folding: -proc unionSets*(a, b: PNode): PNode -proc diffSets*(a, b: PNode): PNode -proc intersectSets*(a, b: PNode): PNode -proc symdiffSets*(a, b: PNode): PNode -proc containsSets*(a, b: PNode): bool -proc equalSets*(a, b: PNode): bool -proc cardSet*(a: PNode): BiggestInt -# implementation - -proc inSet(s: PNode, elem: PNode): bool = +proc inSet*(s: PNode, elem: PNode): bool = + assert s.kind == nkCurly if s.kind != nkCurly: - internalError(s.info, "inSet") + #internalError(s.info, "inSet") return false for i in countup(0, sonsLen(s) - 1): if s.sons[i].kind == nkRange: @@ -44,7 +27,7 @@ proc inSet(s: PNode, elem: PNode): bool = return true result = false -proc overlap(a, b: PNode): bool = +proc overlap*(a, b: PNode): bool = if a.kind == nkRange: if b.kind == nkRange: # X..Y and C..D overlap iff (X <= D and C <= Y) @@ -58,10 +41,11 @@ proc overlap(a, b: PNode): bool = else: result = sameValue(a, b) -proc someInSet(s: PNode, a, b: PNode): bool = +proc someInSet*(s: PNode, a, b: PNode): bool = # checks if some element of a..b is in the set s + assert s.kind == nkCurly if s.kind != nkCurly: - internalError(s.info, "SomeInSet") + #internalError(s.info, "SomeInSet") return false for i in countup(0, sonsLen(s) - 1): if s.sons[i].kind == nkRange: @@ -74,7 +58,7 @@ proc someInSet(s: PNode, a, b: PNode): bool = return true result = false -proc toBitSet(s: PNode, b: var TBitSet) = +proc toBitSet*(s: PNode, b: var TBitSet) = var first, j: BiggestInt first = firstOrd(s.typ.sons[0]) bitSetInit(b, int(getSize(s.typ))) @@ -87,7 +71,7 @@ proc toBitSet(s: PNode, b: var TBitSet) = else: bitSetIncl(b, getOrdValue(s.sons[i]) - first) -proc toTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode = +proc toTreeSet*(s: TBitSet, settype: PType, info: TLineInfo): PNode = var a, b, e, first: BiggestInt # a, b are interval borders elemType: PType @@ -128,18 +112,18 @@ template nodeSetOp(a, b: PNode, op: untyped) {.dirty.} = op(x, y) result = toTreeSet(x, a.typ, a.info) -proc unionSets(a, b: PNode): PNode = nodeSetOp(a, b, bitSetUnion) -proc diffSets(a, b: PNode): PNode = nodeSetOp(a, b, bitSetDiff) -proc intersectSets(a, b: PNode): PNode = nodeSetOp(a, b, bitSetIntersect) -proc symdiffSets(a, b: PNode): PNode = nodeSetOp(a, b, bitSetSymDiff) +proc unionSets*(a, b: PNode): PNode = nodeSetOp(a, b, bitSetUnion) +proc diffSets*(a, b: PNode): PNode = nodeSetOp(a, b, bitSetDiff) +proc intersectSets*(a, b: PNode): PNode = nodeSetOp(a, b, bitSetIntersect) +proc symdiffSets*(a, b: PNode): PNode = nodeSetOp(a, b, bitSetSymDiff) -proc containsSets(a, b: PNode): bool = +proc containsSets*(a, b: PNode): bool = var x, y: TBitSet toBitSet(a, x) toBitSet(b, y) result = bitSetContains(x, y) -proc equalSets(a, b: PNode): bool = +proc equalSets*(a, b: PNode): bool = var x, y: TBitSet toBitSet(a, x) toBitSet(b, y) @@ -156,20 +140,19 @@ proc deduplicate*(a: PNode): PNode = toBitSet(a, x) result = toTreeSet(x, a.typ, a.info) -proc cardSet(a: PNode): BiggestInt = +proc cardSet*(a: PNode): BiggestInt = var x: TBitSet toBitSet(a, x) result = bitSetCard(x) -proc setHasRange(s: PNode): bool = +proc setHasRange*(s: PNode): bool = + assert s.kind == nkCurly if s.kind != nkCurly: - internalError(s.info, "SetHasRange") return false for i in countup(0, sonsLen(s) - 1): if s.sons[i].kind == nkRange: return true result = false -proc emptyRange(a, b: PNode): bool = +proc emptyRange*(a, b: PNode): bool = result = not leValue(a, b) # a > b iff not (a <= b) - diff --git a/compiler/passes.nim b/compiler/passes.nim index b104cd132..931bcc04b 100644 --- a/compiler/passes.nim +++ b/compiler/passes.nim @@ -13,7 +13,8 @@ import strutils, options, ast, astalgo, llstream, msgs, platform, os, condsyms, idents, renderer, types, extccomp, math, magicsys, nversion, - nimsets, syntaxes, times, rodread, idgen, modulegraphs, reorder, rod + nimsets, syntaxes, times, rodread, idgen, modulegraphs, reorder, rod, + configuration type @@ -57,11 +58,11 @@ var # implementation -proc skipCodegen*(n: PNode): bool {.inline.} = +proc skipCodegen*(config: ConfigRef; n: PNode): bool {.inline.} = # can be used by codegen passes to determine whether they should do # something with `n`. Currently, this ignores `n` and uses the global # error count instead. - result = msgs.gErrorCounter > 0 + result = config.errorCounter > 0 const maxPasses = 10 @@ -139,20 +140,21 @@ proc closePassesCached(graph: ModuleGraph; a: var TPassContextArray) = m = gPasses[i].close(graph, a[i], m) a[i] = nil # free the memory here -proc resolveMod(module, relativeTo: string): FileIndex = - let fullPath = findModule(module, relativeTo) +proc resolveMod(conf: ConfigRef; module, relativeTo: string): FileIndex = + let fullPath = findModule(conf, module, relativeTo) if fullPath.len == 0: result = InvalidFileIDX else: - result = fullPath.fileInfoIdx + result = fileInfoIdx(conf, fullPath) -proc processImplicits(implicits: seq[string], nodeKind: TNodeKind, +proc processImplicits(conf: ConfigRef; implicits: seq[string], nodeKind: TNodeKind, a: var TPassContextArray; m: PSym) = # XXX fixme this should actually be relative to the config file! + let gCmdLineInfo = newLineInfo(FileIndex(0), 1, 1) let relativeTo = m.info.toFullPath for module in items(implicits): # implicit imports should not lead to a module importing itself - if m.position != resolveMod(module, relativeTo).int32: + if m.position != resolveMod(conf, module, relativeTo).int32: var importStmt = newNodeI(nodeKind, gCmdLineInfo) var str = newStrNode(nkStrLit, module) str.info = gCmdLineInfo @@ -202,7 +204,7 @@ proc processModule*(graph: ModuleGraph; module: PSym, stream: PLLStream, let filename = fileIdx.toFullPathConsiderDirty s = llStreamOpen(filename, fmRead) if s == nil: - rawMessage(errCannotOpenFile, filename) + rawMessage(graph.config, errCannotOpenFile, filename) return false else: s = stream @@ -214,8 +216,8 @@ proc processModule*(graph: ModuleGraph; module: PSym, stream: PLLStream, # modules to include between compilation runs? we'd need to track that # in ROD files. I think we should enable this feature only # for the interactive mode. - processImplicits implicitImports, nkImportStmt, a, module - processImplicits implicitIncludes, nkIncludeStmt, a, module + processImplicits graph.config, implicitImports, nkImportStmt, a, module + processImplicits graph.config, implicitIncludes, nkIncludeStmt, a, module while true: if graph.stopCompile(): break diff --git a/compiler/reorder.nim b/compiler/reorder.nim index 2542a08ea..d50be1d99 100644 --- a/compiler/reorder.nim +++ b/compiler/reorder.nim @@ -1,7 +1,8 @@ import intsets, ast, idents, algorithm, renderer, parser, ospaths, strutils, - sequtils, msgs, modulegraphs, syntaxes, options, modulepaths, tables + sequtils, msgs, modulegraphs, syntaxes, options, modulepaths, tables, + configuration type DepN = ref object @@ -151,10 +152,10 @@ proc expandIncludes(graph: ModuleGraph, module: PSym, n: PNode, for a in n: if a.kind == nkIncludeStmt: for i in 0..= 0'i64 or (res xor b) >= 0'i64) and checkInRange(n, res): - result = newIntNodeT(res, n) + result = newIntNodeT(res, n) proc foldSub*(a, b: BiggestInt, n: PNode): PNode = let res = a -% b @@ -43,7 +39,7 @@ proc foldSub*(a, b: BiggestInt, n: PNode): PNode = proc foldAbs*(a: BiggestInt, n: PNode): PNode = if a != firstOrd(n.typ): result = newIntNodeT(a, n) - + proc foldMod*(a, b: BiggestInt, n: PNode): PNode = if b != 0'i64: result = newIntNodeT(a mod b, n) @@ -81,9 +77,7 @@ proc foldMul*(a, b: BiggestInt, n: PNode): PNode = checkInRange(n, res): return newIntNodeT(res, n) -# implementation - -proc newIntNodeT(intVal: BiggestInt, n: PNode): PNode = +proc newIntNodeT*(intVal: BiggestInt, n: PNode): PNode = case skipTypes(n.typ, abstractVarRange).kind of tyInt: result = newIntNode(nkIntLit, intVal) @@ -103,7 +97,7 @@ proc newIntNodeT(intVal: BiggestInt, n: PNode): PNode = result.typ = n.typ result.info = n.info -proc newFloatNodeT(floatVal: BiggestFloat, n: PNode): PNode = +proc newFloatNodeT*(floatVal: BiggestFloat, n: PNode): PNode = result = newFloatNode(nkFloatLit, floatVal) if skipTypes(n.typ, abstractVarRange).kind == tyFloat: result.typ = getFloatLitType(result) @@ -111,7 +105,7 @@ proc newFloatNodeT(floatVal: BiggestFloat, n: PNode): PNode = result.typ = n.typ result.info = n.info -proc newStrNodeT(strVal: string, n: PNode): PNode = +proc newStrNodeT*(strVal: string, n: PNode): PNode = result = newStrNode(nkStrLit, strVal) result.typ = n.typ result.info = n.info @@ -378,7 +372,7 @@ proc getConstIfExpr(c: PSym, n: PNode): PNode = if result == nil: result = getConstExpr(c, it.sons[0]) else: internalError(it.info, "getConstIfExpr()") -proc leValueConv(a, b: PNode): bool = +proc leValueConv*(a, b: PNode): bool = result = false case a.kind of nkCharLit..nkUInt64Lit: -- cgit 1.4.1-2-gfad0 From 3c4ceea4272a8e9d817e16e71581f8fa15460a34 Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Fri, 11 May 2018 15:28:26 +0200 Subject: move more global variables into ConfigRef --- compiler/commands.nim | 32 ++++++------ compiler/extccomp.nim | 26 +++++----- compiler/modulepaths.nim | 2 +- compiler/msgs.nim | 2 +- compiler/nimblecmd.nim | 8 +-- compiler/nimconf.nim | 10 ++-- compiler/nimfix/pretty.nim | 2 +- compiler/options.nim | 120 ++++++++++++++++++++++++--------------------- compiler/passes.nim | 4 +- compiler/rodread.nim | 2 +- compiler/rodwrite.nim | 2 +- 11 files changed, 109 insertions(+), 101 deletions(-) (limited to 'compiler/modulepaths.nim') diff --git a/compiler/commands.nim b/compiler/commands.nim index 6ca212ddb..ba6bbab7d 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -287,7 +287,7 @@ proc processPath(conf: ConfigRef; path: string, info: TLineInfo, elif notRelativeToProj: getCurrentDir() / path else: - options.gProjectPath / path + conf.projectPath / path try: result = pathSubs(conf, p, info.toFullPath().splitFile().dir) except ValueError: @@ -366,22 +366,22 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; expectArg(conf, switch, arg, pass, info) let path = processPath(conf, arg, info) - options.searchPaths.keepItIf(cmpPaths(it, path) != 0) - options.lazyPaths.keepItIf(cmpPaths(it, path) != 0) + conf.searchPaths.keepItIf(cmpPaths(it, path) != 0) + conf.lazyPaths.keepItIf(cmpPaths(it, path) != 0) if (len(path) > 0) and (path[len(path) - 1] == DirSep): let strippedPath = path[0 .. (len(path) - 2)] - options.searchPaths.keepItIf(cmpPaths(it, strippedPath) != 0) - options.lazyPaths.keepItIf(cmpPaths(it, strippedPath) != 0) + conf.searchPaths.keepItIf(cmpPaths(it, strippedPath) != 0) + conf.lazyPaths.keepItIf(cmpPaths(it, strippedPath) != 0) of "nimcache": expectArg(conf, switch, arg, pass, info) - options.nimcacheDir = processPath(conf, arg, info, true) + conf.nimcacheDir = processPath(conf, arg, info, true) of "out", "o": expectArg(conf, switch, arg, pass, info) - options.outFile = arg + conf.outFile = arg of "docseesrcurl": expectArg(conf, switch, arg, pass, info) - options.docSeeSrcUrl = arg + conf.docSeeSrcUrl = arg of "mainmodule", "m": discard "allow for backwards compatibility, but don't do anything" of "define", "d": @@ -579,10 +579,10 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; processOnOffSwitchG(conf, {optGenIndex}, arg, pass, info) of "import": expectArg(conf, switch, arg, pass, info) - if pass in {passCmd2, passPP}: implicitImports.add arg + if pass in {passCmd2, passPP}: conf.implicitImports.add arg of "include": expectArg(conf, switch, arg, pass, info) - if pass in {passCmd2, passPP}: implicitIncludes.add arg + if pass in {passCmd2, passPP}: conf.implicitIncludes.add arg of "listcmd": expectNoArg(conf, switch, arg, pass, info) incl(gGlobalOptions, optListCmd) @@ -655,7 +655,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; of "colors": processOnOffSwitchG(conf, {optUseColors}, arg, pass, info) of "lib": expectArg(conf, switch, arg, pass, info) - libpath = processPath(conf, arg, info, notRelativeToProj=true) + conf.libpath = processPath(conf, arg, info, notRelativeToProj=true) of "putenv": expectArg(conf, switch, arg, pass, info) splitSwitch(conf, arg, key, val, pass, info) @@ -751,17 +751,17 @@ proc processArgument*(pass: TCmdLinePass; p: OptParser; if argsCount == 0: # nim filename.nims is the same as "nim e filename.nims": if p.key.endswith(".nims"): - options.command = "e" - options.gProjectName = unixToNativePath(p.key) + config.command = "e" + config.projectName = unixToNativePath(p.key) config.arguments = cmdLineRest(p) result = true elif pass != passCmd2: - options.command = p.key + config.command = p.key else: - if pass == passCmd1: options.commandArgs.add p.key + if pass == passCmd1: config.commandArgs.add p.key if argsCount == 1: # support UNIX style filenames everywhere for portable build scripts: - options.gProjectName = unixToNativePath(p.key) + config.projectName = unixToNativePath(p.key) config.arguments = cmdLineRest(p) result = true inc argsCount diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index bab612835..bded6b3f1 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -474,7 +474,7 @@ proc generateScript(conf: ConfigRef; projectFile: string, script: Rope) = let (dir, name, ext) = splitFile(projectFile) writeRope(script, getNimcacheDir(conf) / addFileExt("compile_" & name, platform.OS[targetOS].scriptExt)) - copyFile(libpath / "nimbase.h", getNimcacheDir(conf) / "nimbase.h") + copyFile(conf.libpath / "nimbase.h", getNimcacheDir(conf) / "nimbase.h") proc getOptSpeed(conf: ConfigRef; c: TSystemCC): string = result = getConfigVar(conf, c, ".options.speed") @@ -563,7 +563,7 @@ proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile): string = var includeCmd, compilePattern: string if not noAbsolutePaths(conf): # compute include paths: - includeCmd = CC[c].includeCmd & quoteShell(libpath) + includeCmd = CC[c].includeCmd & quoteShell(conf.libpath) for includeDir in items(cIncludes): includeCmd.add(join([CC[c].includeCmd, includeDir.quoteShell])) @@ -592,14 +592,14 @@ proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile): string = result = quoteShell(compilePattern % [ "file", cf, "objfile", objfile, "options", options, "include", includeCmd, "nim", getPrefixDir(conf), - "nim", getPrefixDir(conf), "lib", libpath]) + "nim", getPrefixDir(conf), "lib", conf.libpath]) add(result, ' ') addf(result, CC[c].compileTmpl, [ "file", cf, "objfile", objfile, "options", options, "include", includeCmd, "nim", quoteShell(getPrefixDir(conf)), "nim", quoteShell(getPrefixDir(conf)), - "lib", quoteShell(libpath)]) + "lib", quoteShell(conf.libpath)]) proc footprint(conf: ConfigRef; cfile: Cfile): SecureHash = result = secureHash( @@ -655,12 +655,12 @@ proc compileCFile(conf: ConfigRef; list: CFileList, script: var Rope, cmds: var proc getLinkCmd(conf: ConfigRef; projectfile, objfiles: string): string = if optGenStaticLib in gGlobalOptions: var libname: string - if options.outFile.len > 0: - libname = options.outFile.expandTilde + if conf.outFile.len > 0: + libname = conf.outFile.expandTilde if not libname.isAbsolute(): libname = getCurrentDir() / libname else: - libname = (libNameTmpl() % splitFile(gProjectName).name) + libname = (libNameTmpl() % splitFile(conf.projectName).name) result = CC[cCompiler].buildLib % ["libfile", libname, "objfiles", objfiles] else: @@ -679,8 +679,8 @@ proc getLinkCmd(conf: ConfigRef; projectfile, objfiles: string): string = else: exefile = splitFile(projectfile).name & platform.OS[targetOS].exeExt builddll = "" - if options.outFile.len > 0: - exefile = options.outFile.expandTilde + if conf.outFile.len > 0: + exefile = conf.outFile.expandTilde if not exefile.isAbsolute(): exefile = getCurrentDir() / exefile if not noAbsolutePaths(conf): @@ -697,13 +697,13 @@ proc getLinkCmd(conf: ConfigRef; projectfile, objfiles: string): string = linkTmpl = CC[cCompiler].linkTmpl result = quoteShell(result % ["builddll", builddll, "buildgui", buildgui, "options", linkOptions, "objfiles", objfiles, - "exefile", exefile, "nim", getPrefixDir(conf), "lib", libpath]) + "exefile", exefile, "nim", getPrefixDir(conf), "lib", conf.libpath]) result.add ' ' addf(result, linkTmpl, ["builddll", builddll, "buildgui", buildgui, "options", linkOptions, "objfiles", objfiles, "exefile", exefile, "nim", quoteShell(getPrefixDir(conf)), - "lib", quoteShell(libpath)]) + "lib", quoteShell(conf.libpath)]) template tryExceptOSErrorMessage(conf: ConfigRef; errorPrefix: string = "", body: untyped): typed = try: @@ -903,7 +903,7 @@ proc writeMapping*(conf: ConfigRef; symbolMapping: Rope) = getConfigVar(conf, cCompiler, ".options.linker"))) add(code, "\n[Environment]\nlibpath=") - add(code, strutils.escape(libpath)) + add(code, strutils.escape(conf.libpath)) addf(code, "\n[Symbols]$n$1", [symbolMapping]) - writeRope(code, joinPath(gProjectPath, "mapping.txt")) + writeRope(code, joinPath(conf.projectPath, "mapping.txt")) diff --git a/compiler/modulepaths.nim b/compiler/modulepaths.nim index c2e349c4e..daa55c2ba 100644 --- a/compiler/modulepaths.nim +++ b/compiler/modulepaths.nim @@ -152,7 +152,7 @@ proc getModuleName*(conf: ConfigRef; n: PNode): string = let x = addFileExt(a, "nim") if fileExists(x): return x for candidate in stdlibDirs: - attempt(options.libpath / candidate / modname) + attempt(conf.libpath / candidate / modname) # hacky way to implement 'x / y /../ z': result = getModuleName(conf, n1) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 1efc3c944..d8e5a5c27 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -400,7 +400,7 @@ proc quit(conf: ConfigRef; msg: TMsgKind) = else: styledMsgWriteln(fgRed, "No stack traceback available\n" & "To create a stacktrace, rerun compilation with ./koch temp " & - options.command & " ") + conf.command & " ") quit 1 proc handleError(conf: ConfigRef; msg: TMsgKind, eh: TErrorHandling, s: string) = diff --git a/compiler/nimblecmd.nim b/compiler/nimblecmd.nim index da83e9499..8305b01f5 100644 --- a/compiler/nimblecmd.nim +++ b/compiler/nimblecmd.nim @@ -13,8 +13,8 @@ import parseutils, strutils, strtabs, os, options, msgs, sequtils, configuration proc addPath*(conf: ConfigRef; path: string, info: TLineInfo) = - if not options.searchPaths.contains(path): - options.searchPaths.insert(path, 0) + if not conf.searchPaths.contains(path): + conf.searchPaths.insert(path, 0) type Version* = distinct string @@ -112,9 +112,9 @@ proc addNimblePath(conf: ConfigRef; p: string, info: TLineInfo) = if not path.isAbsolute(): path = p / path - if not contains(options.searchPaths, path): + if not contains(conf.searchPaths, path): message(conf, info, hintPath, path) - options.lazyPaths.insert(path, 0) + conf.lazyPaths.insert(path, 0) proc addPathRec(conf: ConfigRef; dir: string, info: TLineInfo) = var packages = newStringTable(modeStyleInsensitive) diff --git a/compiler/nimconf.nim b/compiler/nimconf.nim index b333252a1..6a26f8dc7 100644 --- a/compiler/nimconf.nim +++ b/compiler/nimconf.nim @@ -239,7 +239,7 @@ proc loadConfigs*(cfg: string; cache: IdentCache; config: ConfigRef = nil) = if optSkipUserConfigFile notin gGlobalOptions: readConfigFile(getUserConfigPath(cfg), cache, config) - let pd = if gProjectPath.len > 0: gProjectPath else: getCurrentDir() + let pd = if config.projectPath.len > 0: config.projectPath else: getCurrentDir() if optSkipParentConfigFiles notin gGlobalOptions: for dir in parentDirs(pd, fromRoot=true, inclusive=false): readConfigFile(dir / cfg, cache, config) @@ -247,13 +247,13 @@ proc loadConfigs*(cfg: string; cache: IdentCache; config: ConfigRef = nil) = if optSkipProjConfigFile notin gGlobalOptions: readConfigFile(pd / cfg, cache, config) - if gProjectName.len != 0: + if config.projectName.len != 0: # new project wide config file: - var projectConfig = changeFileExt(gProjectFull, "nimcfg") + var projectConfig = changeFileExt(config.projectFull, "nimcfg") if not fileExists(projectConfig): - projectConfig = changeFileExt(gProjectFull, "nim.cfg") + projectConfig = changeFileExt(config.projectFull, "nim.cfg") readConfigFile(projectConfig, cache, config) -proc loadConfigs*(cfg: string; config: ConfigRef = nil) = +proc loadConfigs*(cfg: string; config: ConfigRef) = # for backwards compatibility only. loadConfigs(cfg, newIdentCache(), config) diff --git a/compiler/nimfix/pretty.nim b/compiler/nimfix/pretty.nim index 8790b7544..c68c3ccf1 100644 --- a/compiler/nimfix/pretty.nim +++ b/compiler/nimfix/pretty.nim @@ -29,7 +29,7 @@ proc overwriteFiles*(conf: ConfigRef) = let doStrip = options.getConfigVar(conf, "pretty.strip").normalize == "on" for i in 0 .. high(gSourceFiles): if gSourceFiles[i].dirty and not gSourceFiles[i].isNimfixFile and - (not gOnlyMainfile or gSourceFiles[i].fileIdx == gProjectMainIdx.FileIndex): + (not gOnlyMainfile or gSourceFiles[i].fileIdx == conf.projectMainIdx.FileIndex): let newFile = if gOverWrite: gSourceFiles[i].fullpath else: gSourceFiles[i].fullpath.changeFileExt(".pretty.nim") try: diff --git a/compiler/options.nim b/compiler/options.nim index 8aa438917..9d265d503 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -135,6 +135,22 @@ type ## symbols are always guaranteed to be style ## insensitive. Otherwise hell would break lose. packageCache*: StringTableRef + searchPaths*: seq[string] + lazyPaths*: seq[string] + outFile*, prefixDir*, libpath*, nimcacheDir*: string + dllOverrides, moduleOverrides*: StringTableRef + projectName*: string # holds a name like 'nim' + projectPath*: string # holds a path like /home/alice/projects/nim/compiler/ + projectFull*: string # projectPath/projectName + projectIsStdin*: bool # whether we're compiling from stdin + projectMainIdx*: int32 # the canonical path id of the main module + command*: string # the main command (e.g. cc, check, scan, etc) + commandArgs*: seq[string] # any arguments after the main command + keepComments*: bool # whether the parser needs to keep comments + implicitImports*: seq[string] # modules that are to be implicitly imported + implicitIncludes*: seq[string] # modules that are to be implicitly included + docSeeSrcUrl*: string # if empty, no seeSrc will be generated. \ + # The string uses the formatting variables `path` and `line`. const oldExperimentalFeatures* = {implicitDeref, dotOperators, callOperator, parallel} @@ -151,7 +167,24 @@ proc newConfigRef*(): ConfigRef = notes: NotesVerbosity[1], mainPackageNotes: NotesVerbosity[1], configVars: newStringTable(modeStyleInsensitive), symbols: newStringTable(modeStyleInsensitive), - packageCache: newPackageCache()) + packageCache: newPackageCache(), + searchPaths: @[], + lazyPaths: @[], + outFile: "", prefixDir: "", libpath: "", nimcacheDir: "", + dllOverrides: newStringTable(modeCaseInsensitive), + moduleOverrides: newStringTable(modeStyleInsensitive), + projectName: "", # holds a name like 'nim' + projectPath: "", # holds a path like /home/alice/projects/nim/compiler/ + projectFull: "", # projectPath/projectName + projectIsStdin: false, # whether we're compiling from stdin + projectMainIdx: 0'i32, # the canonical path id of the main module + command: "", # the main command (e.g. cc, check, scan, etc) + commandArgs: @[], # any arguments after the main command + keepComments: true, # whether the parser needs to keep comments + implicitImports: @[], # modules that are to be implicitly imported + implicitIncludes: @[], # modules that are to be implicitly included + docSeeSrcUrl: "" + ) proc newPartialConfigRef*(): ConfigRef = ## create a new ConfigRef that is only good enough for error reporting. @@ -215,11 +248,6 @@ var gExitcode*: int8 gCmd*: TCommands = cmdNone # the command gSelectedGC* = gcRefc # the selected GC - searchPaths*: seq[string] = @[] - lazyPaths*: seq[string] = @[] - outFile*: string = "" - docSeeSrcUrl*: string = "" # if empty, no seeSrc will be generated. \ - # The string uses the formatting variables `path` and `line`. #headerFile*: string = "" gVerbosity* = 1 # how verbose the compiler is gNumberOfProcessors*: int # number of processors @@ -262,24 +290,6 @@ const DocConfig* = "nimdoc.cfg" DocTexConfig* = "nimdoc.tex.cfg" -# additional configuration variables: -var - gDllOverrides = newStringTable(modeCaseInsensitive) - gModuleOverrides* = newStringTable(modeStyleInsensitive) - gPrefixDir* = "" # Overrides the default prefix dir in getPrefixDir proc. - libpath* = "" - gProjectName* = "" # holds a name like 'nim' - gProjectPath* = "" # holds a path like /home/alice/projects/nim/compiler/ - gProjectFull* = "" # projectPath/projectName - gProjectIsStdin* = false # whether we're compiling from stdin - gProjectMainIdx*: int32 # the canonical path id of the main module - nimcacheDir* = "" - command* = "" # the main command (e.g. cc, check, scan, etc) - commandArgs*: seq[string] = @[] # any arguments after the main command - gKeepComments*: bool = true # whether the parser needs to keep comments - implicitImports*: seq[string] = @[] # modules that are to be implicitly imported - implicitIncludes*: seq[string] = @[] # modules that are to be implicitly included - const oKeepVariableNames* = true template compilingLib*(conf: ConfigRef): bool = @@ -289,10 +299,10 @@ proc mainCommandArg*(conf: ConfigRef): string = ## This is intended for commands like check or parse ## which will work on the main project file unless ## explicitly given a specific file argument - if commandArgs.len > 0: - result = commandArgs[0] + if conf.commandArgs.len > 0: + result = conf.commandArgs[0] else: - result = gProjectName + result = conf.projectName proc existsConfigVar*(conf: ConfigRef; key: string): bool = result = hasKey(conf.configVars, key) @@ -304,37 +314,36 @@ proc setConfigVar*(conf: ConfigRef; key, val: string) = conf.configVars[key] = val proc getOutFile*(conf: ConfigRef; filename, ext: string): string = - if options.outFile != "": result = options.outFile + if conf.outFile != "": result = conf.outFile else: result = changeFileExt(filename, ext) proc getPrefixDir*(conf: ConfigRef): string = ## Gets the prefix dir, usually the parent directory where the binary resides. ## - ## This is overridden by some tools (namely nimsuggest) via the ``gPrefixDir`` + ## This is overridden by some tools (namely nimsuggest) via the ``conf.prefixDir`` ## global. - if gPrefixDir != "": result = gPrefixDir - else: - result = splitPath(getAppDir()).head + if conf.prefixDir != "": result = conf.prefixDir + else: result = splitPath(getAppDir()).head proc setDefaultLibpath*(conf: ConfigRef) = # set default value (can be overwritten): - if libpath == "": + if conf.libpath == "": # choose default libpath: var prefix = getPrefixDir(conf) when defined(posix): - if prefix == "/usr": libpath = "/usr/lib/nim" - elif prefix == "/usr/local": libpath = "/usr/local/lib/nim" - else: libpath = joinPath(prefix, "lib") - else: libpath = joinPath(prefix, "lib") + if prefix == "/usr": conf.libpath = "/usr/lib/nim" + elif prefix == "/usr/local": conf.libpath = "/usr/local/lib/nim" + else: conf.libpath = joinPath(prefix, "lib") + else: conf.libpath = joinPath(prefix, "lib") # Special rule to support other tools (nimble) which import the compiler # modules and make use of them. let realNimPath = findExe("nim") # Find out if $nim/../../lib/system.nim exists. let parentNimLibPath = realNimPath.parentDir.parentDir / "lib" - if not fileExists(libpath / "system.nim") and + if not fileExists(conf.libpath / "system.nim") and fileExists(parentNimlibPath / "system.nim"): - libpath = parentNimLibPath + conf.libpath = parentNimLibPath proc canonicalizePath*(conf: ConfigRef; path: string): string = # on Windows, 'expandFilename' calls getFullPathName which doesn't do @@ -350,7 +359,7 @@ proc canonicalizePath*(conf: ConfigRef; path: string): string = proc shortenDir*(conf: ConfigRef; dir: string): string = ## returns the interesting part of a dir - var prefix = gProjectPath & DirSep + var prefix = conf.projectPath & DirSep if startsWith(dir, prefix): return substr(dir, len(prefix)) prefix = getPrefixDir(conf) & DirSep @@ -366,25 +375,24 @@ proc removeTrailingDirSep*(path: string): string = proc disableNimblePath*(conf: ConfigRef) = gNoNimblePath = true - lazyPaths.setLen(0) + conf.lazyPaths.setLen(0) include packagehandling proc getNimcacheDir*(conf: ConfigRef): string = - result = if nimcacheDir.len > 0: nimcacheDir else: shortenDir(conf, gProjectPath) / - genSubDir - + result = if conf.nimcacheDir.len > 0: conf.nimcacheDir + else: shortenDir(conf, conf.projectPath) / genSubDir proc pathSubs*(conf: ConfigRef; p, config: string): string = let home = removeTrailingDirSep(os.getHomeDir()) result = unixToNativePath(p % [ "nim", getPrefixDir(conf), - "lib", libpath, + "lib", conf.libpath, "home", home, "config", config, - "projectname", options.gProjectName, - "projectpath", options.gProjectPath, - "projectdir", options.gProjectPath, + "projectname", conf.projectName, + "projectpath", conf.projectPath, + "projectdir", conf.projectPath, "nimcache", getNimcacheDir(conf)]) if "~/" in result: result = result.replace("~/", home & '/') @@ -410,28 +418,28 @@ proc completeGeneratedFilePath*(conf: ConfigRef; f: string, createSubDir: bool = #echo "completeGeneratedFilePath(", f, ") = ", result proc rawFindFile(conf: ConfigRef; f: string): string = - for it in searchPaths: + for it in conf.searchPaths: result = joinPath(it, f) if existsFile(result): return canonicalizePath(conf, result) result = "" proc rawFindFile2(conf: ConfigRef; f: string): string = - for i, it in lazyPaths: + for i, it in conf.lazyPaths: result = joinPath(it, f) if existsFile(result): # bring to front for j in countDown(i,1): - swap(lazyPaths[j], lazyPaths[j-1]) + swap(conf.lazyPaths[j], conf.lazyPaths[j-1]) return canonicalizePath(conf, result) result = "" template patchModule(conf: ConfigRef) {.dirty.} = - if result.len > 0 and gModuleOverrides.len > 0: + if result.len > 0 and conf.moduleOverrides.len > 0: let key = getPackageName(conf, result) & "_" & splitFile(result).name - if gModuleOverrides.hasKey(key): - let ov = gModuleOverrides[key] + if conf.moduleOverrides.hasKey(key): + let ov = conf.moduleOverrides[key] if ov.len > 0: result = ov proc findFile*(conf: ConfigRef; f: string): string {.procvar.} = @@ -492,10 +500,10 @@ proc canonDynlibName(s: string): string = result = s.substr(start) proc inclDynlibOverride*(conf: ConfigRef; lib: string) = - gDllOverrides[lib.canonDynlibName] = "true" + conf.dllOverrides[lib.canonDynlibName] = "true" proc isDynlibOverride*(conf: ConfigRef; lib: string): bool = - result = gDynlibOverrideAll or gDllOverrides.hasKey(lib.canonDynlibName) + result = gDynlibOverrideAll or conf.dllOverrides.hasKey(lib.canonDynlibName) proc binaryStrSearch*(x: openArray[string], y: string): int = var a = 0 diff --git a/compiler/passes.nim b/compiler/passes.nim index 931bcc04b..8f9f57f3d 100644 --- a/compiler/passes.nim +++ b/compiler/passes.nim @@ -216,8 +216,8 @@ proc processModule*(graph: ModuleGraph; module: PSym, stream: PLLStream, # modules to include between compilation runs? we'd need to track that # in ROD files. I think we should enable this feature only # for the interactive mode. - processImplicits graph.config, implicitImports, nkImportStmt, a, module - processImplicits graph.config, implicitIncludes, nkIncludeStmt, a, module + processImplicits graph.config, graph.config.implicitImports, nkImportStmt, a, module + processImplicits graph.config, graph.config.implicitIncludes, nkIncludeStmt, a, module while true: if graph.stopCompile(): break diff --git a/compiler/rodread.nim b/compiler/rodread.nim index c7fea2947..f62c24dfd 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -918,7 +918,7 @@ proc handleSymbolFile*(module: PSym; cache: IdentCache; conf: ConfigRef): PRodRe if gSymbolFiles in {disabledSf, writeOnlySf, v2Sf}: module.id = getID() return nil - idgen.loadMaxIds(conf, options.gProjectPath / options.gProjectName) + idgen.loadMaxIds(conf, conf.projectPath / conf.projectName) let fileIdx = module.fileIdx discard checkDep(fileIdx, cache, conf) #if gMods[fileIdx.int32].reason == rrEmpty: internalError("handleSymbolFile") diff --git a/compiler/rodwrite.nim b/compiler/rodwrite.nim index ae6e5c99f..7dc10bbf5 100644 --- a/compiler/rodwrite.nim +++ b/compiler/rodwrite.nim @@ -653,7 +653,7 @@ proc myClose(graph: ModuleGraph; c: PPassContext, n: PNode): PNode = result = process(c, n) var w = PRodWriter(c) writeRod(w) - idgen.saveMaxIds(graph.config, options.gProjectPath / options.gProjectName) + idgen.saveMaxIds(graph.config, graph.config.projectPath / graph.config.projectName) const rodwritePass* = makePass(open = myOpen, close = myClose, process = process) -- cgit 1.4.1-2-gfad0