avoid more global variables

This commit is contained in:
Andreas Rumpf 2018-05-11 15:01:28 +02:00
commit a8a544a8f7
9 changed files with 79 additions and 61 deletions

View file

@ -490,10 +490,10 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
of "oldnewlines": of "oldnewlines":
case arg.normalize case arg.normalize
of "on": of "on":
options.gOldNewlines = true conf.oldNewlines = true
defineSymbol(conf.symbols, "nimOldNewlines") defineSymbol(conf.symbols, "nimOldNewlines")
of "off": of "off":
options.gOldNewlines = false conf.oldNewlines = false
undefSymbol(conf.symbols, "nimOldNewlines") undefSymbol(conf.symbols, "nimOldNewlines")
else: else:
localError(conf, info, errOnOrOffExpectedButXFound % arg) localError(conf, info, errOnOrOffExpectedButXFound % arg)
@ -671,19 +671,19 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
trackDirty(conf, arg, info) trackDirty(conf, arg, info)
of "suggest": of "suggest":
expectNoArg(conf, switch, arg, pass, info) expectNoArg(conf, switch, arg, pass, info)
gIdeCmd = ideSug conf.ideCmd = ideSug
of "def": of "def":
expectNoArg(conf, switch, arg, pass, info) expectNoArg(conf, switch, arg, pass, info)
gIdeCmd = ideDef conf.ideCmd = ideDef
of "eval": of "eval":
expectArg(conf, switch, arg, pass, info) expectArg(conf, switch, arg, pass, info)
gEvalExpr = arg gEvalExpr = arg
of "context": of "context":
expectNoArg(conf, switch, arg, pass, info) expectNoArg(conf, switch, arg, pass, info)
gIdeCmd = ideCon conf.ideCmd = ideCon
of "usages": of "usages":
expectNoArg(conf, switch, arg, pass, info) expectNoArg(conf, switch, arg, pass, info)
gIdeCmd = ideUse conf.ideCmd = ideUse
of "stdout": of "stdout":
expectNoArg(conf, switch, arg, pass, info) expectNoArg(conf, switch, arg, pass, info)
incl(gGlobalOptions, optStdout) incl(gGlobalOptions, optStdout)

View file

@ -18,7 +18,13 @@ const
type type
TMsgKind* = enum TMsgKind* = enum
errUnknown, errInternal, errIllFormedAstX, errCannotOpenFile, errGenerated, errUnknown, errInternal, errIllFormedAstX, errCannotOpenFile,
errXExpected,
errGridTableNotImplemented,
errGeneralParseError,
errNewSectionExpected,
errInvalidDirectiveX,
errGenerated,
errUser, errUser,
warnCannotOpenFile, warnCannotOpenFile,
warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit, warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit,
@ -47,6 +53,11 @@ const
errInternal: "internal error: $1", errInternal: "internal error: $1",
errIllFormedAstX: "illformed AST: $1", errIllFormedAstX: "illformed AST: $1",
errCannotOpenFile: "cannot open '$1'", errCannotOpenFile: "cannot open '$1'",
errXExpected: "'$1' expected",
errGridTableNotImplemented: "grid table is not implemented",
errGeneralParseError: "general parse error",
errNewSectionExpected: "new section expected",
errInvalidDirectiveX: "invalid directive: '$1'",
errGenerated: "$1", errGenerated: "$1",
errUser: "$1", errUser: "$1",
warnCannotOpenFile: "cannot open '$1'", warnCannotOpenFile: "cannot open '$1'",

View file

@ -16,7 +16,7 @@ import
wordrecg, syntaxes, renderer, lexer, packages/docutils/rstast, wordrecg, syntaxes, renderer, lexer, packages/docutils/rstast,
packages/docutils/rst, packages/docutils/rstgen, times, packages/docutils/rst, packages/docutils/rstgen, times,
packages/docutils/highlite, sempass2, json, xmltree, cgi, packages/docutils/highlite, sempass2, json, xmltree, cgi,
typesrenderer, astalgo, modulepaths typesrenderer, astalgo, modulepaths, configuration
type type
TSections = array[TSymKind, Rope] TSections = array[TSymKind, Rope]
@ -53,36 +53,40 @@ proc attachToType(d: PDoc; p: PSym): PSym =
if params.len > 0: check(0) if params.len > 0: check(0)
for i in 2..<params.len: check(i) for i in 2..<params.len: check(i)
proc compilerMsgHandler(filename: string, line, col: int, template declareClosures =
msgKind: rst.MsgKind, arg: string) {.procvar.} = proc compilerMsgHandler(filename: string, line, col: int,
# translate msg kind: msgKind: rst.MsgKind, arg: string) {.procvar.} =
var k: msgs.TMsgKind # translate msg kind:
case msgKind var k: TMsgKind
of meCannotOpenFile: k = errCannotOpenFile case msgKind
of meExpected: k = errXExpected of meCannotOpenFile: k = errCannotOpenFile
of meGridTableNotImplemented: k = errGridTableNotImplemented of meExpected: k = errXExpected
of meNewSectionExpected: k = errNewSectionExpected of meGridTableNotImplemented: k = errGridTableNotImplemented
of meGeneralParseError: k = errGeneralParseError of meNewSectionExpected: k = errNewSectionExpected
of meInvalidDirective: k = errInvalidDirectiveX of meGeneralParseError: k = errGeneralParseError
of mwRedefinitionOfLabel: k = warnRedefinitionOfLabel of meInvalidDirective: k = errInvalidDirectiveX
of mwUnknownSubstitution: k = warnUnknownSubstitutionX of mwRedefinitionOfLabel: k = warnRedefinitionOfLabel
of mwUnsupportedLanguage: k = warnLanguageXNotSupported of mwUnknownSubstitution: k = warnUnknownSubstitutionX
of mwUnsupportedField: k = warnFieldXNotSupported of mwUnsupportedLanguage: k = warnLanguageXNotSupported
globalError(newLineInfo(filename, line, col), k, arg) of mwUnsupportedField: k = warnFieldXNotSupported
globalError(conf, newLineInfo(conf, filename, line, col), k, arg)
proc docgenFindFile(s: string): string {.procvar.} = proc docgenFindFile(s: string): string {.procvar.} =
result = options.findFile(s) result = options.findFile(conf, s)
if result.len == 0: if result.len == 0:
result = getCurrentDir() / s result = getCurrentDir() / s
if not existsFile(result): result = "" if not existsFile(result): result = ""
proc parseRst(text, filename: string, proc parseRst(text, filename: string,
line, column: int, hasToc: var bool, line, column: int, hasToc: var bool,
rstOptions: RstParseOptions): PRstNode = rstOptions: RstParseOptions;
conf: ConfigRef): PRstNode =
declareClosures()
result = rstParse(text, filename, line, column, hasToc, rstOptions, result = rstParse(text, filename, line, column, hasToc, rstOptions,
docgenFindFile, compilerMsgHandler) docgenFindFile, compilerMsgHandler)
proc newDocumentor*(filename: string, config: StringTableRef): PDoc = proc newDocumentor*(filename: string, conf: ConfigRef): PDoc =
declareClosures()
new(result) new(result)
initRstGenerator(result[], (if gCmd != cmdRst2tex: outHtml else: outLatex), initRstGenerator(result[], (if gCmd != cmdRst2tex: outHtml else: outLatex),
options.gConfigVars, filename, {roSupportRawDirective}, options.gConfigVars, filename, {roSupportRawDirective},
@ -109,7 +113,7 @@ proc newDocumentor*(filename: string, config: StringTableRef): PDoc =
result.jArray = newJArray() result.jArray = newJArray()
initStrTable result.types initStrTable result.types
result.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string; status: int; content: string) = result.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string; status: int; content: string) =
localError(newLineInfo(d.filename, -1, -1), warnUser, "only 'rst2html' supports the ':test:' attribute") localError(conf, newLineInfo(conf, d.filename, -1, -1), warnUser, "only 'rst2html' supports the ':test:' attribute")
proc dispA(dest: var Rope, xml, tex: string, args: openArray[Rope]) = proc dispA(dest: var Rope, xml, tex: string, args: openArray[Rope]) =
if gCmd != cmdRst2tex: addf(dest, xml, args) if gCmd != cmdRst2tex: addf(dest, xml, args)

View file

@ -627,7 +627,7 @@ proc getEscapedChar(L: var TLexer, tok: var TToken) =
inc(L.bufpos) # skip '\' inc(L.bufpos) # skip '\'
case L.buf[L.bufpos] case L.buf[L.bufpos]
of 'n', 'N': of 'n', 'N':
if gOldNewlines: if L.config.oldNewlines:
if tok.tokType == tkCharLit: if tok.tokType == tkCharLit:
lexMessage(L, errGenerated, "\\n not allowed in character literal") lexMessage(L, errGenerated, "\\n not allowed in character literal")
add(tok.literal, tnl) add(tok.literal, tnl)

View file

@ -168,7 +168,7 @@ when false:
proc raiseRecoverableError*(msg: string) {.noinline, noreturn.} = proc raiseRecoverableError*(msg: string) {.noinline, noreturn.} =
raise newException(ERecoverableError, msg) raise newException(ERecoverableError, msg)
proc sourceLine*(i: TLineInfo): Rope proc sourceLine*(conf: ConfigRef; i: TLineInfo): Rope
proc unknownLineInfo*(): TLineInfo = proc unknownLineInfo*(): TLineInfo =
result.line = uint16(0) result.line = uint16(0)
@ -492,9 +492,9 @@ proc resetAttributes*(conf: ConfigRef) =
if {optUseColors, optStdout} * gGlobalOptions == {optUseColors}: if {optUseColors, optStdout} * gGlobalOptions == {optUseColors}:
terminal.resetAttributes(stderr) terminal.resetAttributes(stderr)
proc writeSurroundingSrc(info: TLineInfo) = proc writeSurroundingSrc(conf: ConfigRef; info: TLineInfo) =
const indent = " " const indent = " "
msgWriteln(indent & $info.sourceLine) msgWriteln(indent & $sourceLine(conf, info))
msgWriteln(indent & spaces(info.col) & '^') msgWriteln(indent & spaces(info.col) & '^')
proc formatMsg*(info: TLineInfo, msg: TMsgKind, arg: string): string = proc formatMsg*(info: TLineInfo, msg: TMsgKind, arg: string): string =
@ -557,7 +557,7 @@ proc liMessage(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg: string,
else: else:
styledMsgWriteln(styleBright, x, resetStyle, color, title, resetStyle, s) styledMsgWriteln(styleBright, x, resetStyle, color, title, resetStyle, s)
if hintSource in conf.notes: if hintSource in conf.notes:
info.writeSurroundingSrc() conf.writeSurroundingSrc(info)
handleError(conf, msg, eh, s) handleError(conf, msg, eh, s)
proc fatal*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") = proc fatal*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
@ -604,10 +604,10 @@ template internalAssert*(conf: ConfigRef, e: bool) =
proc addSourceLine*(fileIdx: FileIndex, line: string) = proc addSourceLine*(fileIdx: FileIndex, line: string) =
fileInfos[fileIdx.int32].lines.add line.rope fileInfos[fileIdx.int32].lines.add line.rope
proc sourceLine*(i: TLineInfo): Rope = proc sourceLine*(conf: ConfigRef; i: TLineInfo): Rope =
if i.fileIndex.int32 < 0: return nil if i.fileIndex.int32 < 0: return nil
if not optPreserveOrigSource and fileInfos[i.fileIndex.int32].lines.len == 0: if not optPreserveOrigSource(conf) and fileInfos[i.fileIndex.int32].lines.len == 0:
try: try:
for line in lines(i.toFullPath): for line in lines(i.toFullPath):
addSourceLine i.fileIndex, line.string addSourceLine i.fileIndex, line.string

View file

@ -123,7 +123,7 @@ proc parseDirective(L: var TLexer, tok: var TToken; config: ConfigRef; condStack
of wEnd: doEnd(L, tok, condStack) of wEnd: doEnd(L, tok, condStack)
of wWrite: of wWrite:
ppGetTok(L, tok) ppGetTok(L, tok)
msgs.msgWriteln(strtabs.`%`(tokToStr(tok), options.gConfigVars, msgs.msgWriteln(strtabs.`%`(tokToStr(tok), config.configVars,
{useEnvironment, useKey})) {useEnvironment, useKey}))
ppGetTok(L, tok) ppGetTok(L, tok)
else: else:
@ -196,7 +196,7 @@ proc parseAssignment(L: var TLexer, tok: var TToken;
add(val, tokToStr(tok)) add(val, tokToStr(tok))
confTok(L, tok, config, condStack) confTok(L, tok, config, condStack)
if percent: if percent:
processSwitch(s, strtabs.`%`(val, options.gConfigVars, processSwitch(s, strtabs.`%`(val, config.configVars,
{useEnvironment, useEmpty}), passPP, info, config) {useEnvironment, useEmpty}), passPP, info, config)
else: else:
processSwitch(s, val, passPP, info, config) processSwitch(s, val, passPP, info, config)

View file

@ -15,3 +15,6 @@ const
VersionAsString* = system.NimVersion VersionAsString* = system.NimVersion
RodFileVersion* = "1223" # modify this if the rod-format changes! RodFileVersion* = "1223" # modify this if the rod-format changes!
NimCompilerApiVersion* = 1 ## Check for the existance of this before accessing it
## as older versions of the compiler API do not
## declare this.

View file

@ -119,6 +119,8 @@ type
arguments*: string ## the arguments to be passed to the program that arguments*: string ## the arguments to be passed to the program that
## should be run ## should be run
helpWritten*: bool helpWritten*: bool
ideCmd*: IdeCmd
oldNewlines*: bool
enableNotes*: TNoteKinds enableNotes*: TNoteKinds
disableNotes*: TNoteKinds disableNotes*: TNoteKinds
foreignPackageNotes*: TNoteKinds foreignPackageNotes*: TNoteKinds
@ -128,6 +130,7 @@ type
hintCounter*: int hintCounter*: int
warnCounter*: int warnCounter*: int
errorMax*: int errorMax*: int
configVars*: StringTableRef
symbols*: StringTableRef ## We need to use a StringTableRef here as defined symbols*: StringTableRef ## We need to use a StringTableRef here as defined
## symbols are always guaranteed to be style ## symbols are always guaranteed to be style
## insensitive. Otherwise hell would break lose. ## insensitive. Otherwise hell would break lose.
@ -146,6 +149,7 @@ proc newConfigRef*(): ConfigRef =
headerFile: "", features: {}, foreignPackageNotes: {hintProcessing, warnUnknownMagic, headerFile: "", features: {}, foreignPackageNotes: {hintProcessing, warnUnknownMagic,
hintQuitCalled, hintExecuting}, hintQuitCalled, hintExecuting},
notes: NotesVerbosity[1], mainPackageNotes: NotesVerbosity[1], notes: NotesVerbosity[1], mainPackageNotes: NotesVerbosity[1],
configVars: newStringTable(modeStyleInsensitive),
symbols: newStringTable(modeStyleInsensitive), symbols: newStringTable(modeStyleInsensitive),
packageCache: newPackageCache()) packageCache: newPackageCache())
@ -197,10 +201,6 @@ proc isDefined*(conf: ConfigRef; symbol: string): bool =
osDragonfly, osMacosx} osDragonfly, osMacosx}
else: discard else: discard
var
gIdeCmd*: IdeCmd
gOldNewlines*: bool
const const
ChecksOptions* = {optObjCheck, optFieldCheck, optRangeCheck, optNilCheck, ChecksOptions* = {optObjCheck, optFieldCheck, optRangeCheck, optNilCheck,
optOverflowCheck, optBoundsCheck, optAssert, optNaNCheck, optInfCheck, optOverflowCheck, optBoundsCheck, optAssert, optNaNCheck, optInfCheck,
@ -227,8 +227,8 @@ var
gEvalExpr* = "" # expression for idetools --eval gEvalExpr* = "" # expression for idetools --eval
gLastCmdTime*: float # when caas is enabled, we measure each command gLastCmdTime*: float # when caas is enabled, we measure each command
gListFullPaths*: bool gListFullPaths*: bool
gPreciseStack*: bool = false gPreciseStack*: bool
gNoNimblePath* = false gNoNimblePath*: bool
gDynlibOverrideAll*: bool gDynlibOverrideAll*: bool
useNimNamespace*: bool useNimNamespace*: bool
@ -238,15 +238,15 @@ type
var gSymbolFiles*: SymbolFilesOption var gSymbolFiles*: SymbolFilesOption
proc importantComments*(): bool {.inline.} = gCmd in {cmdDoc, cmdIdeTools} proc importantComments*(conf: ConfigRef): bool {.inline.} = gCmd in {cmdDoc, cmdIdeTools}
proc usesNativeGC*(): bool {.inline.} = gSelectedGC >= gcRefc proc usesNativeGC*(conf: ConfigRef): bool {.inline.} = gSelectedGC >= gcRefc
template preciseStack*(): bool = gPreciseStack template preciseStack*(conf: ConfigRef): bool = gPreciseStack
template compilationCachePresent*: untyped = template compilationCachePresent*(conf: ConfigRef): untyped =
gSymbolFiles in {enabledSf, writeOnlySf} gSymbolFiles in {enabledSf, writeOnlySf}
# {optCaasEnabled, optSymbolFiles} * gGlobalOptions != {} # {optCaasEnabled, optSymbolFiles} * gGlobalOptions != {}
template optPreserveOrigSource*: untyped = template optPreserveOrigSource*(conf: ConfigRef): untyped =
optEmbedOrigSrc in gGlobalOptions optEmbedOrigSrc in gGlobalOptions
const const
@ -264,7 +264,6 @@ const
# additional configuration variables: # additional configuration variables:
var var
gConfigVars* = newStringTable(modeStyleInsensitive)
gDllOverrides = newStringTable(modeCaseInsensitive) gDllOverrides = newStringTable(modeCaseInsensitive)
gModuleOverrides* = newStringTable(modeStyleInsensitive) gModuleOverrides* = newStringTable(modeStyleInsensitive)
gPrefixDir* = "" # Overrides the default prefix dir in getPrefixDir proc. gPrefixDir* = "" # Overrides the default prefix dir in getPrefixDir proc.
@ -283,10 +282,10 @@ var
const oKeepVariableNames* = true const oKeepVariableNames* = true
template compilingLib*: bool = template compilingLib*(conf: ConfigRef): bool =
gGlobalOptions * {optGenGuiApp, optGenDynLib} != {} gGlobalOptions * {optGenGuiApp, optGenDynLib} != {}
proc mainCommandArg*: string = proc mainCommandArg*(conf: ConfigRef): string =
## This is intended for commands like check or parse ## This is intended for commands like check or parse
## which will work on the main project file unless ## which will work on the main project file unless
## explicitly given a specific file argument ## explicitly given a specific file argument
@ -296,13 +295,13 @@ proc mainCommandArg*: string =
result = gProjectName result = gProjectName
proc existsConfigVar*(conf: ConfigRef; key: string): bool = proc existsConfigVar*(conf: ConfigRef; key: string): bool =
result = hasKey(gConfigVars, key) result = hasKey(conf.configVars, key)
proc getConfigVar*(conf: ConfigRef; key: string): string = proc getConfigVar*(conf: ConfigRef; key: string): string =
result = gConfigVars.getOrDefault key result = conf.configVars.getOrDefault key
proc setConfigVar*(conf: ConfigRef; key, val: string) = proc setConfigVar*(conf: ConfigRef; key, val: string) =
gConfigVars[key] = val conf.configVars[key] = val
proc getOutFile*(conf: ConfigRef; filename, ext: string): string = proc getOutFile*(conf: ConfigRef; filename, ext: string): string =
if options.outFile != "": result = options.outFile if options.outFile != "": result = options.outFile

View file

@ -17,7 +17,6 @@ proc renderPlainSymbolName*(n: PNode): string =
## Use this on documentation name nodes to extract the *raw* symbol name, ## Use this on documentation name nodes to extract the *raw* symbol name,
## without decorations, parameters, or anything. That can be used as the base ## without decorations, parameters, or anything. That can be used as the base
## for the HTML hyperlinks. ## for the HTML hyperlinks.
result = ""
case n.kind case n.kind
of nkPostfix, nkAccQuoted: of nkPostfix, nkAccQuoted:
result = renderPlainSymbolName(n[n.len-1]) result = renderPlainSymbolName(n[n.len-1])
@ -28,7 +27,8 @@ proc renderPlainSymbolName*(n: PNode): string =
of nkPragmaExpr: of nkPragmaExpr:
result = renderPlainSymbolName(n[0]) result = renderPlainSymbolName(n[0])
else: else:
internalError(n.info, "renderPlainSymbolName() with " & $n.kind) result = ""
#internalError(n.info, "renderPlainSymbolName() with " & $n.kind)
assert(not result.isNil) assert(not result.isNil)
proc renderType(n: PNode): string = proc renderType(n: PNode): string =
@ -105,7 +105,8 @@ proc renderParamTypes(found: var seq[string], n: PNode) =
for i in 0 ..< typePos: for i in 0 ..< typePos:
found.add(typeStr) found.add(typeStr)
else: else:
internalError(n.info, "renderParamTypes(found,n) with " & $n.kind) found.add($n)
#internalError(n.info, "renderParamTypes(found,n) with " & $n.kind)
proc renderParamTypes*(n: PNode, sep = defaultParamSeparator): string = proc renderParamTypes*(n: PNode, sep = defaultParamSeparator): string =
## Returns the types contained in `n` joined by `sep`. ## Returns the types contained in `n` joined by `sep`.