styleCheck: make the compiler and large parts of the stdlib compatible with --styleCheck:error

This commit is contained in:
Araq 2019-07-10 12:42:23 +02:00
commit c94647aeca
90 changed files with 680 additions and 652 deletions

View file

@ -156,7 +156,7 @@ proc genArg(p: BProc, n: PNode, param: PSym; call: PNode): Rope =
# means '*T'. See posix.nim for lots of examples that do that in the wild.
let callee = call.sons[0]
if callee.kind == nkSym and
{sfImportC, sfInfixCall, sfCompilerProc} * callee.sym.flags == {sfImportC} and
{sfImportc, sfInfixCall, sfCompilerProc} * callee.sym.flags == {sfImportc} and
{lfHeader, lfNoDecl} * callee.sym.loc.flags != {}:
result = addrLoc(p.config, a)
else:

View file

@ -76,7 +76,7 @@ proc genLiteral(p: BProc, n: PNode, ty: PType): Rope =
# with the new semantics for 'nil' strings, we can map "" to nil and
# save tons of allocations:
if n.strVal.len == 0 and optNilSeqs notin p.options and
p.config.selectedGc != gcDestructors:
p.config.selectedGC != gcDestructors:
result = genNilStringLiteral(p.module, n.info)
else:
result = genStringLiteral(p.module, n)
@ -1065,7 +1065,7 @@ proc gcUsage(conf: ConfigRef; n: PNode) =
if conf.selectedGC == gcNone: message(conf, n.info, warnGcMem, n.renderTree)
proc strLoc(p: BProc; d: TLoc): Rope =
if p.config.selectedGc == gcDestructors:
if p.config.selectedGC == gcDestructors:
result = byRefLoc(p, d)
else:
result = rdLoc(d)
@ -1657,7 +1657,7 @@ proc makeAddr(n: PNode): PNode =
result.typ = makePtrType(n.typ)
proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) =
if p.config.selectedGc == gcDestructors:
if p.config.selectedGC == gcDestructors:
e.sons[1] = makeAddr(e[1])
genCall(p, e, d)
return
@ -1686,7 +1686,7 @@ proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) =
gcUsage(p.config, e)
proc genSetLengthStr(p: BProc, e: PNode, d: var TLoc) =
if p.config.selectedGc == gcDestructors:
if p.config.selectedGC == gcDestructors:
binaryStmtAddr(p, e, d, "setLengthStrV2")
else:
var a, b, call: TLoc
@ -1900,7 +1900,7 @@ proc genSomeCast(p: BProc, e: PNode, d: var TLoc) =
if srcTyp.kind in {tyPtr, tyPointer} and etyp.kind in IntegralTypes:
putIntoDest(p, d, e, "(($1) (ptrdiff_t) ($2))" %
[getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
elif p.config.selectedGc == gcDestructors and etyp.kind in {tySequence, tyString}:
elif p.config.selectedGC == gcDestructors and etyp.kind in {tySequence, tyString}:
putIntoDest(p, d, e, "(*($1*) (&$2))" %
[getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
else:
@ -2134,7 +2134,7 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
genAssignment(p, dest, call, {})
of mAppendStrStr: genStrAppend(p, e, d)
of mAppendSeqElem:
if p.config.selectedGc == gcDestructors:
if p.config.selectedGC == gcDestructors:
e.sons[1] = makeAddr(e[1])
genCall(p, e, d)
else:
@ -2773,7 +2773,7 @@ proc getNullValueAuxT(p: BProc; orig, t: PType; obj, cons: PNode,
inc count
getNullValueAux(p, t, obj, cons, result, count)
# do not emit '{}' as that is not valid C:
if oldcount == count: result = oldres
if oldcount == count: result = oldRes
elif not p.module.compileToCpp: result.add "}"
proc genConstObjConstr(p: BProc; n: PNode): Rope =
@ -2847,7 +2847,7 @@ proc genConstExpr(p: BProc, n: PNode): Rope =
of nkBracket, nkPar, nkTupleConstr, nkClosure:
var t = skipTypes(n.typ, abstractInstOwned)
if t.kind == tySequence:
if p.config.selectedGc == gcDestructors:
if p.config.selectedGC == gcDestructors:
result = genConstSeqV2(p, n, n.typ)
else:
result = genConstSeq(p, n, n.typ)
@ -2871,7 +2871,7 @@ proc genConstExpr(p: BProc, n: PNode): Rope =
of nkObjConstr:
result = genConstObjConstr(p, n)
of nkStrLit..nkTripleStrLit:
if p.config.selectedGc == gcDestructors:
if p.config.selectedGC == gcDestructors:
result = genStringLiteralV2Const(p.module, n)
else:
var d: TLoc

View file

@ -15,7 +15,7 @@ const
stringCaseThreshold = 8
# above X strings a hash-switch for strings is generated
proc getTraverseProc(p: BProc, v: Psym): Rope =
proc getTraverseProc(p: BProc, v: PSym): Rope =
if p.config.selectedGC in {gcMarkAndSweep, gcDestructors, gcV2, gcRefc} and
optNimV2 notin p.config.globalOptions and
containsGarbageCollectedRef(v.loc.t):

View file

@ -978,7 +978,7 @@ proc getNimNode(m: BModule): Rope =
result = "$1[$2]" % [m.typeNodesName, rope(m.typeNodes)]
inc(m.typeNodes)
proc TINameForHcr(m: BModule, name: Rope): Rope =
proc tiNameForHcr(m: BModule, name: Rope): Rope =
return if m.hcrOn: "(*".rope & name & ")" else: name
proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
@ -990,7 +990,7 @@ proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
else:
nimtypeKind = ord(typ.kind)
let nameHcr = TINameForHcr(m, name)
let nameHcr = tiNameForHcr(m, name)
var size: Rope
if tfIncompleteStruct in typ.flags: size = rope"void*"
@ -1012,7 +1012,7 @@ proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
if typename == "ref object" and origType.skipTypes(skipPtrs).sym != nil:
typename = "anon ref object from " & m.config$origType.skipTypes(skipPtrs).sym.info
addf(m.s[cfsTypeInit3], "$1.name = $2;$n",
[nameHcr, makeCstring typename])
[nameHcr, makeCString typename])
discard cgsym(m, "nimTypeRoot")
addf(m.s[cfsTypeInit3], "$1.nextType = nimTypeRoot; nimTypeRoot=&$1;$n",
[nameHcr])
@ -1142,7 +1142,7 @@ proc genObjectInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo
var tmp = getNimNode(m)
if not isImportedType(typ):
genObjectFields(m, typ, origType, typ.n, tmp, info)
addf(m.s[cfsTypeInit3], "$1.node = &$2;$n", [TINameForHcr(m, name), tmp])
addf(m.s[cfsTypeInit3], "$1.node = &$2;$n", [tiNameForHcr(m, name), tmp])
var t = typ.sons[0]
while t != nil:
t = t.skipTypes(skipPtrs)
@ -1170,7 +1170,7 @@ proc genTupleInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo)
else:
addf(m.s[cfsTypeInit3], "$1.len = $2; $1.kind = 2;$n",
[expr, rope(length)])
addf(m.s[cfsTypeInit3], "$1.node = &$2;$n", [TINameForHcr(m, name), expr])
addf(m.s[cfsTypeInit3], "$1.node = &$2;$n", [tiNameForHcr(m, name), expr])
proc genEnumInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
# Type information for enumerations is quite heavy, so we do some
@ -1209,17 +1209,17 @@ proc genEnumInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
add(m.s[cfsTypeInit3], specialCases)
addf(m.s[cfsTypeInit3],
"$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n",
[getNimNode(m), rope(length), nodePtrs, TINameForHcr(m, name)])
[getNimNode(m), rope(length), nodePtrs, tiNameForHcr(m, name)])
if hasHoles:
# 1 << 2 is {ntfEnumHole}
addf(m.s[cfsTypeInit3], "$1.flags = 1<<2;$n", [TINameForHcr(m, name)])
addf(m.s[cfsTypeInit3], "$1.flags = 1<<2;$n", [tiNameForHcr(m, name)])
proc genSetInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
assert(typ.sons[0] != nil)
genTypeInfoAux(m, typ, typ, name, info)
var tmp = getNimNode(m)
addf(m.s[cfsTypeInit3], "$1.len = $2; $1.kind = 0;$n" & "$3.node = &$1;$n",
[tmp, rope(firstOrd(m.config, typ)), TINameForHcr(m, name)])
[tmp, rope(firstOrd(m.config, typ)), tiNameForHcr(m, name)])
proc genArrayInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
genTypeInfoAuxBase(m, typ, typ, name, genTypeInfo(m, typ.sons[1], info), info)
@ -1350,12 +1350,12 @@ proc genTypeInfo(m: BModule, t: PType; info: TLineInfo): Rope =
if m.config.selectedGC != gcDestructors:
if m.config.selectedGC >= gcMarkAndSweep:
let markerProc = genTraverseProc(m, origType, sig)
addf(m.s[cfsTypeInit3], "$1.marker = $2;$n", [TINameForHcr(m, result), markerProc])
addf(m.s[cfsTypeInit3], "$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
of tyRef:
genTypeInfoAux(m, t, t, result, info)
if m.config.selectedGC >= gcMarkAndSweep:
let markerProc = genTraverseProc(m, origType, sig)
addf(m.s[cfsTypeInit3], "$1.marker = $2;$n", [TINameForHcr(m, result), markerProc])
addf(m.s[cfsTypeInit3], "$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
of tyPtr, tyRange, tyUncheckedArray: genTypeInfoAux(m, t, t, result, info)
of tyArray: genArrayInfo(m, t, result, info)
of tySet: genSetInfo(m, t, result, info)

View file

@ -268,7 +268,7 @@ proc genLineDir(p: BProc, t: PNode) =
[line, makeCString(toFilename(p.config, t.info))])
elif ({optLineTrace, optStackTrace} * p.options ==
{optLineTrace, optStackTrace}) and
(p.prc == nil or sfPure notin p.prc.flags) and t.info.fileIndex != InvalidFileIDX:
(p.prc == nil or sfPure notin p.prc.flags) and t.info.fileIndex != InvalidFileIdx:
if freshLineInfo(p, t.info):
linefmt(p, cpsStmts, "nimln_($1, $2);$n",
[line, quotedFilename(p.config, t.info)])
@ -296,13 +296,13 @@ proc lenField(p: BProc): Rope =
result = rope(if p.module.compileToCpp: "len" else: "Sup.len")
proc lenExpr(p: BProc; a: TLoc): Rope =
if p.config.selectedGc == gcDestructors:
if p.config.selectedGC == gcDestructors:
result = rdLoc(a) & ".len"
else:
result = "($1 ? $1->$2 : 0)" % [rdLoc(a), lenField(p)]
proc dataField(p: BProc): Rope =
if p.config.selectedGc == gcDestructors:
if p.config.selectedGC == gcDestructors:
result = rope".p->data"
else:
result = rope"->data"
@ -380,10 +380,10 @@ proc isComplexValueType(t: PType): bool {.inline.} =
(t.kind == tyProc and t.callConv == ccClosure)
proc resetLoc(p: BProc, loc: var TLoc) =
let containsGcRef = p.config.selectedGc != gcDestructors and containsGarbageCollectedRef(loc.t)
let containsGcRef = p.config.selectedGC != gcDestructors and containsGarbageCollectedRef(loc.t)
let typ = skipTypes(loc.t, abstractVarRange)
if isImportedCppType(typ): return
if p.config.selectedGc == gcDestructors and typ.kind in {tyString, tySequence}:
if p.config.selectedGC == gcDestructors and typ.kind in {tyString, tySequence}:
assert rdLoc(loc) != nil
linefmt(p, cpsStmts, "$1.len = 0; $1.p = NIM_NIL;$n", [rdLoc(loc)])
elif not isComplexValueType(typ):
@ -414,7 +414,7 @@ proc resetLoc(p: BProc, loc: var TLoc) =
proc constructLoc(p: BProc, loc: TLoc, isTemp = false) =
let typ = loc.t
if p.config.selectedGc == gcDestructors and skipTypes(typ, abstractInst).kind in {tyString, tySequence}:
if p.config.selectedGC == gcDestructors and skipTypes(typ, abstractInst).kind in {tyString, tySequence}:
linefmt(p, cpsStmts, "$1.len = 0; $1.p = NIM_NIL;$n", [rdLoc(loc)])
elif not isComplexValueType(typ):
linefmt(p, cpsStmts, "$1 = ($2)0;$n", [rdLoc(loc),
@ -1774,7 +1774,7 @@ proc rawNewModule(g: BModuleList; module: PSym, filename: AbsoluteFile): BModule
if sfSystemModule in module.flags:
incl result.flags, preventStackTrace
excl(result.preInitProc.options, optStackTrace)
let ndiName = if optCDebug in g.config.globalOptions: changeFileExt(completeCFilePath(g.config, filename), "ndi")
let ndiName = if optCDebug in g.config.globalOptions: changeFileExt(completeCfilePath(g.config, filename), "ndi")
else: AbsoluteFile""
open(result.ndi, ndiName, g.config)
@ -1805,7 +1805,7 @@ proc myOpen(graph: ModuleGraph; module: PSym): PPassContext =
let f = if graph.config.headerFile.len > 0: AbsoluteFile graph.config.headerFile
else: graph.config.projectFull
g.generatedHeader = rawNewModule(g, module,
changeFileExt(completeCFilePath(graph.config, f), hExt))
changeFileExt(completeCfilePath(graph.config, f), hExt))
incl g.generatedHeader.flags, isHeaderFile
proc writeHeader(m: BModule) =
@ -1838,9 +1838,9 @@ proc writeHeader(m: BModule) =
proc getCFile(m: BModule): AbsoluteFile =
let ext =
if m.compileToCpp: ".nim.cpp"
elif m.config.cmd == cmdCompileToOC or sfCompileToObjC in m.module.flags: ".nim.m"
elif m.config.cmd == cmdCompileToOC or sfCompileToObjc in m.module.flags: ".nim.m"
else: ".nim.c"
result = changeFileExt(completeCFilePath(m.config, withPackageName(m.config, m.cfilename)), ext)
result = changeFileExt(completeCfilePath(m.config, withPackageName(m.config, m.cfilename)), ext)
when false:
proc myOpenCached(graph: ModuleGraph; module: PSym, rd: PRodReader): PPassContext =
@ -1920,7 +1920,7 @@ proc writeModule(m: BModule, pending: bool) =
generateThreadVarsSize(m)
var cf = Cfile(nimname: m.module.name.s, cname: cfile,
obj: completeCFilePath(m.config, toObjFile(m.config, cfile)), flags: {})
obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
var code = genModule(m, cf)
if code != nil:
when hasTinyCBackend:
@ -1932,7 +1932,7 @@ proc writeModule(m: BModule, pending: bool) =
addFileToCompile(m.config, cf)
elif pending and mergeRequired(m) and sfMainModule notin m.module.flags:
let cf = Cfile(nimname: m.module.name.s, cname: cfile,
obj: completeCFilePath(m.config, toObjFile(m.config, cfile)), flags: {})
obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
mergeFiles(cfile, m)
genInitCode(m)
finishTypeDescriptions(m)
@ -1946,7 +1946,7 @@ proc writeModule(m: BModule, pending: bool) =
# ``system.c`` but then compilation fails due to an error. This means
# that ``system.o`` is missing, so we need to call the C compiler for it:
var cf = Cfile(nimname: m.module.name.s, cname: cfile,
obj: completeCFilePath(m.config, toObjFile(m.config, cfile)), flags: {})
obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
if not fileExists(cf.obj): cf.flags = {CfileFlag.Cached}
addFileToCompile(m.config, cf)
close(m.ndi)
@ -1954,7 +1954,7 @@ proc writeModule(m: BModule, pending: bool) =
proc updateCachedModule(m: BModule) =
let cfile = getCFile(m)
var cf = Cfile(nimname: m.module.name.s, cname: cfile,
obj: completeCFilePath(m.config, toObjFile(m.config, cfile)), flags: {})
obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
if mergeRequired(m) and sfMainModule notin m.module.flags:
mergeFiles(cfile, m)

View file

@ -100,7 +100,7 @@ type
TypeCache* = Table[SigHash, Rope]
TypeCacheWithOwner* = Table[SigHash, tuple[str: Rope, owner: PSym]]
Codegenflag* = enum
CodegenFlag* = enum
preventStackTrace, # true if stack traces need to be prevented
usesThreadVars, # true if the module uses a thread var
frameDeclared, # hack for ROD support so that we don't declare
@ -137,7 +137,7 @@ type
TCGen = object of PPassContext # represents a C source file
s*: TCFileSections # sections of the C file
flags*: set[Codegenflag]
flags*: set[CodegenFlag]
module*: PSym
filename*: AbsoluteFile
cfilename*: AbsoluteFile # filename of the module (including path,

View file

@ -277,7 +277,7 @@ proc testCompileOption*(conf: ConfigRef; switch: string, info: TLineInfo): bool
of "rangechecks": result = contains(conf.options, optRangeCheck)
of "boundchecks": result = contains(conf.options, optBoundsCheck)
of "overflowchecks": result = contains(conf.options, optOverflowCheck)
of "movechecks": result = contains(conf.options, optMoveCheck)
of "stylechecks": result = contains(conf.options, optStyleCheck)
of "linedir": result = contains(conf.options, optLineDir)
of "assertions", "a": result = contains(conf.options, optAssert)
of "run", "r": result = contains(conf.globalOptions, optRun)
@ -531,7 +531,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
of "rangechecks": processOnOffSwitch(conf, {optRangeCheck}, arg, pass, info)
of "boundchecks": processOnOffSwitch(conf, {optBoundsCheck}, arg, pass, info)
of "overflowchecks": processOnOffSwitch(conf, {optOverflowCheck}, arg, pass, info)
of "movechecks": processOnOffSwitch(conf, {optMoveCheck}, arg, pass, info)
of "stylechecks": processOnOffSwitch(conf, {optStyleCheck}, arg, pass, info)
of "linedir": processOnOffSwitch(conf, {optLineDir}, arg, pass, info)
of "assertions", "a": processOnOffSwitch(conf, {optAssert}, arg, pass, info)
of "deadcodeelim": discard # deprecated, dead code elim always on
@ -807,7 +807,7 @@ proc processArgument*(pass: TCmdLinePass; p: OptParser;
argsCount: var int; config: ConfigRef): bool =
if argsCount == 0:
# nim filename.nims is the same as "nim e filename.nims":
if p.key.endswith(".nims"):
if p.key.endsWith(".nims"):
config.command = "e"
incl(config.globalOptions, optWasNimscript)
config.projectName = unixToNativePath(p.key)

View file

@ -96,3 +96,4 @@ proc initDefines*(symbols: StringTableRef) =
defineSymbol("nimHasHint" & s)
defineSymbol("nimFixedOwned")
defineSymbol("nimHasStyleChecks")

View file

@ -416,7 +416,7 @@ proc setCC*(conf: ConfigRef; ccname: string; info: TLineInfo) =
localError(conf, info, "unknown C compiler: '$1'. Available options are: $2" % [ccname, ccList])
conf.compileOptions = getConfigVar(conf, conf.cCompiler, ".options.always")
conf.linkOptions = ""
conf.ccompilerpath = getConfigVar(conf, conf.cCompiler, ".path")
conf.cCompilerPath = getConfigVar(conf, conf.cCompiler, ".path")
for i in low(CC) .. high(CC): undefSymbol(conf.symbols, CC[i].name)
defineSymbol(conf.symbols, CC[conf.cCompiler].name)
@ -443,10 +443,10 @@ proc initVars*(conf: ConfigRef) =
defineSymbol(conf.symbols, CC[conf.cCompiler].name)
addCompileOption(conf, getConfigVar(conf, conf.cCompiler, ".options.always"))
#addLinkOption(getConfigVar(cCompiler, ".options.linker"))
if len(conf.ccompilerpath) == 0:
conf.ccompilerpath = getConfigVar(conf, conf.cCompiler, ".path")
if len(conf.cCompilerPath) == 0:
conf.cCompilerPath = getConfigVar(conf, conf.cCompiler, ".path")
proc completeCFilePath*(conf: ConfigRef; cfile: AbsoluteFile,
proc completeCfilePath*(conf: ConfigRef; cfile: AbsoluteFile,
createSubDir: bool = true): AbsoluteFile =
result = completeGeneratedFilePath(conf, cfile, createSubDir)
@ -591,7 +591,7 @@ proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile, isMainFile = false): str
for includeDir in items(conf.cIncludes):
includeCmd.add(join([CC[c].includeCmd, includeDir.quoteShell]))
compilePattern = joinPath(conf.ccompilerpath, exe)
compilePattern = joinPath(conf.cCompilerPath, exe)
else:
includeCmd = ""
compilePattern = getCompilerExe(conf, c, cfile.cname)
@ -606,7 +606,7 @@ proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile, isMainFile = false): str
if not cfile.flags.contains(CfileFlag.External) or noAbsolutePaths(conf):
toObjFile(conf, cf).string
else:
completeCFilePath(conf, toObjFile(conf, cf)).string
completeCfilePath(conf, toObjFile(conf, cf)).string
elif noAbsolutePaths(conf):
extractFilename(cfile.obj.string)
else:
@ -666,11 +666,11 @@ proc addExternalFileToCompile*(conf: ConfigRef; c: var Cfile) =
proc addExternalFileToCompile*(conf: ConfigRef; filename: AbsoluteFile) =
var c = Cfile(nimname: splitFile(filename).name, cname: filename,
obj: toObjFile(conf, completeCFilePath(conf, filename, false)),
obj: toObjFile(conf, completeCfilePath(conf, filename, false)),
flags: {CfileFlag.External})
addExternalFileToCompile(conf, c)
proc compileCFiles(conf: ConfigRef; list: CFileList, script: var Rope, cmds: var TStringSeq,
proc compileCFiles(conf: ConfigRef; list: CfileList, script: var Rope, cmds: var TStringSeq,
prettyCmds: var TStringSeq) =
var currIdx = 0
for it in list:
@ -704,7 +704,7 @@ proc getLinkCmd(conf: ConfigRef; output: AbsoluteFile,
# bug #6452: We must not use ``quoteShell`` here for ``linkerExe``
if needsExeExt(conf): linkerExe = addFileExt(linkerExe, "exe")
if noAbsolutePaths(conf): result = linkerExe
else: result = joinPath(conf.cCompilerpath, linkerExe)
else: result = joinPath(conf.cCompilerPath, linkerExe)
let buildgui = if optGenGuiApp in conf.globalOptions and conf.target.targetOS == osWindows:
CC[conf.cCompiler].buildGui
else:
@ -856,7 +856,7 @@ proc linkViaResponseFile(conf: ConfigRef; cmd: string) =
finally:
removeFile(linkerArgs)
proc getObjFilePath(conf: ConfigRef, f: CFile): string =
proc getObjFilePath(conf: ConfigRef, f: Cfile): string =
if noAbsolutePaths(conf): f.obj.extractFilename
else: f.obj.string
@ -1041,7 +1041,7 @@ proc runJsonBuildInstructions*(conf: ConfigRef; projectfile: AbsoluteFile) =
echo getCurrentException().getStackTrace()
quit "error evaluating JSON file: " & jsonFile.string
proc genMappingFiles(conf: ConfigRef; list: CFileList): Rope =
proc genMappingFiles(conf: ConfigRef; list: CfileList): Rope =
for it in list:
addf(result, "--file:r\"$1\"$N", [rope(it.cname.string)])

View file

@ -35,7 +35,7 @@ proc opGorge*(cmd, input, cache: string, info: TLineInfo; conf: ConfigRef): (str
var readSuccessful = false
try:
var p = startProcess(cmd, workingDir,
options={poEvalCommand, poStderrToStdout})
options={poEvalCommand, poStdErrToStdOut})
if input.len != 0:
p.inputStream.write(input)
p.inputStream.close()
@ -49,7 +49,7 @@ proc opGorge*(cmd, input, cache: string, info: TLineInfo; conf: ConfigRef): (str
else:
try:
var p = startProcess(cmd, workingDir,
options={poEvalCommand, poStderrToStdout})
options={poEvalCommand, poStdErrToStdOut})
if input.len != 0:
p.inputStream.write(input)
p.inputStream.close()

View file

@ -139,7 +139,7 @@ proc importModuleAs(c: PContext; n: PNode, realModule: PSym): PSym =
proc myImportModule(c: PContext, n: PNode; importStmtResult: PNode): PSym =
let f = checkModuleName(c.config, n)
if f != InvalidFileIDX:
if f != InvalidFileIdx:
let L = c.graph.importStack.len
let recursion = c.graph.importStack.find(f)
c.graph.importStack.add f

View file

@ -540,7 +540,7 @@ proc pArg(arg: PNode; c: var Con; isSink: bool): PNode =
result.add p(arg[0], c)
for i in 1..<arg.len:
var branch: PNode
if arg[i].kind == nkOfbranch:
if arg[i].kind == nkOfBranch:
branch = arg[i] # of branch conditions are constants
branch[^1] = pArgIfTyped(arg[i][^1])
elif arg[i].kind in {nkElifBranch, nkElifExpr}:
@ -620,7 +620,7 @@ proc moveOrCopy(dest, ri: PNode; c: var Con): PNode =
result.add p(ri[0], c)
for i in 1..<ri.len:
var branch: PNode
if ri[i].kind == nkOfbranch:
if ri[i].kind == nkOfBranch:
branch = ri[i] # of branch conditions are constants
branch[^1] = moveOrCopyIfTyped(ri[i][^1])
elif ri[i].kind in {nkElifBranch, nkElifExpr}:

View file

@ -262,7 +262,7 @@ proc `*`*(a: Int128, b: int32): Int128 =
proc `*=`*(a: var Int128, b: int32): Int128 =
result = result * b
proc makeint128(high,low: uint64): Int128 =
proc makeInt128(high,low: uint64): Int128 =
result.udata[0] = cast[uint32](low)
result.udata[1] = cast[uint32](low shr 32)
result.udata[2] = cast[uint32](high)
@ -296,7 +296,7 @@ proc `*`*(lhs,rhs: Int128): Int128 =
result = makeInt128(high64(lhs) * low64(rhs) + low64(lhs) * high64(rhs) + a32 * b32, a00 * b00)
result = result + toInt128(a32 * b00) shl 32
result = result + toint128(a00 * b32) shl 32
result = result + toInt128(a00 * b32) shl 32
if isNegative != isNegative(result):
echo result

View file

@ -573,20 +573,20 @@ proc arithAux(p: PProc, n: PNode, r: var TCompRes, op: TMagic) =
of mMinF64: applyFormat("nimMin($1, $2)", "nimMin($1, $2)")
of mMaxF64: applyFormat("nimMax($1, $2)", "nimMax($1, $2)")
of mAddU: applyFormat("", "")
of msubU: applyFormat("", "")
of mmulU: applyFormat("", "")
of mdivU: applyFormat("", "")
of mmodU: applyFormat("($1 % $2)", "($1 % $2)")
of mSubU: applyFormat("", "")
of mMulU: applyFormat("", "")
of mDivU: applyFormat("", "")
of mModU: applyFormat("($1 % $2)", "($1 % $2)")
of mEqI: applyFormat("($1 == $2)", "($1 == $2)")
of mLeI: applyFormat("($1 <= $2)", "($1 <= $2)")
of mLtI: applyFormat("($1 < $2)", "($1 < $2)")
of mEqF64: applyFormat("($1 == $2)", "($1 == $2)")
of mLeF64: applyFormat("($1 <= $2)", "($1 <= $2)")
of mLtF64: applyFormat("($1 < $2)", "($1 < $2)")
of mleU: applyFormat("($1 <= $2)", "($1 <= $2)")
of mltU: applyFormat("($1 < $2)", "($1 < $2)")
of mleU64: applyFormat("($1 <= $2)", "($1 <= $2)")
of mltU64: applyFormat("($1 < $2)", "($1 < $2)")
of mLeU: applyFormat("($1 <= $2)", "($1 <= $2)")
of mLtU: applyFormat("($1 < $2)", "($1 < $2)")
of mLeU64: applyFormat("($1 <= $2)", "($1 <= $2)")
of mLtU64: applyFormat("($1 < $2)", "($1 < $2)")
of mEqEnum: applyFormat("($1 == $2)", "($1 == $2)")
of mLeEnum: applyFormat("($1 <= $2)", "($1 <= $2)")
of mLtEnum: applyFormat("($1 < $2)", "($1 < $2)")
@ -1591,9 +1591,9 @@ proc arrayTypeForElemType(typ: PType): string =
of tyInt, tyInt32: "Int32Array"
of tyInt16: "Int16Array"
of tyInt8: "Int8Array"
of tyUint, tyUint32: "Uint32Array"
of tyUint16: "Uint16Array"
of tyUint8: "Uint8Array"
of tyUInt, tyUInt32: "Uint32Array"
of tyUInt16: "Uint16Array"
of tyUInt8: "Uint8Array"
of tyFloat32: "Float32Array"
of tyFloat64, tyFloat: "Float64Array"
else: ""
@ -2246,7 +2246,7 @@ proc genProc(oldProc: PProc, prc: PSym): Rope =
if prc.typ.sons[0] != nil and sfPure notin prc.flags:
resultSym = prc.ast.sons[resultPos].sym
let mname = mangleName(p.module, resultSym)
if not isindirect(resultSym) and
if not isIndirect(resultSym) and
resultSym.typ.kind in {tyVar, tyPtr, tyLent, tyRef, tyOwned} and
mapType(p, resultSym.typ) == etyBaseIndex:
resultAsgn = p.indentLine(("var $# = null;$n") % [mname])
@ -2391,7 +2391,7 @@ proc gen(p: PProc, n: PNode, r: var TCompRes) =
of nkFloatLit..nkFloat64Lit:
let f = n.floatVal
case classify(f)
of fcNaN:
of fcNan:
r.res = rope"NaN"
of fcNegZero:
r.res = rope"-0.0"

View file

@ -344,7 +344,7 @@ proc createUpField(c: var DetectionPass; dest, dep: PSym; info: TLineInfo) =
# with cycles properly, so it's better to produce a weak ref (=ptr) here.
# This seems to be generally correct but since it's a bit risky it's only
# enabled for gcDestructors.
let fieldType = if c.graph.config.selectedGc == gcDestructors:
let fieldType = if c.graph.config.selectedGC == gcDestructors:
c.getEnvTypeForOwnerUp(dep, info) #getHiddenParam(dep).typ
else:
c.getEnvTypeForOwner(dep, info)
@ -535,7 +535,7 @@ proc setupEnvVar(owner: PSym; d: DetectionPass;
c: var LiftingPass; info: TLineInfo): PNode =
if owner.isIterator:
return getHiddenParam(d.graph, owner).newSymNode
result = c.envvars.getOrDefault(owner.id)
result = c.envVars.getOrDefault(owner.id)
if result.isNil:
let envVarType = d.ownerToType.getOrDefault(owner.id)
if envVarType.isNil:
@ -710,7 +710,7 @@ proc liftCapturedVars(n: PNode; owner: PSym; d: DetectionPass;
c.inContainer = 0
var body = transformBody(d.graph, s)
body = liftCapturedVars(body, s, d, c)
if c.envvars.getOrDefault(s.id).isNil:
if c.envVars.getOrDefault(s.id).isNil:
s.transformedBody = body
else:
s.transformedBody = newTree(nkStmtList, rawClosureCreation(s, d, c, n.info), body)
@ -851,7 +851,7 @@ proc liftLambdas*(g: ModuleGraph; fn: PSym, body: PNode; tooEarly: var bool;
var c = initLiftingPass(fn)
result = liftCapturedVars(body, fn, d, c)
# echo renderTree(result, {renderIds})
if c.envvars.getOrDefault(fn.id) != nil:
if c.envVars.getOrDefault(fn.id) != nil:
result = newTree(nkStmtList, rawClosureCreation(fn, d, c, body.info), result)
finishClosureCreation(fn, d, c, body.info, result)
else:

View file

@ -219,7 +219,7 @@ proc fillToken(L: var TToken) =
proc openLexer*(lex: var TLexer, fileIdx: FileIndex, inputstream: PLLStream;
cache: IdentCache; config: ConfigRef) =
openBaseLexer(lex, inputstream)
lex.fileIdx = fileidx
lex.fileIdx = fileIdx
lex.indentAhead = -1
lex.currLineIndent = 0
inc(lex.lineNumber, inputstream.lineOffset)
@ -565,7 +565,7 @@ proc getNumber(L: var TLexer, result: var TToken) =
case result.tokType
of floatTypes:
result.fNumber = parseFloat(result.literal)
of tkUint64Lit:
of tkUInt64Lit:
var iNumber: uint64
var len: int
try:

View file

@ -193,7 +193,7 @@ type
# used for better error messages and
# embedding the original source in the
# generated code
dirtyfile*: AbsoluteFile # the file that is actually read into memory
dirtyFile*: AbsoluteFile # the file that is actually read into memory
# and parsed; usually "" but is used
# for 'nimsuggest'
hash*: string # the checksum of the file
@ -229,12 +229,12 @@ proc raiseRecoverableError*(msg: string) {.noinline.} =
raise newException(ERecoverableError, msg)
const
InvalidFileIDX* = FileIndex(-1)
InvalidFileIdx* = FileIndex(-1)
proc unknownLineInfo*(): TLineInfo =
result.line = uint16(0)
result.col = int16(-1)
result.fileIndex = InvalidFileIDX
result.fileIndex = InvalidFileIdx
type
Severity* {.pure.} = enum ## VS Code only supports these three

View file

@ -83,19 +83,13 @@ proc checkStyle(conf: ConfigRef; cache: IdentCache; info: TLineInfo, s: string,
if s != beau:
lintReport(conf, info, beau, s)
proc styleCheckDefImpl(conf: ConfigRef; cache: IdentCache; info: TLineInfo; s: PSym; k: TSymKind) =
# operators stay as they are:
if k in {skResult, skTemp} or s.name.s[0] notin Letters: return
if k in {skType, skGenericParam} and sfAnon in s.flags: return
if {sfImportc, sfExportc} * s.flags == {}:
checkStyle(conf, cache, info, s.name.s, k, s)
proc nep1CheckDefImpl(conf: ConfigRef; info: TLineInfo; s: PSym; k: TSymKind) =
# operators stay as they are:
if k in {skResult, skTemp} or s.name.s[0] notin Letters: return
if k in {skType, skGenericParam} and sfAnon in s.flags: return
if s.typ != nil and s.typ.kind == tyTypeDesc: return
if {sfImportc, sfExportc} * s.flags != {}: return
if optStyleCheck notin s.options: return
let beau = beautifyName(s.name.s, k)
if s.name.s != beau:
lintReport(conf, info, beau, s.name.s)

View file

@ -29,7 +29,7 @@ import ast, intsets, tables, options, lineinfos, hashes, idents,
incremental, btrees, md5
type
SigHash* = distinct Md5Digest
SigHash* = distinct MD5Digest
ModuleGraph* = ref object
modules*: seq[PSym] ## indexed by int32 fileIdx

View file

@ -162,6 +162,6 @@ proc checkModuleName*(conf: ConfigRef; n: PNode; doLocalError=true): FileIndex =
if doLocalError:
let m = if modulename.len > 0: modulename else: $n
localError(conf, n.info, "cannot open file: " & m)
result = InvalidFileIDX
result = InvalidFileIdx
else:
result = fileInfoIdx(conf, fullPath)

View file

@ -133,12 +133,12 @@ proc wantMainModule*(conf: ConfigRef) =
"command expects a filename")
conf.projectMainIdx = fileInfoIdx(conf, addFileExt(conf.projectFull, NimExt))
proc compileProject*(graph: ModuleGraph; projectFileIdx = InvalidFileIDX) =
proc compileProject*(graph: ModuleGraph; projectFileIdx = InvalidFileIdx) =
connectCallbacks(graph)
let conf = graph.config
wantMainModule(conf)
let systemFileIdx = fileInfoIdx(conf, conf.libpath / RelativeFile"system.nim")
let projectFile = if projectFileIdx == InvalidFileIDX: conf.projectMainIdx else: projectFileIdx
let projectFile = if projectFileIdx == InvalidFileIdx: conf.projectMainIdx else: projectFileIdx
graph.importStack.add projectFile
if projectFile == systemFileIdx:
discard graph.compileModule(projectFile, {sfMainModule, sfSystemModule})

View file

@ -108,7 +108,7 @@ proc newLineInfo*(conf: ConfigRef; filename: AbsoluteFile, line, col: int): TLin
result = newLineInfo(fileInfoIdx(conf, filename), line, col)
proc concat(strings: openarray[string]): string =
proc concat(strings: openArray[string]): string =
var totalLen = 0
for s in strings: totalLen += s.len
result = newStringOfCap totalLen
@ -542,7 +542,7 @@ proc localError*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
proc localError*(conf: ConfigRef; info: TLineInfo, arg: string) =
liMessage(conf, info, errGenerated, arg, doNothing)
proc localError*(conf: ConfigRef; info: TLineInfo, format: string, params: openarray[string]) =
proc localError*(conf: ConfigRef; info: TLineInfo, format: string, params: openArray[string]) =
localError(conf, info, format % params)
proc message*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =

View file

@ -47,7 +47,7 @@ proc processCmdLine(pass: TCmdLinePass, cmd: string; config: ConfigRef) =
parseopt.next(p)
case p.kind
of cmdEnd: break
of cmdLongoption, cmdShortOption:
of cmdLongOption, cmdShortOption:
if p.key == " ":
p.key = "-"
if processArgument(pass, p, argsCount, config): break

View file

@ -26,7 +26,7 @@ type # please make sure we have under 32 options
TOption* = enum # **keep binary compatible**
optNone, optObjCheck, optFieldCheck, optRangeCheck, optBoundsCheck,
optOverflowCheck, optNilCheck,
optNaNCheck, optInfCheck, optMoveCheck,
optNaNCheck, optInfCheck, optStyleCheck,
optAssert, optLineDir, optWarns, optHints,
optOptimizeSpeed, optOptimizeSize, optStackTrace, # stack tracing support
optLineTrace, # line tracing support (includes stack tracing)
@ -149,7 +149,7 @@ type
Cfile* = object
nimname*: string
cname*, obj*: AbsoluteFile
flags*: set[CFileFlag]
flags*: set[CfileFlag]
CfileList* = seq[Cfile]
Suggest* = ref object
@ -246,7 +246,7 @@ type
compileOptionsCmd*: seq[string]
linkOptions*: string # (*)
compileOptions*: string # (*)
ccompilerpath*: string
cCompilerPath*: string
toCompile*: CfileList # (*)
suggestionResultHook*: proc (result: Suggest) {.closure.}
suggestVersion*: int
@ -270,12 +270,12 @@ const oldExperimentalFeatures* = {implicitDeref, dotOperators, callOperator, par
const
ChecksOptions* = {optObjCheck, optFieldCheck, optRangeCheck, optNilCheck,
optOverflowCheck, optBoundsCheck, optAssert, optNaNCheck, optInfCheck,
optMoveCheck}
optStyleCheck}
DefaultOptions* = {optObjCheck, optFieldCheck, optRangeCheck,
optBoundsCheck, optOverflowCheck, optAssert, optWarns,
optHints, optStackTrace, optLineTrace,
optTrMacros, optNilCheck, optMoveCheck}
optTrMacros, optNilCheck, optStyleCheck}
DefaultGlobalOptions* = {optThreadAnalysis,
optExcessiveStackTrace, optListFullPaths}
@ -498,7 +498,7 @@ proc setDefaultLibpath*(conf: ConfigRef) =
# Find out if $nim/../../lib/system.nim exists.
let parentNimLibPath = realNimPath.parentDir.parentDir / "lib"
if not fileExists(conf.libpath.string / "system.nim") and
fileExists(parentNimlibPath / "system.nim"):
fileExists(parentNimLibPath / "system.nim"):
conf.libpath = AbsoluteDir parentNimLibPath
proc canonicalizePath*(conf: ConfigRef; path: AbsoluteFile): AbsoluteFile =
@ -590,7 +590,7 @@ proc rawFindFile2(conf: ConfigRef; f: RelativeFile): AbsoluteFile =
result = it / f
if fileExists(result):
# bring to front
for j in countDown(i,1):
for j in countdown(i,1):
swap(conf.lazyPaths[j], conf.lazyPaths[j-1])
return canonicalizePath(conf, result)

View file

@ -346,7 +346,7 @@ proc parseSymbol(p: var TParser, mode = smNormal): PNode =
parMessage(p, errIdentifierExpected, p.tok)
break
of tkOpr, tkDot, tkDotDot, tkEquals, tkParLe..tkParDotRi:
let lineinfo = parLineinfo(p)
let lineinfo = parLineInfo(p)
var accm = ""
while p.tok.tokType in {tkOpr, tkDot, tkDotDot, tkEquals,
tkParLe..tkParDotRi}:
@ -981,7 +981,7 @@ proc parseIdentColonEquals(p: var TParser, flags: TDeclaredIdentFlags): PNode =
while true:
case p.tok.tokType
of tkSymbol, tkAccent:
if withPragma in flags: a = identWithPragma(p, allowDot=withdot in flags)
if withPragma in flags: a = identWithPragma(p, allowDot=withDot in flags)
else: a = parseSymbol(p)
if a.kind == nkEmpty: return
else: break
@ -1090,7 +1090,7 @@ proc parseParamList(p: var TParser, retColon = true): PNode =
getTok(p)
optInd(p, result)
result.sons[0] = parseTypeDesc(p)
elif not retColon and not hasParle:
elif not retColon and not hasParLe:
# Mark as "not there" in order to mark for deprecation in the semantic pass:
result = p.emptyNode
when defined(nimpretty):

View file

@ -30,6 +30,6 @@ proc verboseProcess(context: PPassContext, n: PNode): PNode =
# system.nim deactivates all hints, for verbosity:3 we want the processing
# messages nonetheless, so we activate them again unconditionally:
incl(v.config.notes, hintProcessing)
message(v.config, n.info, hintProcessing, $idgen.gFrontendId)
message(v.config, n.info, hintProcessing, $idgen.gFrontEndId)
const verbosePass* = makePass(open = verboseOpen, process = verboseProcess)

View file

@ -90,7 +90,7 @@ proc processTopLevelStmt(graph: ModuleGraph, n: PNode, a: var TPassContextArray)
proc resolveMod(conf: ConfigRef; module, relativeTo: string): FileIndex =
let fullPath = findModule(conf, module, relativeTo)
if fullPath.isEmpty:
result = InvalidFileIDX
result = InvalidFileIdx
else:
result = fileInfoIdx(conf, fullPath)

View file

@ -21,7 +21,7 @@ type
# conditionals to condsyms (end of module).
osNone, osDos, osWindows, osOs2, osLinux, osMorphos, osSkyos, osSolaris,
osIrix, osNetbsd, osFreebsd, osOpenbsd, osDragonfly, osAix, osPalmos, osQnx,
osAmiga, osAtari, osNetware, osMacos, osMacosx, osHaiku, osAndroid, osVxworks
osAmiga, osAtari, osNetware, osMacos, osMacosx, osHaiku, osAndroid, osVxWorks
osGenode, osJS, osNimVM, osStandalone, osNintendoSwitch
type

View file

@ -20,38 +20,38 @@ const
const
procPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl,
wMagic, wNosideeffect, wSideeffect, wNoreturn, wDynlib, wHeader,
wMagic, wNoSideEffect, wSideEffect, wNoreturn, wDynlib, wHeader,
wCompilerProc, wNonReloadable, wCore, wProcVar, wDeprecated, wVarargs, wCompileTime, wMerge,
wBorrow, wExtern, wImportCompilerProc, wThread, wImportCpp, wImportObjC,
wAsmNoStackFrame, wError, wDiscardable, wNoInit, wCodegenDecl,
wGensym, wInject, wRaises, wTags, wLocks, wDelegator, wGcSafe,
wConstructor, wExportNims, wUsed, wLiftLocals, wStacktrace, wLinetrace, wNoDestroy}
wConstructor, wExportNims, wUsed, wLiftLocals, wStackTrace, wLineTrace, wNoDestroy}
converterPragmas* = procPragmas - {wNoDestroy}
methodPragmas* = procPragmas+{wBase}-{wImportCpp, wNoDestroy}
templatePragmas* = {wDeprecated, wError, wGensym, wInject, wDirty,
wDelegator, wExportNims, wUsed, wPragma}
macroPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc,
wNodecl, wMagic, wNosideeffect, wCompilerProc, wNonReloadable, wCore, wDeprecated, wExtern,
wNodecl, wMagic, wNoSideEffect, wCompilerProc, wNonReloadable, wCore, wDeprecated, wExtern,
wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wDelegator,
wExportNims, wUsed}
iteratorPragmas* = {FirstCallConv..LastCallConv, wNosideeffect, wSideeffect,
iteratorPragmas* = {FirstCallConv..LastCallConv, wNoSideEffect, wSideEffect,
wImportc, wExportc, wNodecl, wMagic, wDeprecated, wBorrow, wExtern,
wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wRaises,
wTags, wLocks, wGcSafe, wExportNims, wUsed}
exprPragmas* = {wLine, wLocks, wNoRewrite, wGcSafe, wNosideeffect}
stmtPragmas* = {wChecks, wObjChecks, wFieldChecks, wRangechecks,
wBoundchecks, wOverflowchecks, wNilchecks, wMovechecks, wAssertions,
exprPragmas* = {wLine, wLocks, wNoRewrite, wGcSafe, wNoSideEffect}
stmtPragmas* = {wChecks, wObjChecks, wFieldChecks, wRangeChecks,
wBoundChecks, wOverflowChecks, wNilChecks, wStyleChecks, wAssertions,
wWarnings, wHints,
wLinedir, wStacktrace, wLinetrace, wOptimization, wHint, wWarning, wError,
wLineDir, wStackTrace, wLineTrace, wOptimization, wHint, wWarning, wError,
wFatal, wDefine, wUndef, wCompile, wLink, wLinksys, wPure, wPush, wPop,
wBreakpoint, wWatchPoint, wPassl, wPassc,
wDeadCodeElimUnused, # deprecated, always on
wDeprecated,
wFloatchecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll,
wFloatChecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll,
wLinearScanEnd, wPatterns, wTrMacros, wEffects, wNoForward, wReorder, wComputedGoto,
wInjectStmt, wDeprecated, wExperimental, wThis}
lambdaPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl,
wNosideeffect, wSideeffect, wNoreturn, wDynlib, wHeader,
wNoSideEffect, wSideEffect, wNoreturn, wDynlib, wHeader,
wDeprecated, wExtern, wThread, wImportCpp, wImportObjC, wAsmNoStackFrame,
wRaises, wLocks, wTags, wGcSafe, wCodegenDecl}
typePragmas* = {wImportc, wExportc, wDeprecated, wMagic, wAcyclic, wNodecl,
@ -69,7 +69,7 @@ const
wExtern, wImportCpp, wImportObjC, wError, wGensym, wInject, wExportNims,
wIntDefine, wStrDefine, wBoolDefine, wUsed, wCompilerProc, wCore}
letPragmas* = varPragmas
procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNosideeffect,
procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNoSideEffect,
wThread, wRaises, wLocks, wTags, wGcSafe}
forVarPragmas* = {wInject, wGensym}
allRoutinePragmas* = methodPragmas + iteratorPragmas + lambdaPragmas
@ -161,7 +161,7 @@ proc processImportObjC(c: PContext; s: PSym, extname: string, info: TLineInfo) =
incl(s.flags, sfNamedParamCall)
excl(s.flags, sfForward)
let m = s.getModule()
incl(m.flags, sfCompileToObjC)
incl(m.flags, sfCompileToObjc)
proc newEmptyStrNode(c: PContext; n: PNode): PNode {.noinline.} =
result = newNodeIT(nkStrLit, n.info, getSysType(c.graph, n.info, tyString))
@ -331,20 +331,20 @@ proc pragmaToOptions(w: TSpecialWord): TOptions {.inline.} =
of wChecks: ChecksOptions
of wObjChecks: {optObjCheck}
of wFieldChecks: {optFieldCheck}
of wRangechecks: {optRangeCheck}
of wBoundchecks: {optBoundsCheck}
of wOverflowchecks: {optOverflowCheck}
of wNilchecks: {optNilCheck}
of wFloatchecks: {optNaNCheck, optInfCheck}
of wRangeChecks: {optRangeCheck}
of wBoundChecks: {optBoundsCheck}
of wOverflowChecks: {optOverflowCheck}
of wNilChecks: {optNilCheck}
of wFloatChecks: {optNaNCheck, optInfCheck}
of wNanChecks: {optNaNCheck}
of wInfChecks: {optInfCheck}
of wMovechecks: {optMoveCheck}
of wStyleChecks: {optStyleCheck}
of wAssertions: {optAssert}
of wWarnings: {optWarns}
of wHints: {optHints}
of wLinedir: {optLineDir}
of wStacktrace: {optStackTrace}
of wLinetrace: {optLineTrace}
of wLineDir: {optLineDir}
of wStackTrace: {optStackTrace}
of wLineTrace: {optLineTrace}
of wDebugger: {optEndb}
of wProfiler: {optProfiler, optMemTracker}
of wMemTracker: {optMemTracker}
@ -491,7 +491,7 @@ proc processCompile(c: PContext, n: PNode) =
let dest = getStrLit(c, it, 1)
var found = parentDir(toFullPath(c.config, n.info)) / s
for f in os.walkFiles(found):
let obj = completeCFilePath(c.config, AbsoluteFile(dest % extractFilename(f)))
let obj = completeCfilePath(c.config, AbsoluteFile(dest % extractFilename(f)))
docompile(c, it, AbsoluteFile f, obj)
else:
let s = expectStrLit(c, n)
@ -501,7 +501,7 @@ proc processCompile(c: PContext, n: PNode) =
else:
found = findFile(c.config, s)
if found.isEmpty: found = AbsoluteFile s
let obj = toObjFile(c.config, completeCFilePath(c.config, found, false))
let obj = toObjFile(c.config, completeCfilePath(c.config, found, false))
docompile(c, it, found, obj)
proc processLink(c: PContext, n: PNode) =
@ -863,12 +863,12 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: var int,
incl(sym.loc.flags, lfNoDecl)
# implies nodecl, because otherwise header would not make sense
if sym.loc.r == nil: sym.loc.r = rope(sym.name.s)
of wNosideeffect:
of wNoSideEffect:
noVal(c, it)
if sym != nil:
incl(sym.flags, sfNoSideEffect)
if sym.typ != nil: incl(sym.typ.flags, tfNoSideEffect)
of wSideeffect:
of wSideEffect:
noVal(c, it)
incl(sym.flags, sfSideEffect)
of wNoreturn:
@ -1011,12 +1011,12 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: var int,
noVal(c, it)
if sym != nil: incl(sym.flags, sfNoInit)
of wCodegenDecl: processCodegenDecl(c, it, sym)
of wChecks, wObjChecks, wFieldChecks, wRangechecks, wBoundchecks,
wOverflowchecks, wNilchecks, wAssertions, wWarnings, wHints,
wLinedir, wOptimization, wMovechecks, wCallconv, wDebugger, wProfiler,
wFloatchecks, wNanChecks, wInfChecks, wPatterns, wTrMacros:
of wChecks, wObjChecks, wFieldChecks, wRangeChecks, wBoundChecks,
wOverflowChecks, wNilChecks, wAssertions, wWarnings, wHints,
wLineDir, wOptimization, wStyleChecks, wCallconv, wDebugger, wProfiler,
wFloatChecks, wNanChecks, wInfChecks, wPatterns, wTrMacros:
processOption(c, it, c.config.options)
of wStacktrace, wLinetrace:
of wStackTrace, wLineTrace:
if sym.kind in {skProc, skMethod, skConverter}:
processOption(c, it, sym.options)
else:

View file

@ -151,7 +151,7 @@ proc expandIncludes(graph: ModuleGraph, module: PSym, n: PNode,
if a.kind == nkIncludeStmt:
for i in 0..<a.len:
var f = checkModuleName(graph.config, a.sons[i])
if f != InvalidFileIDX:
if f != InvalidFileIdx:
if containsOrIncl(includedFiles, f.int):
localError(graph.config, a.info, "recursive dependency: '$1'" %
toMsgFilename(graph.config, f))

View file

@ -35,7 +35,7 @@ proc c_snprintf(s: cstring; n:uint; frmt: cstring): cint {.importc: "snprintf",
proc toStrMaxPrecision*(f: BiggestFloat, literalPostfix = ""): string =
case classify(f)
of fcNaN:
of fcNan:
result = "NAN"
of fcNegZero:
result = "-0.0" & literalPostfix

View file

@ -152,7 +152,7 @@ proc checkConvertible(c: PContext, targetTyp: PType, src: PNode): TConvStatus =
src.intVal notin firstOrd(c.config, targetTyp)..lastOrd(c.config, targetTyp):
result = convNotInRange
elif src.kind in nkFloatLit..nkFloat64Lit and
(classify(src.floatVal) in {fcNaN, fcNegInf, fcInf} or
(classify(src.floatVal) in {fcNan, fcNegInf, fcInf} or
src.floatVal.int64 notin firstOrd(c.config, targetTyp)..lastOrd(c.config, targetTyp)):
result = convNotInRange
elif targetBaseTyp.kind in tyFloat..tyFloat64:
@ -160,7 +160,7 @@ proc checkConvertible(c: PContext, targetTyp: PType, src: PNode): TConvStatus =
not floatRangeCheck(src.floatVal, targetTyp):
result = convNotInRange
elif src.kind in nkCharLit..nkUInt64Lit and
not floatRangeCheck(src.intval.float, targetTyp):
not floatRangeCheck(src.intVal.float, targetTyp):
result = convNotInRange
else:
# we use d, s here to speed up that operation a bit:
@ -1621,7 +1621,7 @@ proc borrowCheck(c: PContext, n, le, ri: PNode) =
template resultTypeIsInferrable(typ: PType): untyped =
typ.isMetaType and typ.kind != tyTypeDesc
proc goodLineInfo(arg: PNode): TLineinfo =
proc goodLineInfo(arg: PNode): TLineInfo =
if arg.kind == nkStmtListExpr and arg.len > 0:
goodLineInfo(arg[^1])
else:
@ -2108,7 +2108,7 @@ proc instantiateCreateFlowVarCall(c: PContext; t: PType;
# since it's an instantiation, we unmark it as a compilerproc. Otherwise
# codegen would fail:
if sfCompilerProc in result.flags:
result.flags = result.flags - {sfCompilerProc, sfExportC, sfImportC}
result.flags = result.flags - {sfCompilerProc, sfExportc, sfImportc}
result.loc.r = nil
proc setMs(n: PNode, s: PSym): PNode =

View file

@ -157,7 +157,7 @@ proc makeRange(typ: PType, first, last: BiggestInt; g: ModuleGraph): PType =
let lowerNode = newIntNode(nkIntLit, minA)
if typ.kind == tyInt and minA == maxA:
result = getIntLitType(g, lowerNode)
elif typ.kind in {tyUint, tyUInt64}:
elif typ.kind in {tyUInt, tyUInt64}:
# these are not ordinal types, so you get no subrange type for these:
result = typ
else:
@ -187,7 +187,7 @@ proc fitLiteral(c: ConfigRef, n: PNode): PNode =
result = n
let typ = n.typ.skipTypes(abstractRange)
if typ.kind in tyUInt..tyUint32:
if typ.kind in tyUInt..tyUInt32:
result.intVal = result.intVal and lastOrd(c, typ, fixedUnsigned=true)
proc evalOp(m: TMagic, n, a, b, c: PNode; g: ModuleGraph): PNode =
@ -431,7 +431,7 @@ proc foldConv(n, a: PNode; g: ModuleGraph; check = false): PNode =
# XXX range checks?
case dstTyp.kind
of tyInt..tyInt64, tyUint..tyUInt64:
of tyInt..tyInt64, tyUInt..tyUInt64:
case srcTyp.kind
of tyFloat..tyFloat64:
result = newIntNodeT(int(getFloat(a)), n, g)
@ -441,7 +441,7 @@ proc foldConv(n, a: PNode; g: ModuleGraph; check = false): PNode =
let toSigned = dstTyp.kind in tyInt..tyInt64
var val = a.getOrdValue
if dstTyp.kind in {tyInt, tyInt64, tyUint, tyUInt64}:
if dstTyp.kind in {tyInt, tyInt64, tyUInt, tyUInt64}:
# No narrowing needed
discard
elif dstTyp.kind in {tyInt..tyInt64}:

View file

@ -497,13 +497,13 @@ proc semGenericStmt(c: PContext, n: PNode,
proc semGenericStmt(c: PContext, n: PNode): PNode =
var ctx: GenericCtx
ctx.toMixin = initIntset()
ctx.toMixin = initIntSet()
result = semGenericStmt(c, n, {}, ctx)
semIdeForTemplateOrGeneric(c, result, ctx.cursorInBody)
proc semConceptBody(c: PContext, n: PNode): PNode =
var ctx: GenericCtx
ctx.toMixin = initIntset()
ctx.toMixin = initIntSet()
result = semGenericStmt(c, n, {withinConcept}, ctx)
semIdeForTemplateOrGeneric(c, result, ctx.cursorInBody)

View file

@ -74,7 +74,7 @@ type
init: seq[int] # list of initialized variables
guards: TModel # nested guards
locked: seq[PNode] # locked locations
gcUnsafe, isRecursive, isToplevel, hasSideEffect, inEnforcedGcSafe: bool
gcUnsafe, isRecursive, isTopLevel, hasSideEffect, inEnforcedGcSafe: bool
inEnforcedNoSideEffects: bool
maxLockLevel, currLockLevel: TLockLevel
config: ConfigRef
@ -263,7 +263,7 @@ proc useVar(a: PEffects, n: PNode) =
# prevent superfluous warnings about the same variable:
a.init.add s.id
if {sfGlobal, sfThread} * s.flags != {} and s.kind in {skVar, skLet} and
s.magic != mNimVm:
s.magic != mNimvm:
if s.guard != nil: guardGlobal(a, n, s.guard)
if {sfGlobal, sfThread} * s.flags == {sfGlobal} and
(tfHasGCedMem in s.typ.flags or s.typ.isGCedMem):
@ -476,7 +476,7 @@ proc propagateEffects(tracked: PEffects, n: PNode, s: PSym) =
markSideEffect(tracked, s)
mergeLockLevels(tracked, n, s.getLockLevel)
proc procVarcheck(n: PNode; conf: ConfigRef) =
proc procVarCheck(n: PNode; conf: ConfigRef) =
if n.kind in nkSymChoices:
for x in n: procVarCheck(x, conf)
elif n.kind == nkSym and n.sym.magic != mNone and n.sym.kind in routineKinds:
@ -485,7 +485,7 @@ proc procVarcheck(n: PNode; conf: ConfigRef) =
proc notNilCheck(tracked: PEffects, n: PNode, paramType: PType) =
let n = n.skipConv
if paramType.isNil or paramType.kind != tyTypeDesc:
procVarcheck skipConvAndClosure(n), tracked.config
procVarCheck skipConvAndClosure(n), tracked.config
#elif n.kind in nkSymChoices:
# echo "came here"
let paramType = paramType.skipTypesOrNil(abstractInst)
@ -833,7 +833,7 @@ proc track(tracked: PEffects, n: PNode) =
createTypeBoundOps(tracked.graph, tracked.c, it.typ, it.info)
let iterCall = n[n.len-2]
let loopBody = n[n.len-1]
if tracked.owner.kind != skMacro and iterCall.safelen > 1:
if tracked.owner.kind != skMacro and iterCall.safeLen > 1:
# XXX this is a bit hacky:
if iterCall[1].typ != nil and iterCall[1].typ.skipTypes(abstractVar).kind notin {tyVarargs, tyOpenArray}:
createTypeBoundOps(tracked.graph, tracked.c, iterCall[1].typ, iterCall[1].info)
@ -861,7 +861,7 @@ proc track(tracked: PEffects, n: PNode) =
lockLocations(tracked, pragmaList.sons[i])
elif pragma == wGcSafe:
enforcedGcSafety = true
elif pragma == wNosideeffect:
elif pragma == wNoSideEffect:
enforceNoSideEffects = true
if enforcedGcSafety: tracked.inEnforcedGcSafe = true
if enforceNoSideEffects: tracked.inEnforcedNoSideEffects = true
@ -1035,5 +1035,5 @@ proc trackTopLevelStmt*(c: PContext; module: PSym; n: PNode) =
var effects = newNode(nkEffectList, n.info)
var t: TEffects
initEffects(g, effects, module, t, c)
t.isToplevel = true
t.isTopLevel = true
track(t, n)

View file

@ -333,7 +333,7 @@ proc semIdentDef(c: PContext, n: PNode, kind: TSymKind): PSym =
suggestSym(c.config, info, result, c.graph.usageSym)
proc checkNilable(c: PContext; v: PSym) =
if {sfGlobal, sfImportC} * v.flags == {sfGlobal} and
if {sfGlobal, sfImportc} * v.flags == {sfGlobal} and
{tfNotNil, tfNeedsInit} * v.typ.flags != {}:
if v.astdef.isNil:
message(c.config, v.info, warnProveInit, v.name.s)
@ -1009,7 +1009,6 @@ proc typeSectionLeftSidePass(c: PContext, n: PNode) =
let typsym = pkg.tab.strTableGet(typName)
if typsym.isNil:
s = semIdentDef(c, name[1], skType)
styleCheckDef(c.config, s)
onDef(name[1].info, s)
s.typ = newTypeS(tyObject, c)
s.typ.sym = s
@ -1024,7 +1023,6 @@ proc typeSectionLeftSidePass(c: PContext, n: PNode) =
s = typsym
else:
s = semIdentDef(c, name, skType)
styleCheckDef(c.config, s)
onDef(name.info, s)
s.typ = newTypeS(tyForward, c)
s.typ.sym = s # process pragmas:
@ -1253,6 +1251,8 @@ proc typeSectionFinalPass(c: PContext, n: PNode) =
if a.kind == nkCommentStmt: continue
let name = typeSectionTypeName(c, a.sons[0])
var s = name.sym
# check the style here after the pragmas have been processed:
styleCheckDef(c.config, s)
# compute the type's size and check for illegal recursions:
if a.sons[1].kind == nkEmpty:
var x = a[2]
@ -1286,7 +1286,7 @@ proc semAllTypeSections(c: PContext; n: PNode): PNode =
of nkIncludeStmt:
for i in 0..<n.len:
var f = checkModuleName(c.config, n.sons[i])
if f != InvalidFileIDX:
if f != InvalidFileIdx:
if containsOrIncl(c.includedFiles, f.int):
localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
else:
@ -2021,7 +2021,7 @@ proc semMacroDef(c: PContext, n: PNode): PNode =
proc incMod(c: PContext, n: PNode, it: PNode, includeStmtResult: PNode) =
var f = checkModuleName(c.config, it)
if f != InvalidFileIDX:
if f != InvalidFileIdx:
if containsOrIncl(c.includedFiles, f.int):
localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
else:

View file

@ -1614,8 +1614,8 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType =
elif op.id == ord(wType):
checkSonsLen(n, 2, c.config)
result = semTypeof(c, n[1], prev)
elif op.s == "typeof" and n[0].kind == nkSym and n[0].sym.magic == mTypeof:
result = semTypeOf2(c, n, prev)
elif op.s == "typeof" and n[0].kind == nkSym and n[0].sym.magic == mTypeOf:
result = semTypeof2(c, n, prev)
elif op.s == "owned" and optNimV2 notin c.config.globalOptions and n.len == 2:
result = semTypeExpr(c, n[1], prev)
else:
@ -1640,7 +1640,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType =
of mSet: result = semSet(c, n, prev)
of mOrdinal: result = semOrdinal(c, n, prev)
of mSeq:
if c.config.selectedGc == gcDestructors and optNimV2 notin c.config.globalOptions:
if c.config.selectedGC == gcDestructors and optNimV2 notin c.config.globalOptions:
let s = c.graph.sysTypes[tySequence]
assert s != nil
assert prev == nil
@ -1658,7 +1658,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType =
c.typesWithOps.add((result, result))
else:
result = semContainer(c, n, tySequence, "seq", prev)
if c.config.selectedGc == gcDestructors:
if c.config.selectedGC == gcDestructors:
incl result.flags, tfHasAsgn
of mOpt: result = semContainer(c, n, tyOpt, "opt", prev)
of mVarargs: result = semVarargs(c, n, prev)
@ -1842,7 +1842,7 @@ proc processMagicType(c: PContext, m: PSym) =
of mString:
setMagicType(c.config, m, tyString, szUncomputedSize)
rawAddSon(m.typ, getSysType(c.graph, m.info, tyChar))
if c.config.selectedGc == gcDestructors:
if c.config.selectedGC == gcDestructors:
incl m.typ.flags, tfHasAsgn
of mCstring:
setMagicIntegral(c.config, m, tyCString, c.config.target.ptrSize)
@ -1883,7 +1883,7 @@ proc processMagicType(c: PContext, m: PSym) =
setMagicIntegral(c.config, m, tyUncheckedArray, szUncomputedSize)
of mSeq:
setMagicType(c.config, m, tySequence, szUncomputedSize)
if c.config.selectedGc == gcDestructors:
if c.config.selectedGC == gcDestructors:
incl m.typ.flags, tfHasAsgn
assert c.graph.sysTypes[tySequence] == nil
c.graph.sysTypes[tySequence] = m.typ

View file

@ -598,7 +598,7 @@ proc replaceTypeVarsTAux(cl: var TReplTypeVars, t: PType): PType =
skipIntLiteralParams(result)
of tySequence:
if cl.isReturnType and cl.c.config.selectedGc == gcDestructors and
if cl.isReturnType and cl.c.config.selectedGC == gcDestructors and
result.attachedOps[attachedDestructor].isNil and
result[0].kind != tyEmpty and optNimV2 notin cl.c.config.globalOptions:
let s = cl.c.graph.sysTypes[tySequence]

View file

@ -249,7 +249,7 @@ proc hashType*(t: PType; flags: set[ConsiderFlag] = {CoType}): SigHash =
var c: MD5Context
md5Init c
hashType c, t, flags+{CoOwnerSig}
md5Final c, result.Md5Digest
md5Final c, result.MD5Digest
when defined(debugSigHashes):
db.exec(sql"INSERT OR IGNORE INTO sighashes(type, hash) VALUES (?, ?)",
typeToString(t), $result)
@ -272,7 +272,7 @@ proc hashProc*(s: PSym): SigHash =
# hash, we also hash the line information. This is pretty bad, but the best
# solution for now:
#c &= s.info.line
md5Final c, result.Md5Digest
md5Final c, result.MD5Digest
proc hashNonProc*(s: PSym): SigHash =
var c: MD5Context
@ -288,7 +288,7 @@ proc hashNonProc*(s: PSym): SigHash =
# might cause:
if s.kind == skParam:
c &= s.position
md5Final c, result.Md5Digest
md5Final c, result.MD5Digest
proc hashOwner*(s: PSym): SigHash =
var c: MD5Context
@ -301,7 +301,7 @@ proc hashOwner*(s: PSym): SigHash =
c &= "."
c &= m.name.s
md5Final c, result.Md5Digest
md5Final c, result.MD5Digest
proc sigHash*(s: PSym): SigHash =
if s.kind in routineKinds and s.typ != nil:
@ -368,14 +368,14 @@ proc symBodyDigest*(graph: ModuleGraph, sym: PSym): SigHash =
md5Init(c)
c.hashType(sym.typ, {CoProc})
c &= char(sym.kind)
c.md5Final(result.Md5Digest)
c.md5Final(result.MD5Digest)
graph.symBodyHashes[sym.id] = result # protect from recursion in the body
if sym.ast != nil:
md5Init(c)
c.md5Update(cast[cstring](result.addr), sizeof(result))
hashBodyTree(graph, c, sym.ast[bodyPos])
c.md5Final(result.Md5Digest)
c.md5Final(result.MD5Digest)
graph.symBodyHashes[sym.id] = result
proc idOrSig*(s: PSym, currentModule: string,

View file

@ -1494,7 +1494,7 @@ proc typeRel(c: var TCandidate, f, aOrig: PType,
# Workaround for regression #4589
if f.sons[i].kind != tyTypeDesc: return
result = isGeneric
elif x.kind == tyGenericInst and isGenericSubType(c, x, f, depth, f) and
elif x.kind == tyGenericInst and isGenericSubtype(c, x, f, depth, f) and
(sonsLen(x) - 1 == sonsLen(f)):
# do not recurse here in order to not K bind twice for this code:
#
@ -1545,7 +1545,7 @@ proc typeRel(c: var TCandidate, f, aOrig: PType,
# Here object inheriting from generic/specialized generic object
# crossing path with metatypes/aliases, so we need to separate them
# by checking sym.id
let genericSubtype = isGenericSubType(c, x, f, depth, f)
let genericSubtype = isGenericSubtype(c, x, f, depth, f)
if not (genericSubtype and aobj.sym.id != fobj.sym.id) and aOrig.kind != tyGenericBody:
depth = -1

View file

@ -253,7 +253,7 @@ proc mapTypeToAstX(cache: IdentCache; t: PType; info: TLineInfo;
result.add t.n.sons[1].copyTree
of tyPointer: result = atomicType("pointer", mPointer)
of tyString: result = atomicType("string", mString)
of tyCString: result = atomicType("cstring", mCString)
of tyCString: result = atomicType("cstring", mCstring)
of tyInt: result = atomicType("int", mInt)
of tyInt8: result = atomicType("int8", mInt8)
of tyInt16: result = atomicType("int16", mInt16)
@ -263,11 +263,11 @@ proc mapTypeToAstX(cache: IdentCache; t: PType; info: TLineInfo;
of tyFloat32: result = atomicType("float32", mFloat32)
of tyFloat64: result = atomicType("float64", mFloat64)
of tyFloat128: result = atomicType("float128", mFloat128)
of tyUInt: result = atomicType("uint", mUint)
of tyUInt8: result = atomicType("uint8", mUint8)
of tyUInt16: result = atomicType("uint16", mUint16)
of tyUInt32: result = atomicType("uint32", mUint32)
of tyUInt64: result = atomicType("uint64", mUint64)
of tyUInt: result = atomicType("uint", mUInt)
of tyUInt8: result = atomicType("uint8", mUInt8)
of tyUInt16: result = atomicType("uint16", mUInt16)
of tyUInt32: result = atomicType("uint32", mUInt32)
of tyUInt64: result = atomicType("uint64", mUInt64)
of tyVarargs: result = mapTypeToBracket("varargs", mVarargs, t, info)
of tyProxy: result = atomicType("error", mNone)
of tyBuiltInTypeClass:

View file

@ -43,16 +43,16 @@ type
wImportCpp, wImportObjC,
wImportCompilerProc,
wImportc, wExportc, wExportNims, wIncompleteStruct, wRequiresInit,
wAlign, wNodecl, wPure, wSideeffect, wHeader,
wAlign, wNodecl, wPure, wSideEffect, wHeader,
wNoSideEffect, wGcSafe, wNoreturn, wMerge, wLib, wDynlib,
wCompilerproc, wCore, wProcVar, wBase, wUsed,
wCompilerProc, wCore, wProcVar, wBase, wUsed,
wFatal, wError, wWarning, wHint, wLine, wPush, wPop, wDefine, wUndef,
wLinedir, wStacktrace, wLinetrace, wLink, wCompile,
wLineDir, wStackTrace, wLineTrace, wLink, wCompile,
wLinksys, wDeprecated, wVarargs, wCallconv, wBreakpoint, wDebugger,
wNimcall, wStdcall, wCdecl, wSafecall, wSyscall, wInline, wNoInline,
wFastcall, wClosure, wNoconv, wOn, wOff, wChecks, wRangechecks,
wBoundchecks, wOverflowchecks, wNilchecks,
wFloatchecks, wNanChecks, wInfChecks, wMoveChecks,
wFastcall, wClosure, wNoconv, wOn, wOff, wChecks, wRangeChecks,
wBoundChecks, wOverflowChecks, wNilChecks,
wFloatChecks, wNanChecks, wInfChecks, wStyleChecks,
wNonReloadable, wExecuteOnReload,
wAssertions, wPatterns, wTrMacros, wWarnings,
wHints, wOptimization, wRaises, wWrites, wReads, wSize, wEffects, wTags,
@ -142,7 +142,7 @@ const
"cdecl", "safecall", "syscall", "inline", "noinline", "fastcall", "closure",
"noconv", "on", "off", "checks", "rangechecks", "boundchecks",
"overflowchecks", "nilchecks",
"floatchecks", "nanchecks", "infchecks", "movechecks",
"floatchecks", "nanchecks", "infchecks", "stylechecks",
"nonreloadable", "executeonreload",
"assertions", "patterns", "trmacros", "warnings", "hints",
@ -192,7 +192,6 @@ proc canonPragmaSpelling*(w: TSpecialWord): string =
of wIncompleteStruct: "incompleteStruct"
of wRequiresInit: "requiresInit"
of wSideEffect: "sideEffect"
of wCompilerProc: "compilerProc"
of wLineDir: "lineDir"
of wStackTrace: "stackTrace"
of wLineTrace: "lineTrace"
@ -203,12 +202,11 @@ proc canonPragmaSpelling*(w: TSpecialWord): string =
of wFloatChecks: "floatChecks"
of wNanChecks: "nanChecks"
of wInfChecks: "infChecks"
of wMoveChecks: "moveChecks"
of wStyleChecks: "styleChecks"
of wNonReloadable: "nonReloadable"
of wExecuteOnReload: "executeOnReload"
of wDeadCodeElimUnused: "deadCodeElim"
of wCompileTime: "compileTime"
of wNoInit: "noInit"
of wFieldChecks: "fieldChecks"
of wLinearScanEnd: "linearScanEnd"
of wComputedGoto: "computedGoto"

View file

@ -499,7 +499,7 @@ type
filename*: string
line*,column*: int
proc `$`*(arg: Lineinfo): string =
proc `$`*(arg: LineInfo): string =
# BUG: without `result = `, gives compile error
result = arg.filename & "(" & $arg.line & ", " & $arg.column & ")"
@ -988,16 +988,16 @@ proc newBlockStmt*(label, body: NimNode): NimNode {.compileTime.} =
## Create a new block statement with label
return newNimNode(nnkBlockStmt).add(label, body)
proc newBlockStmt*(body: NimNode): NimNode {.compiletime.} =
proc newBlockStmt*(body: NimNode): NimNode {.compileTime.} =
## Create a new block: stmt
return newNimNode(nnkBlockStmt).add(newEmptyNode(), body)
proc newVarStmt*(name, value: NimNode): NimNode {.compiletime.} =
proc newVarStmt*(name, value: NimNode): NimNode {.compileTime.} =
## Create a new var stmt
return newNimNode(nnkVarSection).add(
newNimNode(nnkIdentDefs).add(name, newNimNode(nnkEmpty), value))
proc newLetStmt*(name, value: NimNode): NimNode {.compiletime.} =
proc newLetStmt*(name, value: NimNode): NimNode {.compileTime.} =
## Create a new let stmt
return newNimNode(nnkLetSection).add(
newNimNode(nnkIdentDefs).add(name, newNimNode(nnkEmpty), value))
@ -1095,7 +1095,7 @@ proc newProc*(name = newEmptyNode();
body)
proc newIfStmt*(branches: varargs[tuple[cond, body: NimNode]]):
NimNode {.compiletime.} =
NimNode {.compileTime.} =
## Constructor for ``if`` statements.
##
## .. code-block:: nim
@ -1233,7 +1233,7 @@ proc `body=`*(someProc: NimNode, val: NimNode) {.compileTime.} =
else:
badNodeKind someProc, "body="
proc basename*(a: NimNode): NimNode {.compiletime, benign.}
proc basename*(a: NimNode): NimNode {.compileTime, benign.}
proc `$`*(node: NimNode): string {.compileTime.} =
## Get the string of an identifier node
@ -1396,7 +1396,7 @@ else:
else:
result = false
proc hasArgOfName*(params: NimNode; name: string): bool {.compiletime.}=
proc hasArgOfName*(params: NimNode; name: string): bool {.compileTime.}=
## Search nnkFormalParams for an argument.
expectKind(params, nnkFormalParams)
for i in 1 ..< params.len:
@ -1404,7 +1404,7 @@ proc hasArgOfName*(params: NimNode; name: string): bool {.compiletime.}=
if name.eqIdent( $ node[0]):
return true
proc addIdentIfAbsent*(dest: NimNode, ident: string) {.compiletime.} =
proc addIdentIfAbsent*(dest: NimNode, ident: string) {.compileTime.} =
## Add ident to dest if it is not present. This is intended for use
## with pragmas.
for node in dest.children:

View file

@ -170,14 +170,14 @@ proc add*[T](x: var seq[T]; value: sink T) {.magic: "AppendSeqElem", noSideEffec
proc setLen[T](s: var seq[T], newlen: Natural) =
{.noSideEffect.}:
if newlen < s.len:
shrink(s, newLen)
shrink(s, newlen)
else:
let oldLen = s.len
if newLen <= oldLen: return
if newlen <= oldLen: return
var xu = cast[ptr NimSeqV2[T]](addr s)
if xu.p == nil or xu.p.cap < newLen:
xu.p = cast[typeof(xu.p)](prepareSeqAdd(oldLen, xu.p, newLen - oldLen, sizeof(T)))
xu.len = newLen
if xu.p == nil or xu.p.cap < newlen:
xu.p = cast[typeof(xu.p)](prepareSeqAdd(oldLen, xu.p, newlen - oldLen, sizeof(T)))
xu.len = newlen
when false:
proc resize[T](s: var NimSeqV2[T]) =

View file

@ -12,12 +12,12 @@
when false:
# these are to be implemented or changed in the code generator.
#proc rawNewStringNoInit(space: int): NimString {.compilerProc.}
#proc rawNewStringNoInit(space: int): NimString {.compilerproc.}
# seems to be unused.
proc copyDeepString(src: NimString): NimString {.inline.}
# ----------------- sequences ----------------------------------------------
proc incrSeqV3(s: PGenericSeq, typ: PNimType): PGenericSeq {.compilerProc.}
proc incrSeqV3(s: PGenericSeq, typ: PNimType): PGenericSeq {.compilerproc.}
proc setLengthSeqV2(s: PGenericSeq, typ: PNimType, newLen: int): PGenericSeq {.
compilerRtl.}
proc newSeq(typ: PNimType, len: int): pointer {.compilerRtl.}
@ -109,7 +109,7 @@ proc nimAddCharV1(s: var NimStringV2; c: char) {.compilerRtl.} =
s.p.data[s.len+1] = '\0'
inc s.len
proc toNimStr(str: cstring, len: int): NimStringV2 {.compilerProc.} =
proc toNimStr(str: cstring, len: int): NimStringV2 {.compilerproc.} =
if len <= 0:
result = NimStringV2(len: 0, p: nil)
else:
@ -126,7 +126,7 @@ proc cstrToNimstr(str: cstring): NimStringV2 {.compilerRtl.} =
if str == nil: toNimStr(str, 0)
else: toNimStr(str, str.len)
proc nimToCStringConv(s: NimStringV2): cstring {.compilerProc, nonReloadable, inline.} =
proc nimToCStringConv(s: NimStringV2): cstring {.compilerproc, nonReloadable, inline.} =
if s.len == 0: result = cstring""
else: result = cstring(unsafeAddr s.p.data)
@ -141,7 +141,7 @@ proc appendChar(dest: var NimStringV2; c: char) {.compilerproc, inline.} =
dest.p.data[dest.len+1] = '\0'
inc dest.len
proc rawNewString(space: int): NimStringV2 {.compilerProc.} =
proc rawNewString(space: int): NimStringV2 {.compilerproc.} =
# this is also 'system.newStringOfCap'.
if space <= 0:
result = NimStringV2(len: 0, p: nil)
@ -152,7 +152,7 @@ proc rawNewString(space: int): NimStringV2 {.compilerProc.} =
p.cap = space
result = NimStringV2(len: 0, p: p)
proc mnewString(len: int): NimStringV2 {.compilerProc.} =
proc mnewString(len: int): NimStringV2 {.compilerproc.} =
if len <= 0:
result = NimStringV2(len: 0, p: nil)
else:

View file

@ -865,7 +865,7 @@ proc yamlNextToken(g: var GeneralTokenizer) =
inc(pos)
while g.buf[pos] in {'0'..'9', '+', '-'}: inc(pos)
of '0'..'9': yamlPossibleNumber(g, pos)
of '\0': g.kind = gtEOF
of '\0': g.kind = gtEof
else: yamlPlainStrLit(g, pos)
else:
# outside document
@ -883,7 +883,7 @@ proc yamlNextToken(g: var GeneralTokenizer) =
of '#':
g.kind = gtComment
while g.buf[pos] notin {'\0', '\x0A', '\x0D'}: inc(pos)
of '\0': g.kind = gtEOF
of '\0': g.kind = gtEof
else:
g.kind = gtNone
g.state = gtOther

View file

@ -32,6 +32,9 @@
# error only if they actualy try to use the missing declaration
{.deadCodeElim: on.} # dce option deprecated
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
# TODO these constants don't seem to be fetched from a header file for unknown
# platforms - where do they come from and why are they here?
when false:
@ -114,13 +117,13 @@ when StatHasNanoseconds:
## Second-granularity time of last status change.
result = s.st_ctim.tv_sec
else:
proc st_atim*(s: Stat): TimeSpec {.inline.} =
proc st_atim*(s: Stat): Timespec {.inline.} =
## Nanosecond-granularity time of last access.
result.tv_sec = s.st_atime
proc st_mtim*(s: Stat): TimeSpec {.inline.} =
proc st_mtim*(s: Stat): Timespec {.inline.} =
## Nanosecond-granularity time of last data modification.
result.tv_sec = s.st_mtime
proc st_ctim*(s: Stat): TimeSpec {.inline.} =
proc st_ctim*(s: Stat): Timespec {.inline.} =
## Nanosecond-granularity time of last data modification.
result.tv_sec = s.st_ctime
@ -269,45 +272,45 @@ proc strerror*(errnum: cint): cstring {.importc, header: "<string.h>".}
proc pthread_atfork*(a1, a2, a3: proc () {.noconv.}): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_destroy*(a1: ptr PthreadAttr): cint {.
proc pthread_attr_destroy*(a1: ptr Pthread_attr): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_getdetachstate*(a1: ptr PthreadAttr, a2: cint): cint {.
proc pthread_attr_getdetachstate*(a1: ptr Pthread_attr, a2: cint): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_getguardsize*(a1: ptr PthreadAttr, a2: var cint): cint {.
proc pthread_attr_getguardsize*(a1: ptr Pthread_attr, a2: var cint): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_getinheritsched*(a1: ptr PthreadAttr,
proc pthread_attr_getinheritsched*(a1: ptr Pthread_attr,
a2: var cint): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getschedparam*(a1: ptr PthreadAttr,
proc pthread_attr_getschedparam*(a1: ptr Pthread_attr,
a2: ptr Sched_param): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getschedpolicy*(a1: ptr PthreadAttr,
proc pthread_attr_getschedpolicy*(a1: ptr Pthread_attr,
a2: var cint): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getscope*(a1: ptr PthreadAttr,
proc pthread_attr_getscope*(a1: ptr Pthread_attr,
a2: var cint): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getstack*(a1: ptr PthreadAttr,
proc pthread_attr_getstack*(a1: ptr Pthread_attr,
a2: var pointer, a3: var int): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getstackaddr*(a1: ptr PthreadAttr,
proc pthread_attr_getstackaddr*(a1: ptr Pthread_attr,
a2: var pointer): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_getstacksize*(a1: ptr PthreadAttr,
proc pthread_attr_getstacksize*(a1: ptr Pthread_attr,
a2: var int): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_init*(a1: ptr PthreadAttr): cint {.
proc pthread_attr_init*(a1: ptr Pthread_attr): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setdetachstate*(a1: ptr PthreadAttr, a2: cint): cint {.
proc pthread_attr_setdetachstate*(a1: ptr Pthread_attr, a2: cint): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setguardsize*(a1: ptr PthreadAttr, a2: int): cint {.
proc pthread_attr_setguardsize*(a1: ptr Pthread_attr, a2: int): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setinheritsched*(a1: ptr PthreadAttr, a2: cint): cint {.
proc pthread_attr_setinheritsched*(a1: ptr Pthread_attr, a2: cint): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setschedparam*(a1: ptr PthreadAttr,
proc pthread_attr_setschedparam*(a1: ptr Pthread_attr,
a2: ptr Sched_param): cint {.importc, header: "<pthread.h>".}
proc pthread_attr_setschedpolicy*(a1: ptr PthreadAttr, a2: cint): cint {.
proc pthread_attr_setschedpolicy*(a1: ptr Pthread_attr, a2: cint): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setscope*(a1: ptr PthreadAttr, a2: cint): cint {.importc,
proc pthread_attr_setscope*(a1: ptr Pthread_attr, a2: cint): cint {.importc,
header: "<pthread.h>".}
proc pthread_attr_setstack*(a1: ptr PthreadAttr, a2: pointer, a3: int): cint {.
proc pthread_attr_setstack*(a1: ptr Pthread_attr, a2: pointer, a3: int): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setstackaddr*(a1: ptr PthreadAttr, a2: pointer): cint {.
proc pthread_attr_setstackaddr*(a1: ptr Pthread_attr, a2: pointer): cint {.
importc, header: "<pthread.h>".}
proc pthread_attr_setstacksize*(a1: ptr PthreadAttr, a2: int): cint {.
proc pthread_attr_setstacksize*(a1: ptr Pthread_attr, a2: int): cint {.
importc, header: "<pthread.h>".}
proc pthread_barrier_destroy*(a1: ptr Pthread_barrier): cint {.
importc, header: "<pthread.h>".}
@ -350,7 +353,7 @@ proc pthread_condattr_init*(a1: ptr Pthread_condattr): cint {.importc, header: "
proc pthread_condattr_setclock*(a1: ptr Pthread_condattr,a2: ClockId): cint {.importc, header: "<pthread.h>".}
proc pthread_condattr_setpshared*(a1: ptr Pthread_condattr, a2: cint): cint {.importc, header: "<pthread.h>".}
proc pthread_create*(a1: ptr Pthread, a2: ptr PthreadAttr,
proc pthread_create*(a1: ptr Pthread, a2: ptr Pthread_attr,
a3: proc (x: pointer): pointer {.noconv.}, a4: pointer): cint {.importc, header: "<pthread.h>".}
proc pthread_detach*(a1: Pthread): cint {.importc, header: "<pthread.h>".}
proc pthread_equal*(a1, a2: Pthread): cint {.importc, header: "<pthread.h>".}
@ -1068,3 +1071,6 @@ proc setrlimit*(resource: cint, rlp: var RLimit): cint
proc getrlimit*(resource: cint, rlp: var RLimit): cint
{.importc: "getrlimit",header: "<sys/resource.h>".}
## The getrlimit() system call gets resource limits.
when defined(nimHasStyleChecks):
{.pop.} # {.push styleChecks: off.}

View file

@ -19,7 +19,10 @@ const
# On Linux:
# timer_{create,delete,settime,gettime},
# clock_{getcpuclockid, getres, gettime, nanosleep, settime} lives in librt
{.passL: "-lrt".}
{.passl: "-lrt".}
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
# Types
@ -32,7 +35,7 @@ type
SocketHandle* = distinct cint # The type used to represent socket descriptors
# not detected by detect.nim, guarded by #ifdef __USE_UNIX98 in glibc
const SIG_HOLD* = cast[SigHandler](2)
const SIG_HOLD* = cast[Sighandler](2)
type
Time* {.importc: "time_t", header: "<time.h>".} = distinct clong
@ -296,7 +299,7 @@ type
sigev_signo*: cint ## Signal number.
sigev_notify*: cint ## Notification type.
sigev_notify_function*: proc (x: SigVal) {.noconv.} ## Notification func.
sigev_notify_attributes*: ptr PthreadAttr ## Notification attributes.
sigev_notify_attributes*: ptr Pthread_attr ## Notification attributes.
abi: array[12, int]
SigVal* {.importc: "union sigval",
@ -579,4 +582,7 @@ proc WSTOPSIG*(s:cint): cint = WEXITSTATUS(s)
proc WIFEXITED*(s:cint) : bool = WTERMSIG(s) == 0
proc WIFSIGNALED*(s:cint) : bool = (cast[int8]((s and 0x7f) + 1) shr 1) > 0
proc WIFSTOPPED*(s:cint) : bool = (s and 0xff) == 0x7f
proc WIFCONTINUED*(s:cint) : bool = s == W_CONTINUED
proc WIFCONTINUED*(s:cint) : bool = s == WCONTINUED
when defined(nimHasStyleChecks):
{.pop.} # {.push styleChecks: off.}

View file

@ -9,6 +9,9 @@
{.deadCodeElim: on.} # dce option deprecated
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
const
hasSpawnH = true # should exist for every Posix system nowadays
hasAioH = false
@ -272,7 +275,7 @@ type
sigev_signo*: cint ## Signal number.
sigev_value*: SigVal ## Signal value.
sigev_notify_function*: proc (x: SigVal) {.noconv.} ## Notification func.
sigev_notify_attributes*: ptr PthreadAttr ## Notification attributes.
sigev_notify_attributes*: ptr Pthread_attr ## Notification attributes.
SigVal* {.importc: "union sigval",
header: "<signal.h>", final, pure.} = object ## struct sigval
@ -594,3 +597,6 @@ proc WIFSTOPPED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
## True if child is currently stopped.
proc WIFCONTINUED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
## True if child has been continued.
when defined(nimHasStyleChecks):
{.pop.}

View file

@ -9,6 +9,9 @@
{.deadCodeElim: on.} # dce option deprecated
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
const
hasSpawnH = true # should exist for every Posix system nowadays
hasAioH = defined(linux)
@ -281,7 +284,7 @@ type
sigev_signo*: cint ## Signal number.
sigev_value*: SigVal ## Signal value.
sigev_notify_function*: proc (x: SigVal) {.noconv.} ## Notification func.
sigev_notify_attributes*: ptr PthreadAttr ## Notification attributes.
sigev_notify_attributes*: ptr Pthread_attr ## Notification attributes.
SigVal* {.importc: "union sigval",
header: "<signal.h>", final, pure.} = object ## struct sigval
@ -603,3 +606,6 @@ proc WIFSTOPPED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
## True if child is currently stopped.
proc WIFCONTINUED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
## True if child has been continued.
when defined(nimHasStyleChecks):
{.pop.}

View file

@ -532,7 +532,7 @@ func isSorted*[T](a: openArray[T],
if cmp(a[i],a[i+1]) * order > 0:
return false
proc isSorted*[T](a: openarray[T], order = SortOrder.Ascending): bool =
proc isSorted*[T](a: openArray[T], order = SortOrder.Ascending): bool =
## Shortcut version of ``isSorted`` that uses ``system.cmp[T]`` as the comparison function.
##
## **See also:**
@ -588,7 +588,7 @@ proc product*[T](x: openArray[seq[T]]): seq[seq[T]] =
index = 0
indexes[index] -= 1
proc nextPermutation*[T](x: var openarray[T]): bool {.discardable.} =
proc nextPermutation*[T](x: var openArray[T]): bool {.discardable.} =
## Calculates the next lexicographic permutation, directly modifying ``x``.
## The result is whether a permutation happened, otherwise we have reached
## the last-ordered permutation.
@ -628,7 +628,7 @@ proc nextPermutation*[T](x: var openarray[T]): bool {.discardable.} =
result = true
proc prevPermutation*[T](x: var openarray[T]): bool {.discardable.} =
proc prevPermutation*[T](x: var openArray[T]): bool {.discardable.} =
## Calculates the previous lexicographic permutation, directly modifying
## ``x``. The result is whether a permutation happened, otherwise we have
## reached the first-ordered permutation.
@ -693,7 +693,7 @@ when isMainModule:
assert arr1.reversed(i, high(arr1)) == arr1.reversed()[0 .. high(arr1) - i]
proc rotateInternal[T](arg: var openarray[T]; first, middle, last: int): int =
proc rotateInternal[T](arg: var openArray[T]; first, middle, last: int): int =
## A port of std::rotate from c++. Ported from `this reference <http://www.cplusplus.com/reference/algorithm/rotate/>`_.
result = first + last - middle
@ -732,20 +732,20 @@ proc rotateInternal[T](arg: var openarray[T]; first, middle, last: int): int =
elif next == last:
next = mMiddle
proc rotatedInternal[T](arg: openarray[T]; first, middle, last: int): seq[T] =
proc rotatedInternal[T](arg: openArray[T]; first, middle, last: int): seq[T] =
result = newSeq[T](arg.len)
for i in 0 ..< first:
result[i] = arg[i]
let N = last - middle
let M = middle - first
for i in 0 ..< N:
let n = last - middle
let m = middle - first
for i in 0 ..< n:
result[first+i] = arg[middle+i]
for i in 0 ..< M:
result[first+N+i] = arg[first+i]
for i in 0 ..< m:
result[first+n+i] = arg[first+i]
for i in last ..< arg.len:
result[i] = arg[i]
proc rotateLeft*[T](arg: var openarray[T]; slice: HSlice[int, int]; dist: int): int {.discardable.} =
proc rotateLeft*[T](arg: var openArray[T]; slice: HSlice[int, int]; dist: int): int {.discardable.} =
## Performs a left rotation on a range of elements. If you want to rotate
## right, use a negative ``dist``. Specifically, ``rotateLeft`` rotates
## the elements at ``slice`` by ``dist`` positions.
@ -782,7 +782,7 @@ proc rotateLeft*[T](arg: var openarray[T]; slice: HSlice[int, int]; dist: int):
let distLeft = ((dist mod sliceLen) + sliceLen) mod sliceLen
arg.rotateInternal(slice.a, slice.a+distLeft, slice.b + 1)
proc rotateLeft*[T](arg: var openarray[T]; dist: int): int {.discardable.} =
proc rotateLeft*[T](arg: var openArray[T]; dist: int): int {.discardable.} =
## Default arguments for slice, so that this procedure operates on the entire
## ``arg``, and not just on a part of it.
##
@ -801,7 +801,7 @@ proc rotateLeft*[T](arg: var openarray[T]; dist: int): int {.discardable.} =
let distLeft = ((dist mod arglen) + arglen) mod arglen
arg.rotateInternal(0, distLeft, arglen)
proc rotatedLeft*[T](arg: openarray[T]; slice: HSlice[int, int], dist: int): seq[T] =
proc rotatedLeft*[T](arg: openArray[T]; slice: HSlice[int, int], dist: int): seq[T] =
## Same as ``rotateLeft``, just with the difference that it does
## not modify the argument. It creates a new ``seq`` instead.
##
@ -830,7 +830,7 @@ proc rotatedLeft*[T](arg: openarray[T]; slice: HSlice[int, int], dist: int): seq
let distLeft = ((dist mod sliceLen) + sliceLen) mod sliceLen
arg.rotatedInternal(slice.a, slice.a+distLeft, slice.b+1)
proc rotatedLeft*[T](arg: openarray[T]; dist: int): seq[T] =
proc rotatedLeft*[T](arg: openArray[T]; dist: int): seq[T] =
## Same as ``rotateLeft``, just with the difference that it does
## not modify the argument. It creates a new ``seq`` instead.
##

View file

@ -232,7 +232,7 @@ when defined(windows) or defined(nimdoc):
CompletionData* = object
fd*: AsyncFD # TODO: Rename this.
cb*: owned(proc (fd: AsyncFD, bytesTransferred: Dword,
cb*: owned(proc (fd: AsyncFD, bytesTransferred: DWORD,
errcode: OSErrorCode) {.closure, gcsafe.})
cell*: ForeignCell # we need this `cell` to protect our `cb` environment,
# when using RegisterWaitForSingleObject, because
@ -328,7 +328,7 @@ when defined(windows) or defined(nimdoc):
if at == -1: winlean.INFINITE
else: at.int32
var lpNumberOfBytesTransferred: Dword
var lpNumberOfBytesTransferred: DWORD
var lpCompletionKey: ULONG_PTR
var customOverlapped: PCustomOverlapped
let res = getQueuedCompletionStatus(p.ioPort,
@ -379,10 +379,10 @@ when defined(windows) or defined(nimdoc):
proc initPointer(s: SocketHandle, fun: var pointer, guid: var GUID): bool =
# Ref: https://github.com/powdahound/twisted/blob/master/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c
var bytesRet: Dword
var bytesRet: DWORD
fun = nil
result = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, addr guid,
sizeof(GUID).Dword, addr fun, sizeof(pointer).Dword,
sizeof(GUID).DWORD, addr fun, sizeof(pointer).DWORD,
addr bytesRet, nil, nil) == 0
proc initAll() =
@ -425,12 +425,12 @@ when defined(windows) or defined(nimdoc):
dataBuf.buf = cast[cstring](alloc0(size))
dataBuf.len = size.ULONG
var bytesReceived: Dword
var flagsio = flags.toOSFlags().Dword
var bytesReceived: DWORD
var flagsio = flags.toOSFlags().DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
if bytesCount == 0 and dataBuf.buf[0] == '\0':
@ -502,12 +502,12 @@ when defined(windows) or defined(nimdoc):
dataBuf.buf = cast[cstring](buf)
dataBuf.len = size.ULONG
var bytesReceived: Dword
var flagsio = flags.toOSFlags().Dword
var bytesReceived: DWORD
var flagsio = flags.toOSFlags().DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete(bytesCount)
@ -556,11 +556,11 @@ when defined(windows) or defined(nimdoc):
dataBuf.buf = cast[cstring](buf)
dataBuf.len = size.ULONG
var bytesReceived, lowFlags: Dword
var bytesReceived, lowFlags: DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete()
@ -589,7 +589,7 @@ when defined(windows) or defined(nimdoc):
return retFuture
proc sendTo*(socket: AsyncFD, data: pointer, size: int, saddr: ptr SockAddr,
saddrLen: Socklen,
saddrLen: SockLen,
flags = {SocketFlag.SafeDisconn}): owned(Future[void]) =
## Sends ``data`` to specified destination ``saddr``, using
## socket ``socket``. The returned future will complete once all data
@ -599,8 +599,8 @@ when defined(windows) or defined(nimdoc):
var dataBuf: TWSABuf
dataBuf.buf = cast[cstring](data)
dataBuf.len = size.ULONG
var bytesSent = 0.Dword
var lowFlags = 0.Dword
var bytesSent = 0.DWORD
var lowFlags = 0.DWORD
# we will preserve address in our stack
var staddr: array[128, char] # SOCKADDR_STORAGE size is 128 bytes
@ -611,7 +611,7 @@ when defined(windows) or defined(nimdoc):
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete()
@ -647,13 +647,13 @@ when defined(windows) or defined(nimdoc):
var dataBuf = TWSABuf(buf: cast[cstring](data), len: size.ULONG)
var bytesReceived = 0.Dword
var lowFlags = 0.Dword
var bytesReceived = 0.DWORD
var lowFlags = 0.DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
assert bytesCount <= size
@ -704,10 +704,10 @@ when defined(windows) or defined(nimdoc):
const lpOutputLen = 1024
var lpOutputBuf = newString(lpOutputLen)
var dwBytesReceived: Dword
let dwReceiveDataLength = 0.Dword # We don't want any data to be read.
let dwLocalAddressLength = Dword(sizeof(Sockaddr_in6) + 16)
let dwRemoteAddressLength = Dword(sizeof(Sockaddr_in6) + 16)
var dwBytesReceived: DWORD
let dwReceiveDataLength = 0.DWORD # We don't want any data to be read.
let dwLocalAddressLength = DWORD(sizeof(Sockaddr_in6) + 16)
let dwRemoteAddressLength = DWORD(sizeof(Sockaddr_in6) + 16)
template failAccept(errcode) =
if flags.isDisconnectionError(errcode):
@ -728,17 +728,17 @@ when defined(windows) or defined(nimdoc):
sizeof(listenSock).SockLen)
if setoptRet != 0:
let errcode = osLastError()
discard clientSock.closeSocket()
discard clientSock.closesocket()
failAccept(errcode)
else:
var localSockaddr, remoteSockaddr: ptr SockAddr
var localLen, remoteLen: int32
getAcceptExSockaddrs(addr lpOutputBuf[0], dwReceiveDataLength,
getAcceptExSockAddrs(addr lpOutputBuf[0], dwReceiveDataLength,
dwLocalAddressLength, dwRemoteAddressLength,
addr localSockaddr, addr localLen,
addr remoteSockaddr, addr remoteLen)
try:
let address = getAddrString(remoteSockAddr)
let address = getAddrString(remoteSockaddr)
register(clientSock.AsyncFD)
retFuture.complete((address: address, client: clientSock.AsyncFD))
except:
@ -749,7 +749,7 @@ when defined(windows) or defined(nimdoc):
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
completeAccept()
@ -793,14 +793,14 @@ when defined(windows) or defined(nimdoc):
proc waitableCallback(param: pointer,
timerOrWaitFired: WINBOOL): void {.stdcall.} =
var p = cast[PostCallbackDataPtr](param)
discard postQueuedCompletionStatus(p.ioPort, timerOrWaitFired.Dword,
discard postQueuedCompletionStatus(p.ioPort, timerOrWaitFired.DWORD,
ULONG_PTR(p.handleFd),
cast[pointer](p.ovl))
{.pop.}
proc registerWaitableEvent(fd: AsyncFD, cb: Callback; mask: Dword) =
proc registerWaitableEvent(fd: AsyncFD, cb: Callback; mask: DWORD) =
let p = getGlobalDispatcher()
var flags = (WT_EXECUTEINWAITTHREAD or WT_EXECUTEONLYONCE).Dword
var flags = (WT_EXECUTEINWAITTHREAD or WT_EXECUTEONLYONCE).DWORD
var hEvent = wsaCreateEvent()
if hEvent == 0:
raiseOSError(osLastError())
@ -811,7 +811,7 @@ when defined(windows) or defined(nimdoc):
GC_ref(ol)
ol.data = CompletionData(fd: fd, cb:
proc(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) {.gcsafe.} =
proc(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) {.gcsafe.} =
# we excluding our `fd` because cb(fd) can register own handler
# for this `fd`
p.handles.excl(fd)
@ -934,7 +934,7 @@ when defined(windows) or defined(nimdoc):
pcd.ovl = ol
if not registerWaitForSingleObject(addr(pcd.waitFd), hEvent,
cast[WAITORTIMERCALLBACK](waitableCallback),
cast[pointer](pcd), timeout.Dword, flags):
cast[pointer](pcd), timeout.DWORD, flags):
let err = osLastError()
GC_unref(ol)
deallocShared(cast[pointer](pcd))
@ -972,10 +972,10 @@ when defined(windows) or defined(nimdoc):
raiseOSError(osLastError())
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
var flags = WT_EXECUTEINWAITTHREAD.Dword
var flags = WT_EXECUTEINWAITTHREAD.DWORD
if oneshot: flags = flags or WT_EXECUTEONLYONCE
proc timercb(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc timercb(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
let res = cb(fd)
if res or oneshot:
closeWaitable(hEvent)
@ -993,14 +993,14 @@ when defined(windows) or defined(nimdoc):
## ``pid`` exited.
let p = getGlobalDispatcher()
let procFlags = SYNCHRONIZE
var hProcess = openProcess(procFlags, 0, pid.Dword)
var hProcess = openProcess(procFlags, 0, pid.DWORD)
if hProcess == INVALID_HANDLE_VALUE:
raiseOSError(osLastError())
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
var flags = WT_EXECUTEINWAITTHREAD.Dword
var flags = WT_EXECUTEINWAITTHREAD.DWORD
proc proccb(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc proccb(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
closeWaitable(hProcess)
discard cb(fd)
@ -1052,9 +1052,9 @@ when defined(windows) or defined(nimdoc):
let hEvent = ev.hEvent
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
var flags = WT_EXECUTEINWAITTHREAD.Dword
var flags = WT_EXECUTEINWAITTHREAD.DWORD
proc eventcb(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc eventcb(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if ev.hWaiter != 0:
if cb(fd):
# we need this check to avoid exception, if `unregister(event)` was
@ -1615,7 +1615,7 @@ when defined(windows) or defined(nimdoc):
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete()
@ -1708,7 +1708,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
curAddrInfo = curAddrInfo.ai_next
if curAddrInfo == nil:
freeAddrInfo(addrInfo)
freeaddrinfo(addrInfo)
when shouldCreateFd:
closeUnusedFds()
if lastException != nil:
@ -1724,7 +1724,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
try:
curFd = createAsyncNativeSocket(domain, sockType, protocol)
except:
freeAddrInfo(addrInfo)
freeaddrinfo(addrInfo)
closeUnusedFds()
raise getCurrentException()
when defined(windows):
@ -1734,7 +1734,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
doConnect(curFd, curAddrInfo).callback = tryNextAddrInfo
curAddrInfo = curAddrInfo.ai_next
else:
freeAddrInfo(addrInfo)
freeaddrinfo(addrInfo)
when shouldCreateFd:
closeUnusedFds(ord(domain))
retFuture.complete(curFd)

View file

@ -303,7 +303,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
# Find longest filename & line number combo for alignment purposes.
var longestLeft = 0
for entry in entries:
if entry.procName.isNil: continue
if entry.procname.isNil: continue
let left = $entry.filename & $entry.line
if left.len > longestLeft:
@ -312,7 +312,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
var indent = 2
# Format the entries.
for entry in entries:
if entry.procName.isNil:
if entry.procname.isNil:
if entry.line == -10:
result.add(spaces(indent) & "#[\n")
indent.inc(2)
@ -325,7 +325,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
result.add((spaces(indent) & "$#$# $#\n") % [
left,
spaces(longestLeft - left.len + 2),
$entry.procName
$entry.procname
])
let hint = getHint(entry)
if hint.len > 0:

View file

@ -121,7 +121,7 @@ when defined(nimHasalignOf):
# #### Pure Nim version ####
proc firstSetBit_nim(x: uint32): int {.inline, nosideeffect.} =
proc firstSetBitNim(x: uint32): int {.inline, noSideEffect.} =
## Returns the 1-based index of the least significant set bit of x, or if x is zero, returns zero.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#ZerosOnRightMultLookup
const lookup: array[32, uint8] = [0'u8, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15,
@ -130,7 +130,7 @@ proc firstSetBit_nim(x: uint32): int {.inline, nosideeffect.} =
var k = not v + 1 # get two's complement # cast[uint32](-cast[int32](v))
result = 1 + lookup[uint32((v and k) * 0x077CB531'u32) shr 27].int
proc firstSetBit_nim(x: uint64): int {.inline, nosideeffect.} =
proc firstSetBitNim(x: uint64): int {.inline, noSideEffect.} =
## Returns the 1-based index of the least significant set bit of x, or if x is zero, returns zero.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#ZerosOnRightMultLookup
var v = uint64(x)
@ -138,9 +138,9 @@ proc firstSetBit_nim(x: uint64): int {.inline, nosideeffect.} =
if k == 0:
k = uint32(v shr 32'u32) and 0xFFFFFFFF'u32
result = 32
result += firstSetBit_nim(k)
result += firstSetBitNim(k)
proc fastlog2_nim(x: uint32): int {.inline, nosideeffect.} =
proc fastlog2Nim(x: uint32): int {.inline, noSideEffect.} =
## Quickly find the log base 2 of a 32-bit or less integer.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogDeBruijn
# https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers
@ -154,7 +154,7 @@ proc fastlog2_nim(x: uint32): int {.inline, nosideeffect.} =
v = v or v shr 16
result = lookup[uint32(v * 0x07C4ACDD'u32) shr 27].int
proc fastlog2_nim(x: uint64): int {.inline, nosideeffect.} =
proc fastlog2Nim(x: uint64): int {.inline, noSideEffect.} =
## Quickly find the log base 2 of a 64-bit integer.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogDeBruijn
# https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers
@ -176,10 +176,10 @@ proc fastlog2_nim(x: uint64): int {.inline, nosideeffect.} =
# countBits32 and countBits64.
include system/sets
template countSetBits_nim(n: uint32): int = countBits32(n)
template countSetBits_nim(n: uint64): int = countBits64(n)
template countSetBitsNim(n: uint32): int = countBits32(n)
template countSetBitsNim(n: uint64): int = countBits64(n)
template parity_impl[T](value: T): int =
template parityImpl[T](value: T): int =
# formula id from: https://graphics.stanford.edu/%7Eseander/bithacks.html#ParityParallel
var v = value
when sizeof(T) == 8:
@ -216,17 +216,17 @@ when useGCC_builtins:
elif useVCC_builtins:
# Counts the number of one bits (population count) in a 16-, 32-, or 64-byte unsigned integer.
proc builtin_popcnt16(a2: uint16): uint16 {.importc: "__popcnt16" header: "<intrin.h>", nosideeffect.}
proc builtin_popcnt32(a2: uint32): uint32 {.importc: "__popcnt" header: "<intrin.h>", nosideeffect.}
proc builtin_popcnt64(a2: uint64): uint64 {.importc: "__popcnt64" header: "<intrin.h>", nosideeffect.}
proc builtin_popcnt16(a2: uint16): uint16 {.importc: "__popcnt16" header: "<intrin.h>", noSideEffect.}
proc builtin_popcnt32(a2: uint32): uint32 {.importc: "__popcnt" header: "<intrin.h>", noSideEffect.}
proc builtin_popcnt64(a2: uint64): uint64 {.importc: "__popcnt64" header: "<intrin.h>", noSideEffect.}
# Search the mask data from most significant bit (MSB) to least significant bit (LSB) for a set bit (1).
proc bitScanReverse(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanReverse", header: "<intrin.h>", nosideeffect.}
proc bitScanReverse64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanReverse64", header: "<intrin.h>", nosideeffect.}
proc bitScanReverse(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanReverse", header: "<intrin.h>", noSideEffect.}
proc bitScanReverse64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanReverse64", header: "<intrin.h>", noSideEffect.}
# Search the mask data from least significant bit (LSB) to the most significant bit (MSB) for a set bit (1).
proc bitScanForward(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanForward", header: "<intrin.h>", nosideeffect.}
proc bitScanForward64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanForward64", header: "<intrin.h>", nosideeffect.}
proc bitScanForward(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanForward", header: "<intrin.h>", noSideEffect.}
proc bitScanForward64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanForward64", header: "<intrin.h>", noSideEffect.}
template vcc_scan_impl(fnc: untyped; v: untyped): int =
var index: culong
@ -238,16 +238,16 @@ elif useICC_builtins:
# Intel compiler intrinsics: http://fulla.fnal.gov/intel/compiler_c/main_cls/intref_cls/common/intref_allia_misc.htm
# see also: https://software.intel.com/en-us/node/523362
# Count the number of bits set to 1 in an integer a, and return that count in dst.
proc builtin_popcnt32(a: cint): cint {.importc: "_popcnt" header: "<immintrin.h>", nosideeffect.}
proc builtin_popcnt64(a: uint64): cint {.importc: "_popcnt64" header: "<immintrin.h>", nosideeffect.}
proc builtin_popcnt32(a: cint): cint {.importc: "_popcnt" header: "<immintrin.h>", noSideEffect.}
proc builtin_popcnt64(a: uint64): cint {.importc: "_popcnt64" header: "<immintrin.h>", noSideEffect.}
# Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.
proc bitScanForward(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanForward", header: "<immintrin.h>", nosideeffect.}
proc bitScanForward64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanForward64", header: "<immintrin.h>", nosideeffect.}
proc bitScanForward(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanForward", header: "<immintrin.h>", noSideEffect.}
proc bitScanForward64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanForward64", header: "<immintrin.h>", noSideEffect.}
# Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.
proc bitScanReverse(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanReverse", header: "<immintrin.h>", nosideeffect.}
proc bitScanReverse64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanReverse64", header: "<immintrin.h>", nosideeffect.}
proc bitScanReverse(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanReverse", header: "<immintrin.h>", noSideEffect.}
proc bitScanReverse64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanReverse64", header: "<immintrin.h>", noSideEffect.}
template icc_scan_impl(fnc: untyped; v: untyped): int =
var index: uint32
@ -255,14 +255,14 @@ elif useICC_builtins:
index.int
proc countSetBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc countSetBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Counts the set bits in integer. (also called `Hamming weight`:idx:.)
# TODO: figure out if ICC support _popcnt32/_popcnt64 on platform without POPCNT.
# like GCC and MSVC
when x is SomeSignedInt:
let x = x.toUnsigned
when nimvm:
result = forwardImpl(countSetBits_nim, x)
result = forwardImpl(countSetBitsNim, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = builtin_popcount(x.cuint).int
@ -279,14 +279,14 @@ proc countSetBits*(x: SomeInteger): int {.inline, nosideeffect.} =
else: result = builtin_popcnt32((x.uint64 and 0xFFFFFFFF'u64).cint ).int +
builtin_popcnt32((x.uint64 shr 32'u64).cint ).int
else:
when sizeof(x) <= 4: result = countSetBits_nim(x.uint32)
else: result = countSetBits_nim(x.uint64)
when sizeof(x) <= 4: result = countSetBitsNim(x.uint32)
else: result = countSetBitsNim(x.uint64)
proc popcount*(x: SomeInteger): int {.inline, nosideeffect.} =
proc popcount*(x: SomeInteger): int {.inline, noSideEffect.} =
## Alias for for countSetBits (Hamming weight.)
result = countSetBits(x)
proc parityBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc parityBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Calculate the bit parity in integer. If number of 1-bit
## is odd parity is 1, otherwise 0.
# Can be used a base if creating ASM version.
@ -294,16 +294,16 @@ proc parityBits*(x: SomeInteger): int {.inline, nosideeffect.} =
when x is SomeSignedInt:
let x = x.toUnsigned
when nimvm:
result = forwardImpl(parity_impl, x)
result = forwardImpl(parityImpl, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = builtin_parity(x.uint32).int
else: result = builtin_parityll(x.uint64).int
else:
when sizeof(x) <= 4: result = parity_impl(x.uint32)
else: result = parity_impl(x.uint64)
when sizeof(x) <= 4: result = parityImpl(x.uint32)
else: result = parityImpl(x.uint64)
proc firstSetBit*(x: SomeInteger): int {.inline, nosideeffect.} =
proc firstSetBit*(x: SomeInteger): int {.inline, noSideEffect.} =
## Returns the 1-based index of the least significant set bit of x.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
## otherwise result is undefined.
@ -314,7 +314,7 @@ proc firstSetBit*(x: SomeInteger): int {.inline, nosideeffect.} =
when noUndefined:
if x == 0:
return 0
result = forwardImpl(firstSetBit_nim, x)
result = forwardImpl(firstSetBitNim, x)
else:
when noUndefined and not useGCC_builtins:
if x == 0:
@ -328,19 +328,19 @@ proc firstSetBit*(x: SomeInteger): int {.inline, nosideeffect.} =
elif arch64:
result = 1 + vcc_scan_impl(bitScanForward64, x.uint64)
else:
result = firstSetBit_nim(x.uint64)
result = firstSetBitNim(x.uint64)
elif useICC_builtins:
when sizeof(x) <= 4:
result = 1 + icc_scan_impl(bitScanForward, x.uint32)
elif arch64:
result = 1 + icc_scan_impl(bitScanForward64, x.uint64)
else:
result = firstSetBit_nim(x.uint64)
result = firstSetBitNim(x.uint64)
else:
when sizeof(x) <= 4: result = firstSetBit_nim(x.uint32)
else: result = firstSetBit_nim(x.uint64)
when sizeof(x) <= 4: result = firstSetBitNim(x.uint32)
else: result = firstSetBitNim(x.uint64)
proc fastLog2*(x: SomeInteger): int {.inline, nosideeffect.} =
proc fastLog2*(x: SomeInteger): int {.inline, noSideEffect.} =
## Quickly find the log base 2 of an integer.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is -1,
## otherwise result is undefined.
@ -350,7 +350,7 @@ proc fastLog2*(x: SomeInteger): int {.inline, nosideeffect.} =
if x == 0:
return -1
when nimvm:
result = forwardImpl(fastlog2_nim, x)
result = forwardImpl(fastlog2Nim, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = 31 - builtin_clz(x.uint32).int
@ -361,19 +361,19 @@ proc fastLog2*(x: SomeInteger): int {.inline, nosideeffect.} =
elif arch64:
result = vcc_scan_impl(bitScanReverse64, x.uint64)
else:
result = fastlog2_nim(x.uint64)
result = fastlog2Nim(x.uint64)
elif useICC_builtins:
when sizeof(x) <= 4:
result = icc_scan_impl(bitScanReverse, x.uint32)
elif arch64:
result = icc_scan_impl(bitScanReverse64, x.uint64)
else:
result = fastlog2_nim(x.uint64)
result = fastlog2Nim(x.uint64)
else:
when sizeof(x) <= 4: result = fastlog2_nim(x.uint32)
else: result = fastlog2_nim(x.uint64)
when sizeof(x) <= 4: result = fastlog2Nim(x.uint32)
else: result = fastlog2Nim(x.uint64)
proc countLeadingZeroBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc countLeadingZeroBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Returns the number of leading zero bits in integer.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
## otherwise result is undefined.
@ -383,16 +383,16 @@ proc countLeadingZeroBits*(x: SomeInteger): int {.inline, nosideeffect.} =
if x == 0:
return 0
when nimvm:
result = sizeof(x)*8 - 1 - forwardImpl(fastlog2_nim, x)
result = sizeof(x)*8 - 1 - forwardImpl(fastlog2Nim, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = builtin_clz(x.uint32).int - (32 - sizeof(x)*8)
else: result = builtin_clzll(x.uint64).int
else:
when sizeof(x) <= 4: result = sizeof(x)*8 - 1 - fastlog2_nim(x.uint32)
else: result = sizeof(x)*8 - 1 - fastlog2_nim(x.uint64)
when sizeof(x) <= 4: result = sizeof(x)*8 - 1 - fastlog2Nim(x.uint32)
else: result = sizeof(x)*8 - 1 - fastlog2Nim(x.uint64)
proc countTrailingZeroBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc countTrailingZeroBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Returns the number of trailing zeros in integer.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
## otherwise result is undefined.
@ -471,7 +471,7 @@ proc repeatBits[T: SomeUnsignedInt](x: SomeUnsignedInt; retType: type[T]): T {.
while i != (sizeof(T) div sizeof(x)):
result = (result shl (sizeof(x)*8*i)) or result
i *= 2
proc reverseBits*[T: SomeUnsignedInt](x: T): T {.noSideEffect.} =
## Return the bit reversal of x.
runnableExamples:

View file

@ -286,7 +286,7 @@ proc enlarge[A, B](t: var Table[A, B]) =
# ------------------------------ Table ------------------------------
# -------------------------------------------------------------------
proc initTable*[A, B](initialsize = defaultInitialSize): Table[A, B] =
proc initTable*[A, B](initialSize = defaultInitialSize): Table[A, B] =
## Creates a new hash table that is empty.
##
## ``initialSize`` must be a power of two (default: 64).
@ -1263,7 +1263,7 @@ template forAllOrderedPairs(yieldStmt: untyped) {.dirty.} =
# ----------------------------------------------------------------------
proc initOrderedTable*[A, B](initialsize = defaultInitialSize): OrderedTable[A, B] =
proc initOrderedTable*[A, B](initialSize = defaultInitialSize): OrderedTable[A, B] =
## Creates a new ordered hash table that is empty.
##
## ``initialSize`` must be a power of two (default: 64).
@ -2185,7 +2185,7 @@ proc inc*[A](t: var CountTable[A], key: A, val = 1)
# ----------------------------------------------------------------------
proc initCountTable*[A](initialsize = defaultInitialSize): CountTable[A] =
proc initCountTable*[A](initialSize = defaultInitialSize): CountTable[A] =
## Creates a new count table that is empty.
##
## ``initialSize`` must be a power of two (default: 64).

View file

@ -59,7 +59,7 @@ import strutils
type
LibHandle* = pointer ## a handle to a dynamically loaded library
proc loadLib*(path: string, global_symbols=false): LibHandle {.gcsafe.}
proc loadLib*(path: string, globalSymbols=false): LibHandle {.gcsafe.}
## loads a library from `path`. Returns nil if the library could not
## be loaded.
@ -96,14 +96,14 @@ proc libCandidates*(s: string, dest: var seq[string]) =
else:
add(dest, s)
proc loadLibPattern*(pattern: string, global_symbols=false): LibHandle =
proc loadLibPattern*(pattern: string, globalSymbols=false): LibHandle =
## loads a library with name matching `pattern`, similar to what `dlimport`
## pragma does. Returns nil if the library could not be loaded.
## Warning: this proc uses the GC and so cannot be used to load the GC.
var candidates = newSeq[string]()
libCandidates(pattern, candidates)
for c in candidates:
result = loadLib(c, global_symbols)
result = loadLib(c, globalSymbols)
if not result.isNil: break
when defined(posix) and not defined(nintendoswitch):
@ -117,9 +117,9 @@ when defined(posix) and not defined(nintendoswitch):
#
import posix
proc loadLib(path: string, global_symbols=false): LibHandle =
proc loadLib(path: string, globalSymbols=false): LibHandle =
let flags =
if global_symbols: RTLD_NOW or RTLD_GLOBAL
if globalSymbols: RTLD_NOW or RTLD_GLOBAL
else: RTLD_NOW
dlopen(path, flags)
@ -170,7 +170,7 @@ elif defined(windows) or defined(dos):
proc getProcAddress(lib: THINSTANCE, name: cstring): pointer {.
importc: "GetProcAddress", header: "<windows.h>", stdcall.}
proc loadLib(path: string, global_symbols=false): LibHandle =
proc loadLib(path: string, globalSymbols=false): LibHandle =
result = cast[LibHandle](winLoadLibrary(path))
proc loadLib(): LibHandle =
result = cast[LibHandle](winLoadLibrary(nil))

View file

@ -13,33 +13,33 @@
when defined(gcc) or defined(llvm_gcc) or defined(clang):
const useBuiltinSwap = true
proc builtin_bswap16(a: uint16): uint16 {.
importc: "__builtin_bswap16", nodecl, nosideeffect.}
importc: "__builtin_bswap16", nodecl, noSideEffect.}
proc builtin_bswap32(a: uint32): uint32 {.
importc: "__builtin_bswap32", nodecl, nosideeffect.}
importc: "__builtin_bswap32", nodecl, noSideEffect.}
proc builtin_bswap64(a: uint64): uint64 {.
importc: "__builtin_bswap64", nodecl, nosideeffect.}
importc: "__builtin_bswap64", nodecl, noSideEffect.}
elif defined(icc):
const useBuiltinSwap = true
proc builtin_bswap16(a: uint16): uint16 {.
importc: "_bswap16", nodecl, nosideeffect.}
importc: "_bswap16", nodecl, noSideEffect.}
proc builtin_bswap32(a: uint32): uint32 {.
importc: "_bswap", nodecl, nosideeffect.}
importc: "_bswap", nodecl, noSideEffect.}
proc builtin_bswap64(a: uint64): uint64 {.
importc: "_bswap64", nodecl, nosideeffect.}
importc: "_bswap64", nodecl, noSideEffect.}
elif defined(vcc):
const useBuiltinSwap = true
proc builtin_bswap16(a: uint16): uint16 {.
importc: "_byteswap_ushort", nodecl, header: "<intrin.h>", nosideeffect.}
importc: "_byteswap_ushort", nodecl, header: "<intrin.h>", noSideEffect.}
proc builtin_bswap32(a: uint32): uint32 {.
importc: "_byteswap_ulong", nodecl, header: "<intrin.h>", nosideeffect.}
importc: "_byteswap_ulong", nodecl, header: "<intrin.h>", noSideEffect.}
proc builtin_bswap64(a: uint64): uint64 {.
importc: "_byteswap_uint64", nodecl, header: "<intrin.h>", nosideeffect.}
importc: "_byteswap_uint64", nodecl, header: "<intrin.h>", noSideEffect.}
else:
const useBuiltinSwap = false
@ -49,17 +49,17 @@ when useBuiltinSwap:
## may point to a unaligned address. A sufficiently smart compiler _should_
## be able to elide them when they're not necessary.
var tmp: T
copyMem(addr tmp, inp, sizeOf(T))
copyMem(addr tmp, inp, sizeof(T))
tmp = op(tmp)
copyMem(outp, addr tmp, sizeOf(T))
copyMem(outp, addr tmp, sizeof(T))
proc swapEndian64*(outp, inp: pointer) {.inline, nosideeffect.}=
proc swapEndian64*(outp, inp: pointer) {.inline, noSideEffect.}=
swapOpImpl(uint64, builtin_bswap64)
proc swapEndian32*(outp, inp: pointer) {.inline, nosideeffect.}=
proc swapEndian32*(outp, inp: pointer) {.inline, noSideEffect.}=
swapOpImpl(uint32, builtin_bswap32)
proc swapEndian16*(outp, inp: pointer) {.inline, nosideeffect.}=
proc swapEndian16*(outp, inp: pointer) {.inline, noSideEffect.}=
swapOpImpl(uint16, builtin_bswap16)
else:

View file

@ -169,7 +169,7 @@ template hashImpl(result: Hash, x: typed, start, stop: int) =
var n = 0
when nimvm:
# we cannot cast in VM, so we do it manually
for j in countdown(stepsize-1, 0):
for j in countdown(stepSize-1, 0):
n = (n shl (8*elementSize)) or ord(x[i+j])
else:
n = cast[ptr Hash](unsafeAddr x[i])[]

View file

@ -324,7 +324,7 @@ proc `%`*(b: bool): JsonNode =
proc `%`*(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode =
## Generic constructor for JSON data. Creates a new `JObject JsonNode`
if keyvals.len == 0: return newJArray()
if keyVals.len == 0: return newJArray()
result = newJObject()
for key, val in items(keyVals): result.fields[key] = val
@ -380,7 +380,7 @@ proc `%`*(o: enum): JsonNode =
## string. Creates a new ``JString JsonNode``.
result = %($o)
proc toJson(x: NimNode): NimNode {.compiletime.} =
proc toJson(x: NimNode): NimNode {.compileTime.} =
case x.kind
of nnkBracket: # array
if x.len == 0: return newCall(bindSym"newJArray")

View file

@ -15,6 +15,9 @@
## * `hashes module<hashes.html>`_ for efficient computations of hash values
## for diverse Nim types
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
type
MD5State = array[0..3, uint32]
MD5Block = array[0..15, uint32]
@ -197,7 +200,7 @@ proc `$`*(d: MD5Digest): string =
add(result, digits[d[i].int and 0xF])
proc getMD5*(s: string): string =
## Computes an MD5 value of `s` and returns its string representation.
## Computes an MD5 value of `s` and returns its string representation.
## .. note::
## available at compile time
##
@ -232,7 +235,7 @@ proc md5Init*(c: var MD5Context) =
c.state[3] = 0x10325476'u32
c.count[0] = 0'u32
c.count[1] = 0'u32
zeroMem(addr(c.buffer), sizeof(MD5buffer))
zeroMem(addr(c.buffer), sizeof(MD5Buffer))
proc md5Update*(c: var MD5Context, input: cstring, len: int) =
## Updates the `MD5Context` with the `input` data of length `len`.
@ -280,3 +283,6 @@ when isMainModule:
assert(getMD5("Frank jagt im komplett verwahrlosten Taxi quer durch Bayern") ==
"7e716d0e702df0505fc72e2b89467910")
assert($toMD5("") == "d41d8cd98f00b204e9800998ecf8427e")
when defined(nimHasStyleChecks):
{.pop.} #{.push styleChecks: off.}

View file

@ -354,11 +354,11 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} =
else:
raiseOSError(osLastError(), "unknown h_addrtype")
if result.addrtype == AF_INET:
result.addrlist = @[]
result.addrList = @[]
var i = 0
while not isNil(s.h_addrlist[i]):
while not isNil(s.h_addr_list[i]):
var inaddr_ptr = cast[ptr InAddr](s.h_addr_list[i])
result.addrlist.add($inet_ntoa(inaddr_ptr[]))
result.addrList.add($inet_ntoa(inaddr_ptr[]))
inc(i)
else:
result.addrList = cstringArrayToSeq(s.h_addr_list)
@ -383,11 +383,11 @@ proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} =
else:
raiseOSError(osLastError(), "unknown h_addrtype")
if result.addrtype == AF_INET:
result.addrlist = @[]
result.addrList = @[]
var i = 0
while not isNil(s.h_addrlist[i]):
while not isNil(s.h_addr_list[i]):
var inaddr_ptr = cast[ptr InAddr](s.h_addr_list[i])
result.addrlist.add($inet_ntoa(inaddr_ptr[]))
result.addrList.add($inet_ntoa(inaddr_ptr[]))
inc(i)
else:
result.addrList = cstringArrayToSeq(s.h_addr_list)
@ -400,7 +400,7 @@ proc getHostname*(): string {.tags: [ReadIOEffect].} =
const size = 64
result = newString(size)
when useWinVersion:
let success = winlean.getHostname(result, size)
let success = winlean.gethostname(result, size)
else:
# Posix
let success = posix.getHostname(result, size)
@ -613,7 +613,7 @@ proc selectRead*(readfds: var seq[SocketHandle], timeout = 500): int =
##
## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
## an unlimited time.
var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
var rd: TFdSet
var m = 0
@ -635,7 +635,7 @@ proc selectWrite*(writefds: var seq[SocketHandle],
##
## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
## an unlimited time.
var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
var wr: TFdSet
var m = 0

View file

@ -398,35 +398,35 @@ proc isIpAddress*(addressStr: string): bool {.tags: [].} =
return true
proc toSockAddr*(address: IpAddress, port: Port, sa: var Sockaddr_storage,
sl: var Socklen) =
sl: var SockLen) =
## Converts `IpAddress` and `Port` to `SockAddr` and `Socklen`
let port = htons(uint16(port))
case address.family
of IpAddressFamily.IPv4:
sl = sizeof(Sockaddr_in).Socklen
sl = sizeof(Sockaddr_in).SockLen
let s = cast[ptr Sockaddr_in](addr sa)
s.sin_family = type(s.sin_family)(toInt(AF_INET))
s.sin_port = port
copyMem(addr s.sin_addr, unsafeAddr address.address_v4[0],
sizeof(s.sin_addr))
of IpAddressFamily.IPv6:
sl = sizeof(Sockaddr_in6).Socklen
sl = sizeof(Sockaddr_in6).SockLen
let s = cast[ptr Sockaddr_in6](addr sa)
s.sin6_family = type(s.sin6_family)(toInt(AF_INET6))
s.sin6_port = port
copyMem(addr s.sin6_addr, unsafeAddr address.address_v6[0],
sizeof(s.sin6_addr))
proc fromSockAddrAux(sa: ptr Sockaddr_storage, sl: Socklen,
proc fromSockAddrAux(sa: ptr Sockaddr_storage, sl: SockLen,
address: var IpAddress, port: var Port) =
if sa.ss_family.cint == toInt(AF_INET) and sl == sizeof(Sockaddr_in).Socklen:
if sa.ss_family.cint == toInt(AF_INET) and sl == sizeof(Sockaddr_in).SockLen:
address = IpAddress(family: IpAddressFamily.IPv4)
let s = cast[ptr Sockaddr_in](sa)
copyMem(addr address.address_v4[0], addr s.sin_addr,
sizeof(address.address_v4))
port = ntohs(s.sin_port).Port
elif sa.ss_family.cint == toInt(AF_INET6) and
sl == sizeof(Sockaddr_in6).Socklen:
sl == sizeof(Sockaddr_in6).SockLen:
address = IpAddress(family: IpAddressFamily.IPv6)
let s = cast[ptr Sockaddr_in6](sa)
copyMem(addr address.address_v6[0], addr s.sin6_addr,
@ -436,7 +436,7 @@ proc fromSockAddrAux(sa: ptr Sockaddr_storage, sl: Socklen,
raise newException(ValueError, "Neither IPv4 nor IPv6")
proc fromSockAddr*(sa: Sockaddr_storage | SockAddr | Sockaddr_in | Sockaddr_in6,
sl: Socklen, address: var IpAddress, port: var Port) {.inline.} =
sl: SockLen, address: var IpAddress, port: var Port) {.inline.} =
## Converts `SockAddr` and `Socklen` to `IpAddress` and `Port`. Raises
## `ObjectConversionError` in case of invalid `sa` and `sl` arguments.
fromSockAddrAux(cast[ptr Sockaddr_storage](unsafeAddr sa), sl, address, port)
@ -762,9 +762,9 @@ proc bindAddr*(socket: Socket, port = Port(0), address = "") {.
var aiList = getAddrInfo(realaddr, port, socket.domain)
if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
freeAddrInfo(aiList)
freeaddrinfo(aiList)
raiseOSError(osLastError())
freeAddrInfo(aiList)
freeaddrinfo(aiList)
proc acceptAddr*(server: Socket, client: var owned(Socket), address: var string,
flags = {SocketFlag.SafeDisconn}) {.
@ -1378,7 +1378,7 @@ proc sendTo*(socket: Socket, address: string, port: Port, data: pointer,
it = it.ai_next
let osError = osLastError()
freeAddrInfo(aiList)
freeaddrinfo(aiList)
if not success:
raiseOSError(osError)
@ -1405,6 +1405,9 @@ proc isSsl*(socket: Socket): bool =
proc getFd*(socket: Socket): SocketHandle = return socket.fd
## Returns the socket's file descriptor
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
proc IPv4_any*(): IpAddress =
## Returns the IPv4 any address, which can be used to listen on all available
## network adapters
@ -1437,6 +1440,9 @@ proc IPv6_loopback*(): IpAddress =
family: IpAddressFamily.IPv6,
address_v6: [0'u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
when defined(nimHasStyleChecks):
{.pop.}
proc `==`*(lhs, rhs: IpAddress): bool =
## Compares two IpAddresses for Equality. Returns true if the addresses are equal
if lhs.family != rhs.family: return false
@ -1547,7 +1553,7 @@ proc dial*(address: string, port: Port,
# network system problem (e.g. not enough FDs), and not an unreachable
# address.
let err = osLastError()
freeAddrInfo(aiList)
freeaddrinfo(aiList)
closeUnusedFds()
raiseOSError(err)
fdPerDomain[ord(domain)] = lastFd
@ -1556,7 +1562,7 @@ proc dial*(address: string, port: Port,
break
lastError = osLastError()
it = it.ai_next
freeAddrInfo(aiList)
freeaddrinfo(aiList)
closeUnusedFds(ord(domain))
if success:
@ -1586,7 +1592,7 @@ proc connect*(socket: Socket, address: string,
else: lastError = osLastError()
it = it.ai_next
freeAddrInfo(aiList)
freeaddrinfo(aiList)
if not success: raiseOSError(lastError)
when defineSsl:
@ -1634,7 +1640,7 @@ proc connectAsync(socket: Socket, name: string, port = Port(0),
it = it.ai_next
freeAddrInfo(aiList)
freeaddrinfo(aiList)
if not success: raiseOSError(lastError)
proc connect*(socket: Socket, address: string, port = Port(0),

View file

@ -934,13 +934,13 @@ when defined(windows) and not weirdTarget:
template getCommandLine(): untyped = getCommandLineW()
template getFilename(f: untyped): untyped =
$cast[WideCString](addr(f.cFilename[0]))
$cast[WideCString](addr(f.cFileName[0]))
else:
template findFirstFile(a, b: untyped): untyped = findFirstFileA(a, b)
template findNextFile(a, b: untyped): untyped = findNextFileA(a, b)
template getCommandLine(): untyped = getCommandLineA()
template getFilename(f: untyped): untyped = $f.cFilename
template getFilename(f: untyped): untyped = $f.cFileName
proc skipFindData(f: WIN32_FIND_DATA): bool {.inline.} =
# Note - takes advantage of null delimiter in the cstring
@ -1035,7 +1035,7 @@ const
when defined(windows): ["exe", "cmd", "bat"] else: [""]
proc findExe*(exe: string, followSymlinks: bool = true;
extensions: openarray[string]=ExeExts): string {.
extensions: openArray[string]=ExeExts): string {.
tags: [ReadDirEffect, ReadEnvEffect, ReadIOEffect], noNimScript.} =
## Searches for `exe` in the current working directory and then
## in directories listed in the ``PATH`` environment variable.
@ -2867,7 +2867,7 @@ template rawToFormalFileInfo(rawInfo, path, formalInfo): untyped =
formalInfo.permissions.incl(formalMode)
formalInfo.id = (rawInfo.st_dev, rawInfo.st_ino)
formalInfo.size = rawInfo.st_size
formalInfo.linkCount = rawInfo.st_Nlink.BiggestInt
formalInfo.linkCount = rawInfo.st_nlink.BiggestInt
formalInfo.lastAccessTime = rawInfo.st_atim.toTime
formalInfo.lastWriteTime = rawInfo.st_mtim.toTime
formalInfo.creationTime = rawInfo.st_ctim.toTime

View file

@ -501,7 +501,7 @@ when defined(Windows) and not defined(useNimRtl):
#var
# O_WRONLY {.importc: "_O_WRONLY", header: "<fcntl.h>".}: int
# O_RDONLY {.importc: "_O_RDONLY", header: "<fcntl.h>".}: int
proc myDup(h: Handle; inherit: WinBool=1): Handle =
proc myDup(h: Handle; inherit: WINBOOL=1): Handle =
let thisProc = getCurrentProcess()
if duplicateHandle(thisProc, h,
thisProc, addr result,0,inherit,
@ -594,11 +594,11 @@ when defined(Windows) and not defined(useNimRtl):
else:
createPipeHandles(he, si.hStdError)
if setHandleInformation(he, DWORD(1), DWORD(0)) == 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
if setHandleInformation(hi, DWORD(1), DWORD(0)) == 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
if setHandleInformation(ho, DWORD(1), DWORD(0)) == 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
else:
createAllPipeHandles(si, hi, ho, he, cast[int](result))
result.inHandle = FileHandle(hi)
@ -1086,10 +1086,10 @@ elif not defined(useNimRtl):
discard close(p.errHandle)
proc suspend(p: Process) =
if kill(p.id, SIGSTOP) != 0'i32: raiseOsError(osLastError())
if kill(p.id, SIGSTOP) != 0'i32: raiseOSError(osLastError())
proc resume(p: Process) =
if kill(p.id, SIGCONT) != 0'i32: raiseOsError(osLastError())
if kill(p.id, SIGCONT) != 0'i32: raiseOSError(osLastError())
proc running(p: Process): bool =
if p.exitFlag:
@ -1111,11 +1111,11 @@ elif not defined(useNimRtl):
proc terminate(p: Process) =
if kill(p.id, SIGTERM) != 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
proc kill(p: Process) =
if kill(p.id, SIGKILL) != 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
when defined(macosx) or defined(freebsd) or defined(netbsd) or
defined(openbsd) or defined(dragonfly):

View file

@ -505,7 +505,7 @@ proc formatValue*(result: var string; value: string; specifier: string) =
"invalid type in format string for string, expected 's', but got " &
spec.typ)
if spec.precision != -1:
if spec.precision < runelen(value):
if spec.precision < runeLen(value):
setLen(value, runeOffset(value, spec.precision))
result.add alignString(value, spec.minimumWidth, spec.align, spec.fill)

View file

@ -115,7 +115,7 @@ const
IdentStartChars* = {'a'..'z', 'A'..'Z', '_'}
## the set of characters an identifier can start with
NewLines* = {'\13', '\10'}
Newlines* = {'\13', '\10'}
## the set of characters a newline terminator can start with (carriage
## return, line feed)
@ -2360,7 +2360,7 @@ proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault,
for i in 0 ..< L:
# Depending on the locale either dot or comma is produced,
# but nothing else is possible:
if buf[i] in {'.', ','}: result[i] = decimalsep
if buf[i] in {'.', ','}: result[i] = decimalSep
else: result[i] = buf[i]
when defined(windows):
# VS pre 2015 violates the C standard: "The exponent always contains at
@ -2447,7 +2447,7 @@ proc formatSize*(bytes: int64,
var
xb: int64 = bytes
fbytes: float
last_xb: int64 = bytes
lastXb: int64 = bytes
matchedIndex: int
prefixes: array[9, string]
if prefix == bpColloquial:
@ -2458,11 +2458,11 @@ proc formatSize*(bytes: int64,
# Iterate through prefixes seeing if value will be greater than
# 0 in each case
for index in 1..<prefixes.len:
last_xb = xb
lastXb = xb
xb = bytes div (1'i64 shl (index*10))
matchedIndex = index
if xb == 0:
xb = last_xb
xb = lastXb
matchedIndex = index - 1
break
# xb has the integer number for the latest value; index should be correct
@ -2902,7 +2902,7 @@ proc editDistance*(a, b: string): int {.noSideEffect,
for i in 1 .. len1 - 1:
var char1 = a[i + s - 1]
var char2p: int
var D, x: int
var diff, x: int
var p: int
if i >= len1 - half:
# skip the upper triangle:
@ -2913,33 +2913,33 @@ proc editDistance*(a, b: string): int {.noSideEffect,
inc(p)
inc(char2p)
x = row[p] + 1
D = x
diff = x
if x > c3: x = c3
row[p] = x
inc(p)
else:
p = 1
char2p = 0
D = i
diff = i
x = i
if i <= half + 1:
# skip the lower triangle:
e = len2 + i - half - 2
# main:
while p <= e:
dec(D)
var c3 = D + ord(char1 != b[char2p + s])
dec(diff)
var c3 = diff + ord(char1 != b[char2p + s])
inc(char2p)
inc(x)
if x > c3: x = c3
D = row[p] + 1
if x > D: x = D
diff = row[p] + 1
if x > diff: x = diff
row[p] = x
inc(p)
# lower triangle sentinel:
if i <= half:
dec(D)
var c3 = D + ord(char1 != b[char2p + s])
dec(diff)
var c3 = diff + ord(char1 != b[char2p + s])
inc(x)
if x > c3: x = c3
row[p] = x

View file

@ -91,22 +91,22 @@ when defined(windows):
dwSize: DWORD
bVisible: WINBOOL
proc duplicateHandle(hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE,
hTargetProcessHandle: HANDLE, lpTargetHandle: ptr HANDLE,
proc duplicateHandle(hSourceProcessHandle: Handle, hSourceHandle: Handle,
hTargetProcessHandle: Handle, lpTargetHandle: ptr Handle,
dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32",
importc: "DuplicateHandle".}
proc getCurrentProcess(): HANDLE{.stdcall, dynlib: "kernel32",
proc getCurrentProcess(): Handle{.stdcall, dynlib: "kernel32",
importc: "GetCurrentProcess".}
proc getConsoleScreenBufferInfo(hConsoleOutput: HANDLE,
proc getConsoleScreenBufferInfo(hConsoleOutput: Handle,
lpConsoleScreenBufferInfo: ptr CONSOLE_SCREEN_BUFFER_INFO): WINBOOL{.stdcall,
dynlib: "kernel32", importc: "GetConsoleScreenBufferInfo".}
proc getConsoleCursorInfo(hConsoleOutput: HANDLE,
proc getConsoleCursorInfo(hConsoleOutput: Handle,
lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "GetConsoleCursorInfo".}
proc setConsoleCursorInfo(hConsoleOutput: HANDLE,
proc setConsoleCursorInfo(hConsoleOutput: Handle,
lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "SetConsoleCursorInfo".}
@ -140,21 +140,21 @@ when defined(windows):
if h > 0: return h
return 0
proc setConsoleCursorPosition(hConsoleOutput: HANDLE,
proc setConsoleCursorPosition(hConsoleOutput: Handle,
dwCursorPosition: COORD): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "SetConsoleCursorPosition".}
proc fillConsoleOutputCharacter(hConsoleOutput: Handle, cCharacter: char,
nLength: DWORD, dwWriteCoord: Coord,
nLength: DWORD, dwWriteCoord: COORD,
lpNumberOfCharsWritten: ptr DWORD): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".}
proc fillConsoleOutputAttribute(hConsoleOutput: HANDLE, wAttribute: int16,
proc fillConsoleOutputAttribute(hConsoleOutput: Handle, wAttribute: int16,
nLength: DWORD, dwWriteCoord: COORD,
lpNumberOfAttrsWritten: ptr DWORD): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "FillConsoleOutputAttribute".}
proc setConsoleTextAttribute(hConsoleOutput: HANDLE,
proc setConsoleTextAttribute(hConsoleOutput: Handle,
wAttributes: int16): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "SetConsoleTextAttribute".}
@ -165,7 +165,7 @@ when defined(windows):
stdcall, dynlib: "kernel32", importc: "SetConsoleMode".}
proc getCursorPos(h: Handle): tuple [x,y: int] =
var c: CONSOLESCREENBUFFERINFO
var c: CONSOLE_SCREEN_BUFFER_INFO
if getConsoleScreenBufferInfo(h, addr(c)) == 0:
raiseOSError(osLastError())
return (int(c.dwCursorPosition.X), int(c.dwCursorPosition.Y))
@ -178,7 +178,7 @@ when defined(windows):
raiseOSError(osLastError())
proc getAttributes(h: Handle): int16 =
var c: CONSOLESCREENBUFFERINFO
var c: CONSOLE_SCREEN_BUFFER_INFO
# workaround Windows bugs: try several times
if getConsoleScreenBufferInfo(h, addr(c)) != 0:
return c.wAttributes
@ -207,7 +207,7 @@ else:
proc setRaw(fd: FileHandle, time: cint = TCSAFLUSH) =
var mode: Termios
discard fd.tcgetattr(addr mode)
discard fd.tcGetAttr(addr mode)
mode.c_iflag = mode.c_iflag and not Cflag(BRKINT or ICRNL or INPCK or
ISTRIP or IXON)
mode.c_oflag = mode.c_oflag and not Cflag(OPOST)
@ -215,7 +215,7 @@ else:
mode.c_lflag = mode.c_lflag and not Cflag(ECHO or ICANON or IEXTEN or ISIG)
mode.c_cc[VMIN] = 1.cuchar
mode.c_cc[VTIME] = 0.cuchar
discard fd.tcsetattr(time, addr mode)
discard fd.tcSetAttr(time, addr mode)
proc terminalWidthIoctl*(fds: openArray[int]): int =
## Returns terminal width from first fd that supports the ioctl.
@ -315,7 +315,7 @@ proc setCursorXPos*(f: File, x: int) =
## The y position is not changed.
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
@ -332,7 +332,7 @@ when defined(windows):
## **Warning**: This is not supported on UNIX!
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
@ -417,7 +417,7 @@ proc eraseLine*(f: File) =
## Erases the entire current line.
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
var numwrote: DWORD
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError())
@ -440,7 +440,7 @@ proc eraseScreen*(f: File) =
## Erases the screen with the background colour and moves the cursor to home.
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
var numwrote: DWORD
var origin: COORD # is inititalized to 0, 0
@ -759,10 +759,10 @@ proc getch*(): char =
else:
let fd = getFileHandle(stdin)
var oldMode: Termios
discard fd.tcgetattr(addr oldMode)
discard fd.tcGetAttr(addr oldMode)
fd.setRaw()
result = stdin.readChar()
discard fd.tcsetattr(TCSADRAIN, addr oldMode)
discard fd.tcSetAttr(TCSADRAIN, addr oldMode)
when defined(windows):
from unicode import toUTF8, Rune, runeLenAt
@ -803,14 +803,14 @@ else:
password.string.setLen(0)
let fd = stdin.getFileHandle()
var cur, old: Termios
discard fd.tcgetattr(cur.addr)
discard fd.tcGetAttr(cur.addr)
old = cur
cur.c_lflag = cur.c_lflag and not Cflag(ECHO)
discard fd.tcsetattr(TCSADRAIN, cur.addr)
discard fd.tcSetAttr(TCSADRAIN, cur.addr)
stdout.write prompt
result = stdin.readLine(password)
stdout.write "\n"
discard fd.tcsetattr(TCSADRAIN, old.addr)
discard fd.tcSetAttr(TCSADRAIN, old.addr)
proc readPasswordFromStdin*(prompt = "password: "): TaintedString =
## Reads a password from stdin without printing it.

View file

@ -222,9 +222,9 @@ elif defined(posix):
type CTime = posix.Time
var
realTimeClockId {.importc: "CLOCK_REALTIME", header: "<time.h>".}: Clockid
realTimeClockId {.importc: "CLOCK_REALTIME", header: "<time.h>".}: ClockId
cpuClockId
{.importc: "CLOCK_THREAD_CPUTIME_ID", header: "<time.h>".}: Clockid
{.importc: "CLOCK_THREAD_CPUTIME_ID", header: "<time.h>".}: ClockId
when not defined(freebsd) and not defined(netbsd) and not defined(openbsd):
var timezone {.importc, header: "<time.h>".}: int
@ -689,7 +689,7 @@ proc getDayOfWeek*(monthday: MonthdayRange, month: Month, year: int): WeekDay
assertValidDate monthday, month, year
# 1970-01-01 is a Thursday, we adjust to the previous Monday
let days = toEpochday(monthday, month, year) - 3
let days = toEpochDay(monthday, month, year) - 3
let weeks = floorDiv(days, 7)
let wd = days - weeks * 7
# The value of d is 0 for a Sunday, 1 for a Monday, 2 for a Tuesday, etc.
@ -930,7 +930,7 @@ proc abs*(a: Duration): Duration =
proc toTime*(dt: DateTime): Time {.tags: [], raises: [], benign.} =
## Converts a ``DateTime`` to a ``Time`` representing the same point in time.
let epochDay = toEpochday(dt.monthday, dt.month, dt.year)
let epochDay = toEpochDay(dt.monthday, dt.month, dt.year)
var seconds = epochDay * secondsInDay
seconds.inc dt.hour * secondsInHour
seconds.inc dt.minute * 60
@ -950,7 +950,7 @@ proc initDateTime(zt: ZonedTime, zone: Timezone): DateTime =
rem = rem - minute * secondsInMin
let second = rem
let (d, m, y) = fromEpochday(epochday)
let (d, m, y) = fromEpochDay(epochday)
DateTime(
year: y,
@ -1011,7 +1011,7 @@ proc zonedTimeFromTime*(zone: Timezone, time: Time): ZonedTime =
## Returns the ``ZonedTime`` for some point in time.
zone.zonedTimeFromTimeImpl(time)
proc zonedTimeFromAdjTime*(zone: TimeZone, adjTime: Time): ZonedTime =
proc zonedTimeFromAdjTime*(zone: Timezone, adjTime: Time): ZonedTime =
## Returns the ``ZonedTime`` for some local time.
##
## Note that the ``Time`` argument does not represent a point in time, it
@ -1047,7 +1047,7 @@ proc inZone*(dt: DateTime, zone: Timezone): DateTime
dt.toTime.inZone(zone)
proc toAdjTime(dt: DateTime): Time =
let epochDay = toEpochday(dt.monthday, dt.month, dt.year)
let epochDay = toEpochDay(dt.monthday, dt.month, dt.year)
var seconds = epochDay * secondsInDay
seconds.inc dt.hour * secondsInHour
seconds.inc dt.minute * secondsInMin
@ -1081,7 +1081,7 @@ when defined(JS):
else:
proc toAdjUnix(tm: Tm): int64 =
let epochDay = toEpochday(tm.tm_mday, (tm.tm_mon + 1).Month,
let epochDay = toEpochDay(tm.tm_mday, (tm.tm_mon + 1).Month,
tm.tm_year.int + 1900)
result = epochDay * secondsInDay
result.inc tm.tm_hour * secondsInHour
@ -1147,7 +1147,7 @@ proc utcTzInfo(time: Time): ZonedTime =
var utcInstance {.threadvar.}: Timezone
var localInstance {.threadvar.}: Timezone
proc utc*(): TimeZone =
proc utc*(): Timezone =
## Get the ``Timezone`` implementation for the UTC timezone.
runnableExamples:
doAssert now().utc.timezone == utc()
@ -1156,7 +1156,7 @@ proc utc*(): TimeZone =
utcInstance = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo)
result = utcInstance
proc local*(): TimeZone =
proc local*(): Timezone =
## Get the ``Timezone`` implementation for the local timezone.
runnableExamples:
doAssert now().timezone == local()
@ -1389,7 +1389,7 @@ proc evaluateInterval(dt: DateTime, interval: TimeInterval):
var curMonth = dt.month
# Subtracting
if months < 0:
for mth in countDown(-1 * months, 1):
for mth in countdown(-1 * months, 1):
if curMonth == mJan:
curMonth = mDec
curYear.dec
@ -2111,7 +2111,7 @@ proc parsePattern(input: string, pattern: FormatPattern, i: var int,
i.inc 1
of tt:
if input.substr(i, i+1).cmpIgnoreCase("AM") == 0:
parsed.amPm = apAM
parsed.amPm = apAm
i.inc 2
elif input.substr(i, i+1).cmpIgnoreCase("PM") == 0:
parsed.amPm = apPm

View file

@ -169,7 +169,7 @@ proc runeAt*(s: string, i: Natural): Rune =
doAssert a.runeAt(3) == "y".runeAt(0)
fastRuneAt(s, i, result, false)
proc validateUTF8*(s: string): int =
proc validateUtf8*(s: string): int =
## Returns the position of the invalid byte in ``s`` if the string ``s`` does
## not hold valid UTF-8 data. Otherwise ``-1`` is returned.
##
@ -211,7 +211,7 @@ template fastToUTF8Copy*(c: Rune, s: var string, pos: int, doInc = true) =
## with an additional amount equal to the byte length of ``c``.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `toUTF8 proc <#toUTF8,Rune>`_
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
var i = RuneImpl(c)
@ -261,7 +261,7 @@ proc toUTF8*(c: Rune): string {.rtl, extern: "nuc$1".} =
## Converts a rune into its UTF-8 representation.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
## * `utf8 iterator <#utf8.i,string>`_
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
@ -287,7 +287,7 @@ proc `$`*(rune: Rune): string =
## An alias for `toUTF8 <#toUTF8,Rune>`_.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
rune.toUTF8
@ -487,12 +487,12 @@ proc toLower*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
## * `toTitle proc <#toTitle,Rune>`_
## * `isLower proc <#isLower,Rune>`_
var c = RuneImpl(c)
var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
return Rune(c + tolowerRanges[p+2] - 500)
p = binarySearch(c, tolowerSinglets, len(tolowerSinglets) div 2, 2)
if p >= 0 and c == tolowerSinglets[p]:
return Rune(c + tolowerSinglets[p+1] - 500)
var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
return Rune(c + toLowerRanges[p+2] - 500)
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
if p >= 0 and c == toLowerSinglets[p]:
return Rune(c + toLowerSinglets[p+1] - 500)
return Rune(c)
proc toUpper*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
@ -505,12 +505,12 @@ proc toUpper*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
## * `toTitle proc <#toTitle,Rune>`_
## * `isUpper proc <#isUpper,Rune>`_
var c = RuneImpl(c)
var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
return Rune(c + toupperRanges[p+2] - 500)
p = binarySearch(c, toupperSinglets, len(toupperSinglets) div 2, 2)
if p >= 0 and c == toupperSinglets[p]:
return Rune(c + toupperSinglets[p+1] - 500)
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
return Rune(c + toUpperRanges[p+2] - 500)
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
if p >= 0 and c == toUpperSinglets[p]:
return Rune(c + toUpperSinglets[p+1] - 500)
return Rune(c)
proc toTitle*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
@ -537,11 +537,11 @@ proc isLower*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
## * `isTitle proc <#isTitle,Rune>`_
var c = RuneImpl(c)
# Note: toUpperRanges is correct here!
var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
return true
p = binarySearch(c, toupperSinglets, len(toupperSinglets) div 2, 2)
if p >= 0 and c == toupperSinglets[p]:
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
if p >= 0 and c == toUpperSinglets[p]:
return true
proc isUpper*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
@ -557,11 +557,11 @@ proc isUpper*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
## * `isWhiteSpace proc <#isWhiteSpace,Rune>`_
var c = RuneImpl(c)
# Note: toLowerRanges is correct here!
var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
return true
p = binarySearch(c, tolowerSinglets, len(tolowerSinglets) div 2, 2)
if p >= 0 and c == tolowerSinglets[p]:
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
if p >= 0 and c == toLowerSinglets[p]:
return true
proc isAlpha*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
@ -805,7 +805,7 @@ iterator utf8*(s: string): string =
## Iterates over any rune of the string ``s`` returning utf8 values.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `toUTF8 proc <#toUTF8,Rune>`_
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
@ -928,7 +928,7 @@ proc size*(r: Rune): int {.noSideEffect.} =
else: result = 1
# --------- Private templates for different split separators -----------
proc stringHasSep(s: string, index: int, seps: openarray[Rune]): bool =
proc stringHasSep(s: string, index: int, seps: openArray[Rune]): bool =
var rune: Rune
fastRuneAt(s, index, rune, false)
return seps.contains(rune)
@ -960,7 +960,7 @@ template splitCommon(s, sep, maxsplit: untyped, sepLen: int = -1) =
else:
inc(last, if last < len(s): runeLenAt(s, last) else: 1)
iterator split*(s: string, seps: openarray[Rune] = unicodeSpaces,
iterator split*(s: string, seps: openArray[Rune] = unicodeSpaces,
maxsplit: int = -1): string =
## Splits the unicode string ``s`` into substrings using a group of separators.
##
@ -1044,7 +1044,7 @@ iterator split*(s: string, sep: Rune, maxsplit: int = -1): string =
##
splitCommon(s, sep, maxsplit, sep.size)
proc split*(s: string, seps: openarray[Rune] = unicodeSpaces, maxsplit: int = -1): seq[string] {.
proc split*(s: string, seps: openArray[Rune] = unicodeSpaces, maxsplit: int = -1): seq[string] {.
noSideEffect, rtl, extern: "nucSplitRunes".} =
## The same as the `split iterator <#split.i,string,openArray[Rune],int>`_,
## but is a proc that returns a sequence of substrings.
@ -1057,7 +1057,7 @@ proc split*(s: string, sep: Rune, maxsplit: int = -1): seq[string] {.noSideEffec
accResult(split(s, sep, maxsplit))
proc strip*(s: string, leading = true, trailing = true,
runes: openarray[Rune] = unicodeSpaces): string {.noSideEffect,
runes: openArray[Rune] = unicodeSpaces): string {.noSideEffect,
rtl, extern: "nucStrip".} =
## Strips leading or trailing ``runes`` from ``s`` and returns
## the resulting string.
@ -1072,46 +1072,46 @@ proc strip*(s: string, leading = true, trailing = true,
doAssert a.strip(trailing = false) == "áñyóng "
var
s_i = 0 ## starting index into string ``s``
e_i = len(s) - 1 ## ending index into ``s``, where the last ``Rune`` starts
sI = 0 ## starting index into string ``s``
eI = len(s) - 1 ## ending index into ``s``, where the last ``Rune`` starts
if leading:
var
i = 0
l_i: int ## value of ``s_i`` at the beginning of the iteration
xI: int ## value of ``sI`` at the beginning of the iteration
rune: Rune
while i < len(s):
l_i = i
xI = i
fastRuneAt(s, i, rune)
s_i = i # Assume to start from next rune
sI = i # Assume to start from next rune
if not runes.contains(rune):
s_i = l_i # Go back to where the current rune starts
sI = xI # Go back to where the current rune starts
break
if trailing:
var
i = e_i
l_i: int
i = eI
xI: int
rune: Rune
while i >= 0:
l_i = i
fastRuneAt(s, l_i, rune)
var p_i = i - 1
while p_i >= 0:
xI = i
fastRuneAt(s, xI, rune)
var yI = i - 1
while yI >= 0:
var
p_i_end = p_i
p_rune: Rune
fastRuneAt(s, p_i_end, p_rune)
if p_i_end < l_i: break
i = p_i
rune = p_rune
dec(p_i)
yIend = yI
pRune: Rune
fastRuneAt(s, yIend, pRune)
if yIend < xI: break
i = yI
rune = pRune
dec(yI)
if not runes.contains(rune):
e_i = l_i - 1
eI = xI - 1
break
dec(i)
let newLen = e_i - s_i + 1
let newLen = eI - sI + 1
result = newStringOfCap(newLen)
if newLen > 0:
result.add s[s_i .. e_i]
result.add s[sI .. eI]
proc repeat*(c: Rune, count: Natural): string {.noSideEffect,
rtl, extern: "nucRepeatRune".} =

View file

@ -445,7 +445,7 @@ proc `$`*(u: Uri): string =
result.add(":")
result.add(u.password)
result.add("@")
if u.hostname.endswith('/'):
if u.hostname.endsWith('/'):
result.add(u.hostname[0..^2])
else:
result.add(u.hostname)

View file

@ -462,7 +462,7 @@ proc shallowCopy*[T](x: var T, y: T) {.noSideEffect, magic: "ShallowCopy".}
## and strings.
when defined(nimArrIdx):
# :array|openarray|string|seq|cstring|tuple
# :array|openArray|string|seq|cstring|tuple
proc `[]`*[I: Ordinal;T](a: T; i: I): T {.
noSideEffect, magic: "ArrGet".}
proc `[]=`*[I: Ordinal;T,S](a: T; i: I;
@ -700,7 +700,7 @@ type
## is an `int` type ranging from one to the maximum value
## of an `int`. This type is often useful for documentation and debugging.
RootObj* {.compilerProc, inheritable.} =
RootObj* {.compilerproc, inheritable.} =
object ## The root of Nim's object hierarchy.
##
## Objects should inherit from `RootObj` or one of its descendants.
@ -1026,7 +1026,7 @@ when not defined(JS):
proc len*[TOpenArray: openArray|varargs](x: TOpenArray): int {.
magic: "LengthOpenArray", noSideEffect.}
## Returns the length of an openarray.
## Returns the length of an openArray.
##
## .. code-block:: Nim
## var s = [1, 1, 1, 1, 1]
@ -2002,7 +2002,7 @@ else:
## turned on.
when defined(profiler) and not defined(nimscript):
proc nimProfile() {.compilerProc, noinline.}
proc nimProfile() {.compilerproc, noinline.}
when hasThreadSupport:
{.pragma: rtlThreadVar, threadvar.}
else:
@ -2082,7 +2082,7 @@ const hasAlloc = (hostOS != "standalone" or not defined(nogc)) and not defined(n
when not defined(JS) and not defined(nimscript) and hostOS != "standalone":
include "system/cgprocs"
when not defined(JS) and not defined(nimscript) and hasAlloc and not defined(gcDestructors):
proc addChar(s: NimString, c: char): NimString {.compilerProc, benign.}
proc addChar(s: NimString, c: char): NimString {.compilerproc, benign.}
when not defined(gcDestructors):
proc add*[T](x: var seq[T], y: T) {.magic: "AppendSeqElem", noSideEffect.}
@ -2551,7 +2551,7 @@ proc swap*[T](a, b: var T) {.magic: "Swap", noSideEffect.}
## assert b == 5
when not defined(js) and not defined(booting) and defined(nimTrMacros):
template swapRefsInArray*{swap(arr[a], arr[b])}(arr: openarray[ref], a, b: int) =
template swapRefsInArray*{swap(arr[a], arr[b])}(arr: openArray[ref], a, b: int) =
# Optimize swapping of array elements if they are refs. Default swap
# implementation will cause unsureAsgnRef to be emitted which causes
# unnecessary slow down in this case.
@ -2919,7 +2919,7 @@ proc `==`*[I, T](x, y: array[I, T]): bool =
return
result = true
proc `==`*[T](x, y: openarray[T]): bool =
proc `==`*[T](x, y: openArray[T]): bool =
if x.len != y.len:
return false
@ -2930,7 +2930,7 @@ proc `==`*[T](x, y: openarray[T]): bool =
result = true
proc `@`*[T](a: openArray[T]): seq[T] =
## Turns an *openarray* into a sequence.
## Turns an *openArray* into a sequence.
##
## This is not as efficient as turning a fixed length array into a sequence
## as it always copies every element of `a`.
@ -3081,9 +3081,9 @@ when not defined(js):
when defined(nimV2):
type
TNimNode {.compilerProc.} = object # to keep the code generator simple
TNimNode {.compilerproc.} = object # to keep the code generator simple
DestructorProc = proc (p: pointer) {.nimcall, benign.}
TNimType {.compilerProc.} = object
TNimType {.compilerproc.} = object
destructor: pointer
size: int
name: cstring
@ -3427,7 +3427,7 @@ template newException*(exceptn: typedesc, message: string;
e
when hostOS == "standalone" and defined(nogc):
proc nimToCStringConv(s: NimString): cstring {.compilerProc, inline.} =
proc nimToCStringConv(s: NimString): cstring {.compilerproc, inline.} =
if s == nil or s.len == 0: result = cstring""
else: result = cstring(addr s.data)
@ -3844,7 +3844,7 @@ elif defined(JS):
return 1
proc quit*(errormsg: string, errorcode = QuitFailure) {.noReturn.} =
proc quit*(errormsg: string, errorcode = QuitFailure) {.noreturn.} =
## A shorthand for ``echo(errormsg); quit(errorcode)``.
when defined(nimscript) or defined(js) or (hostOS == "standalone"):
echo errormsg
@ -4484,21 +4484,21 @@ when defined(windows) and appType == "console" and defined(nimSetUtf8CodePage) a
discard setConsoleOutputCP(65001) # 65001 - utf-8 codepage
when not defined(js):
proc toOpenArray*[T](x: seq[T]; first, last: int): openarray[T] {.
proc toOpenArray*[T](x: seq[T]; first, last: int): openArray[T] {.
magic: "Slice".}
proc toOpenArray*[T](x: openarray[T]; first, last: int): openarray[T] {.
proc toOpenArray*[T](x: openArray[T]; first, last: int): openArray[T] {.
magic: "Slice".}
proc toOpenArray*[T](x: ptr UncheckedArray[T]; first, last: int): openarray[T] {.
proc toOpenArray*[T](x: ptr UncheckedArray[T]; first, last: int): openArray[T] {.
magic: "Slice".}
proc toOpenArray*[I, T](x: array[I, T]; first, last: I): openarray[T] {.
proc toOpenArray*[I, T](x: array[I, T]; first, last: I): openArray[T] {.
magic: "Slice".}
proc toOpenArray*(x: string; first, last: int): openarray[char] {.
proc toOpenArray*(x: string; first, last: int): openArray[char] {.
magic: "Slice".}
proc toOpenArrayByte*(x: string; first, last: int): openarray[byte] {.
proc toOpenArrayByte*(x: string; first, last: int): openArray[byte] {.
magic: "Slice".}
type
ForLoopStmt* {.compilerProc.} = object ## \
ForLoopStmt* {.compilerproc.} = object ## \
## A special type that marks a macro as a `for-loop macro`:idx:.
## See `"For Loop Macro" <manual.html#macros-for-loop-macro>`_.

View file

@ -1007,7 +1007,7 @@ template instantiateForRegion(allocator: untyped) =
dealloc(allocator, p)
proc realloc(p: pointer, newsize: Natural): pointer =
result = realloc(allocator, p, newSize)
result = realloc(allocator, p, newsize)
when false:
proc countFreeMem(): int =
@ -1060,7 +1060,7 @@ template instantiateForRegion(allocator: untyped) =
result = realloc(sharedHeap, p, newsize)
releaseSys(heapLock)
else:
result = realloc(p, newSize)
result = realloc(p, newsize)
when hasThreadSupport:
template sharedMemStatsShared(v: int) =

View file

@ -113,7 +113,7 @@ proc c_signal*(sign: cint, handler: proc (a: cint) {.noconv.}): CSighandlerT {.
type
CFile {.importc: "FILE", header: "<stdio.h>",
incompletestruct.} = object
incompleteStruct.} = object
CFilePtr* = ptr CFile ## The type representing a file handle.
var
@ -142,7 +142,7 @@ proc c_realloc*(p: pointer, newsize: csize): pointer {.
proc c_fwrite*(buf: pointer, size, n: csize, f: CFilePtr): cint {.
importc: "fwrite", header: "<stdio.h>".}
proc rawWrite*(f: CFilePtr, s: cstring) {.compilerproc, nonreloadable, inline.} =
proc rawWrite*(f: CFilePtr, s: cstring) {.compilerproc, nonReloadable, inline.} =
# we cannot throw an exception here!
discard c_fwrite(s, 1, s.len, f)

View file

@ -59,11 +59,11 @@ when defined(builtinOverflow):
proc mulIntOverflow(a, b: int, c: var int): bool {.
importc: "__builtin_smul_overflow", nodecl, nosideeffect.}
proc addInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc addInt64(a, b: int64): int64 {.compilerproc, inline.} =
if addInt64Overflow(a, b, result):
raiseOverflow()
proc subInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc subInt64(a, b: int64): int64 {.compilerproc, inline.} =
if subInt64Overflow(a, b, result):
raiseOverflow()
@ -71,13 +71,13 @@ when defined(builtinOverflow):
if mulInt64Overflow(a, b, result):
raiseOverflow()
else:
proc addInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc addInt64(a, b: int64): int64 {.compilerproc, inline.} =
result = a +% b
if (result xor a) >= int64(0) or (result xor b) >= int64(0):
return result
raiseOverflow()
proc subInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc subInt64(a, b: int64): int64 {.compilerproc, inline.} =
result = a -% b
if (result xor a) >= int64(0) or (result xor not b) >= int64(0):
return result
@ -126,29 +126,29 @@ else:
return result
raiseOverflow()
proc negInt64(a: int64): int64 {.compilerProc, inline.} =
proc negInt64(a: int64): int64 {.compilerproc, inline.} =
if a != low(int64): return -a
raiseOverflow()
proc absInt64(a: int64): int64 {.compilerProc, inline.} =
proc absInt64(a: int64): int64 {.compilerproc, inline.} =
if a != low(int64):
if a >= 0: return a
else: return -a
raiseOverflow()
proc divInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc divInt64(a, b: int64): int64 {.compilerproc, inline.} =
if b == int64(0):
raiseDivByZero()
if a == low(int64) and b == int64(-1):
raiseOverflow()
return a div b
proc modInt64(a, b: int64): int64 {.compilerProc, inline.} =
proc modInt64(a, b: int64): int64 {.compilerproc, inline.} =
if b == int64(0):
raiseDivByZero()
return a mod b
proc absInt(a: int): int {.compilerProc, inline.} =
proc absInt(a: int): int {.compilerproc, inline.} =
if a != low(int):
if a >= 0: return a
else: return -a
@ -164,7 +164,7 @@ const
when asmVersion and not defined(gcc) and not defined(llvm_gcc):
# assembler optimized versions for compilers that
# have an intel syntax assembler:
proc addInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
proc addInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
# a in eax, and b in edx
asm """
mov eax, ecx
@ -175,7 +175,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
ret
"""
proc subInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
proc subInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
asm """
mov eax, ecx
sub eax, edx
@ -185,7 +185,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
ret
"""
proc negInt(a: int): int {.compilerProc, asmNoStackFrame.} =
proc negInt(a: int): int {.compilerproc, asmNoStackFrame.} =
asm """
mov eax, ecx
neg eax
@ -195,7 +195,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
ret
"""
proc divInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
proc divInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
asm """
test edx, edx
jne L_NOT_ZERO
@ -214,7 +214,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
ret
"""
proc modInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
proc modInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
asm """
test edx, edx
jne L_NOT_ZERO
@ -234,7 +234,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
ret
"""
proc mulInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
proc mulInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
asm """
mov eax, ecx
mov ecx, edx
@ -247,7 +247,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
"""
elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
proc addInt(a, b: int): int {.compilerProc, inline.} =
proc addInt(a, b: int): int {.compilerproc, inline.} =
# don't use a pure proc here!
asm """
"addl %%ecx, %%eax\n"
@ -261,7 +261,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
#/* Intel syntax here */
#".att_syntax"
proc subInt(a, b: int): int {.compilerProc, inline.} =
proc subInt(a, b: int): int {.compilerproc, inline.} =
asm """ "subl %%ecx,%%eax\n"
"jno 1\n"
"call _raiseOverflow\n"
@ -270,7 +270,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
:"a"(`a`), "c"(`b`)
"""
proc mulInt(a, b: int): int {.compilerProc, inline.} =
proc mulInt(a, b: int): int {.compilerproc, inline.} =
asm """ "xorl %%edx, %%edx\n"
"imull %%ecx\n"
"jno 1\n"
@ -281,7 +281,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
:"%edx"
"""
proc negInt(a: int): int {.compilerProc, inline.} =
proc negInt(a: int): int {.compilerproc, inline.} =
asm """ "negl %%eax\n"
"jno 1\n"
"call _raiseOverflow\n"
@ -290,7 +290,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
:"a"(`a`)
"""
proc divInt(a, b: int): int {.compilerProc, inline.} =
proc divInt(a, b: int): int {.compilerproc, inline.} =
asm """ "xorl %%edx, %%edx\n"
"idivl %%ecx\n"
"jno 1\n"
@ -301,7 +301,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
:"%edx"
"""
proc modInt(a, b: int): int {.compilerProc, inline.} =
proc modInt(a, b: int): int {.compilerproc, inline.} =
asm """ "xorl %%edx, %%edx\n"
"idivl %%ecx\n"
"jno 1\n"
@ -314,42 +314,42 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
"""
when not declared(addInt) and defined(builtinOverflow):
proc addInt(a, b: int): int {.compilerProc, inline.} =
proc addInt(a, b: int): int {.compilerproc, inline.} =
if addIntOverflow(a, b, result):
raiseOverflow()
when not declared(subInt) and defined(builtinOverflow):
proc subInt(a, b: int): int {.compilerProc, inline.} =
proc subInt(a, b: int): int {.compilerproc, inline.} =
if subIntOverflow(a, b, result):
raiseOverflow()
when not declared(mulInt) and defined(builtinOverflow):
proc mulInt(a, b: int): int {.compilerProc, inline.} =
proc mulInt(a, b: int): int {.compilerproc, inline.} =
if mulIntOverflow(a, b, result):
raiseOverflow()
# Platform independent versions of the above (slower!)
when not declared(addInt):
proc addInt(a, b: int): int {.compilerProc, inline.} =
proc addInt(a, b: int): int {.compilerproc, inline.} =
result = a +% b
if (result xor a) >= 0 or (result xor b) >= 0:
return result
raiseOverflow()
when not declared(subInt):
proc subInt(a, b: int): int {.compilerProc, inline.} =
proc subInt(a, b: int): int {.compilerproc, inline.} =
result = a -% b
if (result xor a) >= 0 or (result xor not b) >= 0:
return result
raiseOverflow()
when not declared(negInt):
proc negInt(a: int): int {.compilerProc, inline.} =
proc negInt(a: int): int {.compilerproc, inline.} =
if a != low(int): return -a
raiseOverflow()
when not declared(divInt):
proc divInt(a, b: int): int {.compilerProc, inline.} =
proc divInt(a, b: int): int {.compilerproc, inline.} =
if b == 0:
raiseDivByZero()
if a == low(int) and b == -1:
@ -357,7 +357,7 @@ when not declared(divInt):
return a div b
when not declared(modInt):
proc modInt(a, b: int): int {.compilerProc, inline.} =
proc modInt(a, b: int): int {.compilerproc, inline.} =
if b == 0:
raiseDivByZero()
return a mod b
@ -383,7 +383,7 @@ when not declared(mulInt):
# the only one that can lose catastrophic amounts of information, it's the
# native int product that must have overflowed.
#
proc mulInt(a, b: int): int {.compilerProc.} =
proc mulInt(a, b: int): int {.compilerproc.} =
var
resAsFloat, floatProd: float
@ -412,7 +412,7 @@ when not declared(mulInt):
proc raiseFloatInvalidOp {.noinline.} =
sysFatal(FloatInvalidOpError, "FPU operation caused a NaN result")
proc nanCheck(x: float64) {.compilerProc, inline.} =
proc nanCheck(x: float64) {.compilerproc, inline.} =
if x != x: raiseFloatInvalidOp()
proc raiseFloatOverflow(x: float64) {.noinline.} =
@ -421,5 +421,5 @@ proc raiseFloatOverflow(x: float64) {.noinline.} =
else:
sysFatal(FloatUnderflowError, "FPU operations caused an underflow")
proc infCheck(x: float64) {.compilerProc, inline.} =
proc infCheck(x: float64) {.compilerproc, inline.} =
if x != 0.0 and x*0.5 == x: raiseFloatOverflow(x)

View file

@ -11,12 +11,12 @@ proc `$`(x: int): string {.magic: "IntToStr", noSideEffect.}
proc `$`(info: InstantiationInfo): string =
# The +1 is needed here
# instead of overriding `$` (and changing its meaning), consider explicit name.
info.fileName & "(" & $info.line & ", " & $(info.column+1) & ")"
info.filename & "(" & $info.line & ", " & $(info.column+1) & ")"
# ---------------------------------------------------------------------------
proc raiseAssert*(msg: string) {.noinline, noReturn.} =
proc raiseAssert*(msg: string) {.noinline, noreturn.} =
sysFatal(AssertionError, msg)
proc failedAssertImpl*(msg: string) {.raises: [], tags: [].} =

View file

@ -107,10 +107,10 @@ proc genericAssignAux(dest, src: pointer, mt: PNimType, shallow: bool) =
else:
copyMem(dest, src, mt.size) # copy raw bits
proc genericAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} =
proc genericAssign(dest, src: pointer, mt: PNimType) {.compilerproc.} =
genericAssignAux(dest, src, mt, false)
proc genericShallowAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} =
proc genericShallowAssign(dest, src: pointer, mt: PNimType) {.compilerproc.} =
genericAssignAux(dest, src, mt, true)
when false:
@ -142,7 +142,7 @@ when false:
cprintf("%s %ld\n", k, t.size)
debugNimType(t.base)
proc genericSeqAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} =
proc genericSeqAssign(dest, src: pointer, mt: PNimType) {.compilerproc.} =
var src = src # ugly, but I like to stress the parser sometimes :-)
genericAssign(dest, addr(src), mt)
@ -155,7 +155,7 @@ proc genericAssignOpenArray(dest, src: pointer, len: int,
genericAssign(cast[pointer](d +% i *% mt.base.size),
cast[pointer](s +% i *% mt.base.size), mt.base)
proc objectInit(dest: pointer, typ: PNimType) {.compilerProc, benign.}
proc objectInit(dest: pointer, typ: PNimType) {.compilerproc, benign.}
proc objectInitAux(dest: pointer, n: ptr TNimNode) {.benign.} =
var d = cast[ByteAddress](dest)
case n.kind
@ -188,7 +188,7 @@ proc objectInit(dest: pointer, typ: PNimType) =
# ---------------------- assign zero -----------------------------------------
proc genericReset(dest: pointer, mt: PNimType) {.compilerProc, benign.}
proc genericReset(dest: pointer, mt: PNimType) {.compilerproc, benign.}
proc genericResetAux(dest: pointer, n: ptr TNimNode) =
var d = cast[ByteAddress](dest)
case n.kind
@ -229,7 +229,7 @@ proc selectBranch(discVal, L: int,
proc FieldDiscriminantCheck(oldDiscVal, newDiscVal: int,
a: ptr array[0x7fff, ptr TNimNode],
L: int) {.compilerProc.} =
L: int) {.compilerproc.} =
let oldBranch = selectBranch(oldDiscVal, L, a)
let newBranch = selectBranch(newDiscVal, L, a)
when defined(nimOldCaseObjects):

View file

@ -154,7 +154,7 @@ proc contains(s: CellSet, cell: PCell): bool =
else:
result = false
proc incl(s: var CellSet, cell: PCell) {.noinline.} =
proc incl(s: var CellSet, cell: PCell) =
var u = cast[uint](cell)
var t = cellSetPut(s, u shr PageShift)
u = (u mod PageSize) div MemAlign

View file

@ -99,7 +99,7 @@ when not defined(nimV2):
return true
proc isObjWithCache(obj, subclass: PNimType;
cache: var ObjCheckCache): bool {.compilerProc, inline.} =
cache: var ObjCheckCache): bool {.compilerproc, inline.} =
if obj == subclass: return true
if obj.base == subclass: return true
if cache[0] == obj: return false
@ -116,6 +116,6 @@ when not defined(nimV2):
return true
when defined(nimV2):
proc nimFieldDiscriminantCheckV2(oldDiscVal, newDiscVal: uint8) {.compilerProc.} =
proc nimFieldDiscriminantCheckV2(oldDiscVal, newDiscVal: uint8) {.compilerproc.} =
if oldDiscVal != newDiscVal:
sysFatal(FieldError, "assignment to discriminant changes object branch")

View file

@ -165,14 +165,14 @@ proc genericDeepCopyAux(dest, src: pointer, mt: PNimType; tab: var PtrTable) =
else:
copyMem(dest, src, mt.size)
proc genericDeepCopy(dest, src: pointer, mt: PNimType) {.compilerProc.} =
proc genericDeepCopy(dest, src: pointer, mt: PNimType) {.compilerproc.} =
GC_disable()
var tab = initPtrTable()
genericDeepCopyAux(dest, src, mt, tab)
deinit tab
GC_enable()
proc genericSeqDeepCopy(dest, src: pointer, mt: PNimType) {.compilerProc.} =
proc genericSeqDeepCopy(dest, src: pointer, mt: PNimType) {.compilerproc.} =
# also invoked for 'string'
var src = src
genericDeepCopy(dest, addr(src), mt)

View file

@ -149,7 +149,7 @@ when not defined(nimNoArrayToString):
## Generic ``$`` operator for arrays that is lifted from the components.
collectionToString(x, "[", ", ", "]")
proc `$`*[T](x: openarray[T]): string =
proc `$`*[T](x: openArray[T]): string =
## Generic ``$`` operator for openarrays that is lifted from the components
## of `x`. Example:
##

View file

@ -14,7 +14,7 @@ elif defined(nimQuirky) and not defined(nimscript):
proc name(t: typedesc): string {.magic: "TypeTrait".}
proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noReturn.} =
proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noreturn.} =
var buf = newStringOfCap(200)
add(buf, "Error: unhandled exception: ")
add(buf, message)
@ -25,11 +25,11 @@ elif defined(nimQuirky) and not defined(nimscript):
cstderr.rawWrite buf
quit 1
proc sysFatal(exceptn: typedesc, message: string) {.inline, noReturn.} =
proc sysFatal(exceptn: typedesc, message: string) {.inline, noreturn.} =
sysFatal(exceptn, message, "")
else:
proc sysFatal(exceptn: typedesc, message: string) {.inline, noReturn.} =
proc sysFatal(exceptn: typedesc, message: string) {.inline, noreturn.} =
when declared(owned):
var e: owned(ref exceptn)
else:
@ -38,7 +38,7 @@ else:
e.msg = message
raise e
proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noReturn.} =
proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noreturn.} =
when declared(owned):
var e: owned(ref exceptn)
else:

View file

@ -184,7 +184,7 @@ proc incRef(c: PCell) {.inline.} =
# and not colorMask
logCell("incRef", c)
proc nimGCref(p: pointer) {.compilerProc.} =
proc nimGCref(p: pointer) {.compilerproc.} =
# we keep it from being collected by pretending it's not even allocated:
let c = usrToCell(p)
add(gch.additionalRoots, c)
@ -202,7 +202,7 @@ proc decRef(c: PCell) {.inline.} =
rtlAddZCT(c)
logCell("decRef", c)
proc nimGCunref(p: pointer) {.compilerProc.} =
proc nimGCunref(p: pointer) {.compilerproc.} =
let cell = usrToCell(p)
var L = gch.additionalRoots.len-1
var i = L
@ -223,15 +223,15 @@ template beforeDealloc(gch: var GcHeap; c: PCell; msg: typed) =
if gch.decStack.d[i] == c:
sysAssert(false, msg)
proc nimGCunrefNoCycle(p: pointer) {.compilerProc, inline.} =
proc nimGCunrefNoCycle(p: pointer) {.compilerproc, inline.} =
sysAssert(allocInv(gch.region), "begin nimGCunrefNoCycle")
decRef(usrToCell(p))
sysAssert(allocInv(gch.region), "end nimGCunrefNoCycle 5")
proc nimGCunrefRC1(p: pointer) {.compilerProc, inline.} =
proc nimGCunrefRC1(p: pointer) {.compilerproc, inline.} =
decRef(usrToCell(p))
proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} =
proc asgnRef(dest: PPointer, src: pointer) {.compilerproc, inline.} =
# the code generator calls this proc!
gcAssert(not isOnStack(dest), "asgnRef")
# BUGFIX: first incRef then decRef!
@ -242,7 +242,7 @@ proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} =
proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline,
deprecated: "old compiler compat".} = asgnRef(dest, src)
proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerProc.} =
proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerproc.} =
# unsureAsgnRef updates the reference counters only if dest is not on the
# stack. It is used by the code generator if it cannot decide wether a
# reference is in the stack or not (this can happen for var parameters).

View file

@ -193,12 +193,12 @@ proc doOperation(p: pointer, op: WalkOp) {.benign.}
proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) {.benign.}
# we need the prototype here for debugging purposes
proc nimGCref(p: pointer) {.compilerProc.} =
proc nimGCref(p: pointer) {.compilerproc.} =
let cell = usrToCell(p)
markAsEscaped(cell)
add(gch.additionalRoots, cell)
proc nimGCunref(p: pointer) {.compilerProc.} =
proc nimGCunref(p: pointer) {.compilerproc.} =
let cell = usrToCell(p)
var L = gch.additionalRoots.len-1
var i = L
@ -210,10 +210,10 @@ proc nimGCunref(p: pointer) {.compilerProc.} =
break
dec(i)
proc nimGCunrefNoCycle(p: pointer) {.compilerProc, inline.} =
proc nimGCunrefNoCycle(p: pointer) {.compilerproc, inline.} =
discard "can we do some freeing here?"
proc nimGCunrefRC1(p: pointer) {.compilerProc, inline.} =
proc nimGCunrefRC1(p: pointer) {.compilerproc, inline.} =
discard "can we do some freeing here?"
template markGrey(x: PCell) =
@ -225,7 +225,7 @@ template markGrey(x: PCell) =
x.setColor(rcGrey)
add(gch.greyStack, x)
proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} =
proc asgnRef(dest: PPointer, src: pointer) {.compilerproc, inline.} =
# the code generator calls this proc!
gcAssert(not isOnStack(dest), "asgnRef")
# BUGFIX: first incRef then decRef!
@ -238,7 +238,7 @@ proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} =
proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline,
deprecated: "old compiler compat".} = asgnRef(dest, src)
proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerProc.} =
proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerproc.} =
# unsureAsgnRef marks 'src' as grey only if dest is not on the
# stack. It is used by the code generator if it cannot decide wether a
# reference is in the stack or not (this can happen for var parameters).

View file

@ -456,7 +456,7 @@ var
threadLocalMarkers {.exportc.}: array[0..3499, GlobalMarkerProc]
gHeapidGenerator: int
proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerProc.} =
proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerproc.} =
if globalMarkersLen <= high(globalMarkers):
globalMarkers[globalMarkersLen] = markerProc
inc globalMarkersLen
@ -464,7 +464,7 @@ proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerProc.} =
cstderr.rawWrite("[GC] cannot register global variable; too many global variables")
quit 1
proc nimRegisterThreadLocalMarker(markerProc: GlobalMarkerProc) {.compilerProc.} =
proc nimRegisterThreadLocalMarker(markerProc: GlobalMarkerProc) {.compilerproc.} =
if threadLocalMarkersLen <= high(threadLocalMarkers):
threadLocalMarkers[threadLocalMarkersLen] = markerProc
inc threadLocalMarkersLen

View file

@ -162,7 +162,7 @@ when defined(nimGcRefLeak):
var ax: array[10_000, GcStackTrace]
proc nimGCref(p: pointer) {.compilerProc.} =
proc nimGCref(p: pointer) {.compilerproc.} =
# we keep it from being collected by pretending it's not even allocated:
when false:
when withBitvectors: excl(gch.allocated, usrToCell(p))
@ -171,7 +171,7 @@ proc nimGCref(p: pointer) {.compilerProc.} =
captureStackTrace(framePtr, ax[gch.additionalRoots.len])
add(gch.additionalRoots, usrToCell(p))
proc nimGCunref(p: pointer) {.compilerProc.} =
proc nimGCunref(p: pointer) {.compilerproc.} =
let cell = usrToCell(p)
var L = gch.additionalRoots.len-1
var i = L
@ -372,14 +372,14 @@ proc mark(gch: var GcHeap, c: PCell) =
c, c.typ.name)
inc gch.indentation, 2
c.refCount = rcBlack
c.refcount = rcBlack
gcAssert gch.tempStack.len == 0, "stack not empty!"
forAllChildren(c, waMarkPrecise)
while gch.tempStack.len > 0:
dec gch.tempStack.len
var d = gch.tempStack.d[gch.tempStack.len]
if d.refcount == rcWhite:
d.refCount = rcBlack
d.refcount = rcBlack
forAllChildren(d, waMarkPrecise)
when defined(nimTracing):

View file

@ -73,7 +73,7 @@ type
tyVoidHidden
TNimNodeKind = enum nkNone, nkSlot, nkList, nkCase
TNimNode {.compilerProc.} = object
TNimNode {.compilerproc.} = object
kind: TNimNodeKind
offset: int
typ: ptr TNimType
@ -86,7 +86,7 @@ type
ntfAcyclic = 1, # type cannot form a cycle
ntfEnumHole = 2 # enum has holes and thus `$` for them needs the slow
# version
TNimType {.compilerProc.} = object
TNimType {.compilerproc.} = object
size: int
kind: TNimKind
flags: set[TNimTypeFlag]
@ -105,7 +105,7 @@ type
when defined(nimTypeNames):
# Declare this variable only once in system.nim
when declared(ThisIsSystem):
var nimTypeRoot {.compilerProc.}: PNimType
var nimTypeRoot {.compilerproc.}: PNimType
else:
var nimTypeRoot {.importc.}: PNimType

View file

@ -12,7 +12,7 @@ include inclrtl
# ----------------- IO Part ------------------------------------------------
type
CFile {.importc: "FILE", header: "<stdio.h>",
incompletestruct.} = object
incompleteStruct.} = object
File* = ptr CFile ## The type representing a file handle.
FileMode* = enum ## The file mode when opening a file.
@ -420,7 +420,7 @@ when defined(windows) and not defined(useWinAnsi):
result = wfreopen(f, m, stream)
else:
proc fopen(filename, mode: cstring): pointer {.importc: "fopen", noDecl.}
proc fopen(filename, mode: cstring): pointer {.importc: "fopen", nodecl.}
proc freopen(filename, mode: cstring, stream: File): File {.
importc: "freopen", nodecl.}
@ -442,7 +442,7 @@ when defined(posix) and not defined(nimscript):
st_mode: Mode ## Mode of file
filler_2: array[144 - 24 - 4, char]
proc S_ISDIR(m: Mode): bool =
proc modeIsDir(m: Mode): bool =
## Test for a directory.
(m and 0o170000) == 0o40000
@ -454,7 +454,7 @@ when defined(posix) and not defined(nimscript):
header: "<sys/stat.h>", final, pure.} = object ## struct stat
st_mode: Mode ## Mode of file
proc S_ISDIR(m: Mode): bool {.importc, header: "<sys/stat.h>".}
proc modeIsDir(m: Mode): bool {.importc: "S_ISDIR", header: "<sys/stat.h>".}
## Test for a directory.
proc c_fstat(a1: cint, a2: var Stat): cint {.
@ -476,7 +476,7 @@ proc open*(f: var File, filename: string,
# be opened.
var f2 = cast[File](p)
var res: Stat
if c_fstat(getFileHandle(f2), res) >= 0'i32 and S_ISDIR(res.st_mode):
if c_fstat(getFileHandle(f2), res) >= 0'i32 and modeIsDir(res.st_mode):
close(f2)
return false
result = true
@ -550,11 +550,11 @@ when declared(stdout):
var echoLock: SysLock
initSysLock echoLock
proc echoBinSafe(args: openArray[string]) {.compilerProc.} =
proc echoBinSafe(args: openArray[string]) {.compilerproc.} =
# flockfile deadlocks some versions of Android 5.x.x
when not defined(windows) and not defined(android) and not defined(nintendoswitch):
proc flockfile(f: File) {.importc, noDecl.}
proc funlockfile(f: File) {.importc, noDecl.}
proc flockfile(f: File) {.importc, nodecl.}
proc funlockfile(f: File) {.importc, nodecl.}
flockfile(stdout)
when defined(windows) and compileOption("threads"):
acquireSys echoLock

View file

@ -9,7 +9,7 @@
# Compilerprocs for strings that do not depend on the string implementation.
proc cmpStrings(a, b: string): int {.inline, compilerProc.} =
proc cmpStrings(a, b: string): int {.inline, compilerproc.} =
let alen = a.len
let blen = b.len
let minlen = min(alen, blen)
@ -20,7 +20,7 @@ proc cmpStrings(a, b: string): int {.inline, compilerProc.} =
else:
result = alen - blen
proc eqStrings(a, b: string): bool {.inline, compilerProc.} =
proc eqStrings(a, b: string): bool {.inline, compilerproc.} =
let alen = a.len
let blen = b.len
if alen == blen:
@ -135,7 +135,7 @@ const
1e20, 1e21, 1e22]
proc nimParseBiggestFloat(s: string, number: var BiggestFloat,
start = 0): int {.compilerProc.} =
start = 0): int {.compilerproc.} =
# This routine attempt to parse float that can parsed quickly.
# ie whose integer part can fit inside a 53bits integer.
# their real exponent must also be <= 22. If the float doesn't follow

View file

@ -40,7 +40,7 @@ else:
template allocStrNoInit(size: untyped): untyped =
cast[NimString](newObjNoInit(addr(strDesc), size))
proc rawNewStringNoInit(space: int): NimString {.compilerProc.} =
proc rawNewStringNoInit(space: int): NimString {.compilerproc.} =
var s = space
if s < 7: s = 7
result = allocStrNoInit(sizeof(TGenericSeq) + s + 1)
@ -49,7 +49,7 @@ proc rawNewStringNoInit(space: int): NimString {.compilerProc.} =
when defined(gogc):
result.elemSize = 1
proc rawNewString(space: int): NimString {.compilerProc.} =
proc rawNewString(space: int): NimString {.compilerproc.} =
var s = space
if s < 7: s = 7
result = allocStr(sizeof(TGenericSeq) + s + 1)
@ -58,11 +58,11 @@ proc rawNewString(space: int): NimString {.compilerProc.} =
when defined(gogc):
result.elemSize = 1
proc mnewString(len: int): NimString {.compilerProc.} =
proc mnewString(len: int): NimString {.compilerproc.} =
result = rawNewString(len)
result.len = len
proc copyStrLast(s: NimString, start, last: int): NimString {.compilerProc.} =
proc copyStrLast(s: NimString, start, last: int): NimString {.compilerproc.} =
# This is not used by most recent versions of the compiler anymore, but
# required for bootstrapping purposes.
let start = max(start, 0)
@ -76,17 +76,17 @@ proc copyStrLast(s: NimString, start, last: int): NimString {.compilerProc.} =
else:
result = rawNewString(len)
proc copyStr(s: NimString, start: int): NimString {.compilerProc.} =
proc copyStr(s: NimString, start: int): NimString {.compilerproc.} =
# This is not used by most recent versions of the compiler anymore, but
# required for bootstrapping purposes.
if s == nil: return nil
result = copyStrLast(s, start, s.len-1)
proc nimToCStringConv(s: NimString): cstring {.compilerProc, nonReloadable, inline.} =
proc nimToCStringConv(s: NimString): cstring {.compilerproc, nonReloadable, inline.} =
if s == nil or s.len == 0: result = cstring""
else: result = cstring(addr s.data)
proc toNimStr(str: cstring, len: int): NimString {.compilerProc.} =
proc toNimStr(str: cstring, len: int): NimString {.compilerproc.} =
result = rawNewStringNoInit(len)
result.len = len
copyMem(addr(result.data), str, len + 1)
@ -245,7 +245,7 @@ proc setLengthStr(s: NimString, newLen: int): NimString {.compilerRtl.} =
# ----------------- sequences ----------------------------------------------
proc incrSeq(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
proc incrSeq(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerproc.} =
# increments the length by one:
# this is needed for supporting ``add``;
#
@ -260,7 +260,7 @@ proc incrSeq(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
result.reserved = r
inc(result.len)
proc incrSeqV2(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
proc incrSeqV2(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerproc.} =
# incrSeq version 2
result = seq
if result.len >= result.space:
@ -272,7 +272,7 @@ proc incrSeqV2(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
template `+!`(p: pointer, s: int): pointer =
cast[pointer](cast[int](p) +% s)
proc incrSeqV3(s: PGenericSeq, typ: PNimType): PGenericSeq {.compilerProc.} =
proc incrSeqV3(s: PGenericSeq, typ: PNimType): PGenericSeq {.compilerproc.} =
if s == nil:
result = cast[PGenericSeq](newSeq(typ, 1))
result.len = 0

View file

@ -14,8 +14,10 @@
import dynlib
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
{.passC: "-DWIN32_LEAN_AND_MEAN".}
{.passc: "-DWIN32_LEAN_AND_MEAN".}
const
useWinUnicode* = not defined(useWinAnsi)
@ -136,11 +138,11 @@ proc getVersion*(): DWORD {.stdcall, dynlib: "kernel32", importc: "GetVersion".}
proc closeHandle*(hObject: Handle): WINBOOL {.stdcall, dynlib: "kernel32",
importc: "CloseHandle".}
proc readFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToRead: int32,
proc readFile*(hFile: Handle, buffer: pointer, nNumberOfBytesToRead: int32,
lpNumberOfBytesRead: ptr int32, lpOverlapped: pointer): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "ReadFile".}
proc writeFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToWrite: int32,
proc writeFile*(hFile: Handle, buffer: pointer, nNumberOfBytesToWrite: int32,
lpNumberOfBytesWritten: ptr int32,
lpOverlapped: pointer): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "WriteFile".}
@ -215,13 +217,13 @@ when useWinUnicode:
proc formatMessageW*(dwFlags: int32, lpSource: pointer,
dwMessageId, dwLanguageId: int32,
lpBuffer: pointer, nSize: int32,
Arguments: pointer): int32 {.
arguments: pointer): int32 {.
importc: "FormatMessageW", stdcall, dynlib: "kernel32".}
else:
proc formatMessageA*(dwFlags: int32, lpSource: pointer,
dwMessageId, dwLanguageId: int32,
lpBuffer: pointer, nSize: int32,
Arguments: pointer): int32 {.
arguments: pointer): int32 {.
importc: "FormatMessageA", stdcall, dynlib: "kernel32".}
proc localFree*(p: pointer) {.
@ -414,13 +416,13 @@ proc sleep*(dwMilliseconds: int32){.stdcall, dynlib: "kernel32",
importc: "Sleep".}
when useWinUnicode:
proc shellExecuteW*(HWND: Handle, lpOperation, lpFile,
proc shellExecuteW*(hwnd: Handle, lpOperation, lpFile,
lpParameters, lpDirectory: WideCString,
nShowCmd: int32): Handle{.
stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW".}
else:
proc shellExecuteA*(HWND: Handle, lpOperation, lpFile,
proc shellExecuteA*(hwnd: Handle, lpOperation, lpFile,
lpParameters, lpDirectory: cstring,
nShowCmd: int32): Handle{.
stdcall, dynlib: "shell32.dll", importc: "ShellExecuteA".}
@ -482,12 +484,6 @@ type
sin6_addr*: In6_addr
sin6_scope_id*: int32 # unsigned
Sockaddr_in6_old* = object
sin6_family*: uint16
sin6_port*: int16 # unsigned
sin6_flowinfo*: int32 # unsigned
sin6_addr*: In6_addr
Sockaddr_storage* {.importc: "SOCKADDR_STORAGE",
header: "winsock2.h".} = object
ss_family*: uint16
@ -707,18 +703,18 @@ const
ERROR_HANDLE_EOF* = 38
ERROR_BAD_ARGUMENTS* = 165
proc duplicateHandle*(hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE,
hTargetProcessHandle: HANDLE,
lpTargetHandle: ptr HANDLE,
proc duplicateHandle*(hSourceProcessHandle: Handle, hSourceHandle: Handle,
hTargetProcessHandle: Handle,
lpTargetHandle: ptr Handle,
dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32",
importc: "DuplicateHandle".}
proc setHandleInformation*(hObject: HANDLE, dwMask: DWORD,
proc setHandleInformation*(hObject: Handle, dwMask: DWORD,
dwFlags: DWORD): WINBOOL {.stdcall,
dynlib: "kernel32", importc: "SetHandleInformation".}
proc getCurrentProcess*(): HANDLE{.stdcall, dynlib: "kernel32",
proc getCurrentProcess*(): Handle{.stdcall, dynlib: "kernel32",
importc: "GetCurrentProcess".}
when useWinUnicode:
@ -1004,7 +1000,7 @@ const
type
WAITORTIMERCALLBACK* = proc(para1: pointer, para2: int32): void {.stdcall.}
proc postQueuedCompletionStatus*(CompletionPort: HANDLE,
proc postQueuedCompletionStatus*(CompletionPort: Handle,
dwNumberOfBytesTransferred: DWORD,
dwCompletionKey: ULONG_PTR,
lpOverlapped: pointer): bool
@ -1017,7 +1013,7 @@ proc registerWaitForSingleObject*(phNewWaitObject: ptr Handle, hObject: Handle,
dwFlags: ULONG): bool
{.stdcall, dynlib: "kernel32", importc: "RegisterWaitForSingleObject".}
proc unregisterWait*(WaitHandle: HANDLE): DWORD
proc unregisterWait*(WaitHandle: Handle): DWORD
{.stdcall, dynlib: "kernel32", importc: "UnregisterWait".}
proc openProcess*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
@ -1104,6 +1100,9 @@ proc toFILETIME*(t: int64): FILETIME =
type
LPFILETIME* = ptr FILETIME
proc setFileTime*(hFile: HANDLE, lpCreationTime: LPFILETIME,
proc setFileTime*(hFile: Handle, lpCreationTime: LPFILETIME,
lpLastAccessTime: LPFILETIME, lpLastWriteTime: LPFILETIME): WINBOOL
{.stdcall, dynlib: "kernel32", importc: "SetFileTime".}
when defined(nimHasStyleChecks):
{.pop.} # {.push styleChecks: off.}