styleCheck: make the compiler and large parts of the stdlib compatible with --styleCheck:error
This commit is contained in:
parent
96523cdd3e
commit
c94647aeca
90 changed files with 680 additions and 652 deletions
|
|
@ -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.
|
# means '*T'. See posix.nim for lots of examples that do that in the wild.
|
||||||
let callee = call.sons[0]
|
let callee = call.sons[0]
|
||||||
if callee.kind == nkSym and
|
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 != {}:
|
{lfHeader, lfNoDecl} * callee.sym.loc.flags != {}:
|
||||||
result = addrLoc(p.config, a)
|
result = addrLoc(p.config, a)
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -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
|
# with the new semantics for 'nil' strings, we can map "" to nil and
|
||||||
# save tons of allocations:
|
# save tons of allocations:
|
||||||
if n.strVal.len == 0 and optNilSeqs notin p.options and
|
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)
|
result = genNilStringLiteral(p.module, n.info)
|
||||||
else:
|
else:
|
||||||
result = genStringLiteral(p.module, n)
|
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)
|
if conf.selectedGC == gcNone: message(conf, n.info, warnGcMem, n.renderTree)
|
||||||
|
|
||||||
proc strLoc(p: BProc; d: TLoc): Rope =
|
proc strLoc(p: BProc; d: TLoc): Rope =
|
||||||
if p.config.selectedGc == gcDestructors:
|
if p.config.selectedGC == gcDestructors:
|
||||||
result = byRefLoc(p, d)
|
result = byRefLoc(p, d)
|
||||||
else:
|
else:
|
||||||
result = rdLoc(d)
|
result = rdLoc(d)
|
||||||
|
|
@ -1657,7 +1657,7 @@ proc makeAddr(n: PNode): PNode =
|
||||||
result.typ = makePtrType(n.typ)
|
result.typ = makePtrType(n.typ)
|
||||||
|
|
||||||
proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) =
|
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])
|
e.sons[1] = makeAddr(e[1])
|
||||||
genCall(p, e, d)
|
genCall(p, e, d)
|
||||||
return
|
return
|
||||||
|
|
@ -1686,7 +1686,7 @@ proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) =
|
||||||
gcUsage(p.config, e)
|
gcUsage(p.config, e)
|
||||||
|
|
||||||
proc genSetLengthStr(p: BProc, e: PNode, d: var TLoc) =
|
proc genSetLengthStr(p: BProc, e: PNode, d: var TLoc) =
|
||||||
if p.config.selectedGc == gcDestructors:
|
if p.config.selectedGC == gcDestructors:
|
||||||
binaryStmtAddr(p, e, d, "setLengthStrV2")
|
binaryStmtAddr(p, e, d, "setLengthStrV2")
|
||||||
else:
|
else:
|
||||||
var a, b, call: TLoc
|
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:
|
if srcTyp.kind in {tyPtr, tyPointer} and etyp.kind in IntegralTypes:
|
||||||
putIntoDest(p, d, e, "(($1) (ptrdiff_t) ($2))" %
|
putIntoDest(p, d, e, "(($1) (ptrdiff_t) ($2))" %
|
||||||
[getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
|
[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))" %
|
putIntoDest(p, d, e, "(*($1*) (&$2))" %
|
||||||
[getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
|
[getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
|
||||||
else:
|
else:
|
||||||
|
|
@ -2134,7 +2134,7 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
|
||||||
genAssignment(p, dest, call, {})
|
genAssignment(p, dest, call, {})
|
||||||
of mAppendStrStr: genStrAppend(p, e, d)
|
of mAppendStrStr: genStrAppend(p, e, d)
|
||||||
of mAppendSeqElem:
|
of mAppendSeqElem:
|
||||||
if p.config.selectedGc == gcDestructors:
|
if p.config.selectedGC == gcDestructors:
|
||||||
e.sons[1] = makeAddr(e[1])
|
e.sons[1] = makeAddr(e[1])
|
||||||
genCall(p, e, d)
|
genCall(p, e, d)
|
||||||
else:
|
else:
|
||||||
|
|
@ -2773,7 +2773,7 @@ proc getNullValueAuxT(p: BProc; orig, t: PType; obj, cons: PNode,
|
||||||
inc count
|
inc count
|
||||||
getNullValueAux(p, t, obj, cons, result, count)
|
getNullValueAux(p, t, obj, cons, result, count)
|
||||||
# do not emit '{}' as that is not valid C:
|
# 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 "}"
|
elif not p.module.compileToCpp: result.add "}"
|
||||||
|
|
||||||
proc genConstObjConstr(p: BProc; n: PNode): Rope =
|
proc genConstObjConstr(p: BProc; n: PNode): Rope =
|
||||||
|
|
@ -2847,7 +2847,7 @@ proc genConstExpr(p: BProc, n: PNode): Rope =
|
||||||
of nkBracket, nkPar, nkTupleConstr, nkClosure:
|
of nkBracket, nkPar, nkTupleConstr, nkClosure:
|
||||||
var t = skipTypes(n.typ, abstractInstOwned)
|
var t = skipTypes(n.typ, abstractInstOwned)
|
||||||
if t.kind == tySequence:
|
if t.kind == tySequence:
|
||||||
if p.config.selectedGc == gcDestructors:
|
if p.config.selectedGC == gcDestructors:
|
||||||
result = genConstSeqV2(p, n, n.typ)
|
result = genConstSeqV2(p, n, n.typ)
|
||||||
else:
|
else:
|
||||||
result = genConstSeq(p, n, n.typ)
|
result = genConstSeq(p, n, n.typ)
|
||||||
|
|
@ -2871,7 +2871,7 @@ proc genConstExpr(p: BProc, n: PNode): Rope =
|
||||||
of nkObjConstr:
|
of nkObjConstr:
|
||||||
result = genConstObjConstr(p, n)
|
result = genConstObjConstr(p, n)
|
||||||
of nkStrLit..nkTripleStrLit:
|
of nkStrLit..nkTripleStrLit:
|
||||||
if p.config.selectedGc == gcDestructors:
|
if p.config.selectedGC == gcDestructors:
|
||||||
result = genStringLiteralV2Const(p.module, n)
|
result = genStringLiteralV2Const(p.module, n)
|
||||||
else:
|
else:
|
||||||
var d: TLoc
|
var d: TLoc
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ const
|
||||||
stringCaseThreshold = 8
|
stringCaseThreshold = 8
|
||||||
# above X strings a hash-switch for strings is generated
|
# 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
|
if p.config.selectedGC in {gcMarkAndSweep, gcDestructors, gcV2, gcRefc} and
|
||||||
optNimV2 notin p.config.globalOptions and
|
optNimV2 notin p.config.globalOptions and
|
||||||
containsGarbageCollectedRef(v.loc.t):
|
containsGarbageCollectedRef(v.loc.t):
|
||||||
|
|
|
||||||
|
|
@ -978,7 +978,7 @@ proc getNimNode(m: BModule): Rope =
|
||||||
result = "$1[$2]" % [m.typeNodesName, rope(m.typeNodes)]
|
result = "$1[$2]" % [m.typeNodesName, rope(m.typeNodes)]
|
||||||
inc(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
|
return if m.hcrOn: "(*".rope & name & ")" else: name
|
||||||
|
|
||||||
proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
|
proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
|
||||||
|
|
@ -990,7 +990,7 @@ proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
|
||||||
else:
|
else:
|
||||||
nimtypeKind = ord(typ.kind)
|
nimtypeKind = ord(typ.kind)
|
||||||
|
|
||||||
let nameHcr = TINameForHcr(m, name)
|
let nameHcr = tiNameForHcr(m, name)
|
||||||
|
|
||||||
var size: Rope
|
var size: Rope
|
||||||
if tfIncompleteStruct in typ.flags: size = rope"void*"
|
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:
|
if typename == "ref object" and origType.skipTypes(skipPtrs).sym != nil:
|
||||||
typename = "anon ref object from " & m.config$origType.skipTypes(skipPtrs).sym.info
|
typename = "anon ref object from " & m.config$origType.skipTypes(skipPtrs).sym.info
|
||||||
addf(m.s[cfsTypeInit3], "$1.name = $2;$n",
|
addf(m.s[cfsTypeInit3], "$1.name = $2;$n",
|
||||||
[nameHcr, makeCstring typename])
|
[nameHcr, makeCString typename])
|
||||||
discard cgsym(m, "nimTypeRoot")
|
discard cgsym(m, "nimTypeRoot")
|
||||||
addf(m.s[cfsTypeInit3], "$1.nextType = nimTypeRoot; nimTypeRoot=&$1;$n",
|
addf(m.s[cfsTypeInit3], "$1.nextType = nimTypeRoot; nimTypeRoot=&$1;$n",
|
||||||
[nameHcr])
|
[nameHcr])
|
||||||
|
|
@ -1142,7 +1142,7 @@ proc genObjectInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo
|
||||||
var tmp = getNimNode(m)
|
var tmp = getNimNode(m)
|
||||||
if not isImportedType(typ):
|
if not isImportedType(typ):
|
||||||
genObjectFields(m, typ, origType, typ.n, tmp, info)
|
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]
|
var t = typ.sons[0]
|
||||||
while t != nil:
|
while t != nil:
|
||||||
t = t.skipTypes(skipPtrs)
|
t = t.skipTypes(skipPtrs)
|
||||||
|
|
@ -1170,7 +1170,7 @@ proc genTupleInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo)
|
||||||
else:
|
else:
|
||||||
addf(m.s[cfsTypeInit3], "$1.len = $2; $1.kind = 2;$n",
|
addf(m.s[cfsTypeInit3], "$1.len = $2; $1.kind = 2;$n",
|
||||||
[expr, rope(length)])
|
[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) =
|
proc genEnumInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
|
||||||
# Type information for enumerations is quite heavy, so we do some
|
# 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)
|
add(m.s[cfsTypeInit3], specialCases)
|
||||||
addf(m.s[cfsTypeInit3],
|
addf(m.s[cfsTypeInit3],
|
||||||
"$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n",
|
"$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:
|
if hasHoles:
|
||||||
# 1 << 2 is {ntfEnumHole}
|
# 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) =
|
proc genSetInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
|
||||||
assert(typ.sons[0] != nil)
|
assert(typ.sons[0] != nil)
|
||||||
genTypeInfoAux(m, typ, typ, name, info)
|
genTypeInfoAux(m, typ, typ, name, info)
|
||||||
var tmp = getNimNode(m)
|
var tmp = getNimNode(m)
|
||||||
addf(m.s[cfsTypeInit3], "$1.len = $2; $1.kind = 0;$n" & "$3.node = &$1;$n",
|
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) =
|
proc genArrayInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
|
||||||
genTypeInfoAuxBase(m, typ, typ, name, genTypeInfo(m, typ.sons[1], info), info)
|
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 != gcDestructors:
|
||||||
if m.config.selectedGC >= gcMarkAndSweep:
|
if m.config.selectedGC >= gcMarkAndSweep:
|
||||||
let markerProc = genTraverseProc(m, origType, sig)
|
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:
|
of tyRef:
|
||||||
genTypeInfoAux(m, t, t, result, info)
|
genTypeInfoAux(m, t, t, result, info)
|
||||||
if m.config.selectedGC >= gcMarkAndSweep:
|
if m.config.selectedGC >= gcMarkAndSweep:
|
||||||
let markerProc = genTraverseProc(m, origType, sig)
|
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 tyPtr, tyRange, tyUncheckedArray: genTypeInfoAux(m, t, t, result, info)
|
||||||
of tyArray: genArrayInfo(m, t, result, info)
|
of tyArray: genArrayInfo(m, t, result, info)
|
||||||
of tySet: genSetInfo(m, t, result, info)
|
of tySet: genSetInfo(m, t, result, info)
|
||||||
|
|
|
||||||
|
|
@ -268,7 +268,7 @@ proc genLineDir(p: BProc, t: PNode) =
|
||||||
[line, makeCString(toFilename(p.config, t.info))])
|
[line, makeCString(toFilename(p.config, t.info))])
|
||||||
elif ({optLineTrace, optStackTrace} * p.options ==
|
elif ({optLineTrace, optStackTrace} * p.options ==
|
||||||
{optLineTrace, optStackTrace}) and
|
{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):
|
if freshLineInfo(p, t.info):
|
||||||
linefmt(p, cpsStmts, "nimln_($1, $2);$n",
|
linefmt(p, cpsStmts, "nimln_($1, $2);$n",
|
||||||
[line, quotedFilename(p.config, t.info)])
|
[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")
|
result = rope(if p.module.compileToCpp: "len" else: "Sup.len")
|
||||||
|
|
||||||
proc lenExpr(p: BProc; a: TLoc): Rope =
|
proc lenExpr(p: BProc; a: TLoc): Rope =
|
||||||
if p.config.selectedGc == gcDestructors:
|
if p.config.selectedGC == gcDestructors:
|
||||||
result = rdLoc(a) & ".len"
|
result = rdLoc(a) & ".len"
|
||||||
else:
|
else:
|
||||||
result = "($1 ? $1->$2 : 0)" % [rdLoc(a), lenField(p)]
|
result = "($1 ? $1->$2 : 0)" % [rdLoc(a), lenField(p)]
|
||||||
|
|
||||||
proc dataField(p: BProc): Rope =
|
proc dataField(p: BProc): Rope =
|
||||||
if p.config.selectedGc == gcDestructors:
|
if p.config.selectedGC == gcDestructors:
|
||||||
result = rope".p->data"
|
result = rope".p->data"
|
||||||
else:
|
else:
|
||||||
result = rope"->data"
|
result = rope"->data"
|
||||||
|
|
@ -380,10 +380,10 @@ proc isComplexValueType(t: PType): bool {.inline.} =
|
||||||
(t.kind == tyProc and t.callConv == ccClosure)
|
(t.kind == tyProc and t.callConv == ccClosure)
|
||||||
|
|
||||||
proc resetLoc(p: BProc, loc: var TLoc) =
|
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)
|
let typ = skipTypes(loc.t, abstractVarRange)
|
||||||
if isImportedCppType(typ): return
|
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
|
assert rdLoc(loc) != nil
|
||||||
linefmt(p, cpsStmts, "$1.len = 0; $1.p = NIM_NIL;$n", [rdLoc(loc)])
|
linefmt(p, cpsStmts, "$1.len = 0; $1.p = NIM_NIL;$n", [rdLoc(loc)])
|
||||||
elif not isComplexValueType(typ):
|
elif not isComplexValueType(typ):
|
||||||
|
|
@ -414,7 +414,7 @@ proc resetLoc(p: BProc, loc: var TLoc) =
|
||||||
|
|
||||||
proc constructLoc(p: BProc, loc: TLoc, isTemp = false) =
|
proc constructLoc(p: BProc, loc: TLoc, isTemp = false) =
|
||||||
let typ = loc.t
|
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)])
|
linefmt(p, cpsStmts, "$1.len = 0; $1.p = NIM_NIL;$n", [rdLoc(loc)])
|
||||||
elif not isComplexValueType(typ):
|
elif not isComplexValueType(typ):
|
||||||
linefmt(p, cpsStmts, "$1 = ($2)0;$n", [rdLoc(loc),
|
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:
|
if sfSystemModule in module.flags:
|
||||||
incl result.flags, preventStackTrace
|
incl result.flags, preventStackTrace
|
||||||
excl(result.preInitProc.options, optStackTrace)
|
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""
|
else: AbsoluteFile""
|
||||||
open(result.ndi, ndiName, g.config)
|
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
|
let f = if graph.config.headerFile.len > 0: AbsoluteFile graph.config.headerFile
|
||||||
else: graph.config.projectFull
|
else: graph.config.projectFull
|
||||||
g.generatedHeader = rawNewModule(g, module,
|
g.generatedHeader = rawNewModule(g, module,
|
||||||
changeFileExt(completeCFilePath(graph.config, f), hExt))
|
changeFileExt(completeCfilePath(graph.config, f), hExt))
|
||||||
incl g.generatedHeader.flags, isHeaderFile
|
incl g.generatedHeader.flags, isHeaderFile
|
||||||
|
|
||||||
proc writeHeader(m: BModule) =
|
proc writeHeader(m: BModule) =
|
||||||
|
|
@ -1838,9 +1838,9 @@ proc writeHeader(m: BModule) =
|
||||||
proc getCFile(m: BModule): AbsoluteFile =
|
proc getCFile(m: BModule): AbsoluteFile =
|
||||||
let ext =
|
let ext =
|
||||||
if m.compileToCpp: ".nim.cpp"
|
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"
|
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:
|
when false:
|
||||||
proc myOpenCached(graph: ModuleGraph; module: PSym, rd: PRodReader): PPassContext =
|
proc myOpenCached(graph: ModuleGraph; module: PSym, rd: PRodReader): PPassContext =
|
||||||
|
|
@ -1920,7 +1920,7 @@ proc writeModule(m: BModule, pending: bool) =
|
||||||
generateThreadVarsSize(m)
|
generateThreadVarsSize(m)
|
||||||
|
|
||||||
var cf = Cfile(nimname: m.module.name.s, cname: cfile,
|
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)
|
var code = genModule(m, cf)
|
||||||
if code != nil:
|
if code != nil:
|
||||||
when hasTinyCBackend:
|
when hasTinyCBackend:
|
||||||
|
|
@ -1932,7 +1932,7 @@ proc writeModule(m: BModule, pending: bool) =
|
||||||
addFileToCompile(m.config, cf)
|
addFileToCompile(m.config, cf)
|
||||||
elif pending and mergeRequired(m) and sfMainModule notin m.module.flags:
|
elif pending and mergeRequired(m) and sfMainModule notin m.module.flags:
|
||||||
let cf = Cfile(nimname: m.module.name.s, cname: cfile,
|
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)
|
mergeFiles(cfile, m)
|
||||||
genInitCode(m)
|
genInitCode(m)
|
||||||
finishTypeDescriptions(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
|
# ``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:
|
# 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,
|
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}
|
if not fileExists(cf.obj): cf.flags = {CfileFlag.Cached}
|
||||||
addFileToCompile(m.config, cf)
|
addFileToCompile(m.config, cf)
|
||||||
close(m.ndi)
|
close(m.ndi)
|
||||||
|
|
@ -1954,7 +1954,7 @@ proc writeModule(m: BModule, pending: bool) =
|
||||||
proc updateCachedModule(m: BModule) =
|
proc updateCachedModule(m: BModule) =
|
||||||
let cfile = getCFile(m)
|
let cfile = getCFile(m)
|
||||||
var cf = Cfile(nimname: m.module.name.s, cname: cfile,
|
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:
|
if mergeRequired(m) and sfMainModule notin m.module.flags:
|
||||||
mergeFiles(cfile, m)
|
mergeFiles(cfile, m)
|
||||||
|
|
|
||||||
|
|
@ -100,7 +100,7 @@ type
|
||||||
TypeCache* = Table[SigHash, Rope]
|
TypeCache* = Table[SigHash, Rope]
|
||||||
TypeCacheWithOwner* = Table[SigHash, tuple[str: Rope, owner: PSym]]
|
TypeCacheWithOwner* = Table[SigHash, tuple[str: Rope, owner: PSym]]
|
||||||
|
|
||||||
Codegenflag* = enum
|
CodegenFlag* = enum
|
||||||
preventStackTrace, # true if stack traces need to be prevented
|
preventStackTrace, # true if stack traces need to be prevented
|
||||||
usesThreadVars, # true if the module uses a thread var
|
usesThreadVars, # true if the module uses a thread var
|
||||||
frameDeclared, # hack for ROD support so that we don't declare
|
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
|
TCGen = object of PPassContext # represents a C source file
|
||||||
s*: TCFileSections # sections of the C file
|
s*: TCFileSections # sections of the C file
|
||||||
flags*: set[Codegenflag]
|
flags*: set[CodegenFlag]
|
||||||
module*: PSym
|
module*: PSym
|
||||||
filename*: AbsoluteFile
|
filename*: AbsoluteFile
|
||||||
cfilename*: AbsoluteFile # filename of the module (including path,
|
cfilename*: AbsoluteFile # filename of the module (including path,
|
||||||
|
|
|
||||||
|
|
@ -277,7 +277,7 @@ proc testCompileOption*(conf: ConfigRef; switch: string, info: TLineInfo): bool
|
||||||
of "rangechecks": result = contains(conf.options, optRangeCheck)
|
of "rangechecks": result = contains(conf.options, optRangeCheck)
|
||||||
of "boundchecks": result = contains(conf.options, optBoundsCheck)
|
of "boundchecks": result = contains(conf.options, optBoundsCheck)
|
||||||
of "overflowchecks": result = contains(conf.options, optOverflowCheck)
|
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 "linedir": result = contains(conf.options, optLineDir)
|
||||||
of "assertions", "a": result = contains(conf.options, optAssert)
|
of "assertions", "a": result = contains(conf.options, optAssert)
|
||||||
of "run", "r": result = contains(conf.globalOptions, optRun)
|
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 "rangechecks": processOnOffSwitch(conf, {optRangeCheck}, arg, pass, info)
|
||||||
of "boundchecks": processOnOffSwitch(conf, {optBoundsCheck}, arg, pass, info)
|
of "boundchecks": processOnOffSwitch(conf, {optBoundsCheck}, arg, pass, info)
|
||||||
of "overflowchecks": processOnOffSwitch(conf, {optOverflowCheck}, 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 "linedir": processOnOffSwitch(conf, {optLineDir}, arg, pass, info)
|
||||||
of "assertions", "a": processOnOffSwitch(conf, {optAssert}, arg, pass, info)
|
of "assertions", "a": processOnOffSwitch(conf, {optAssert}, arg, pass, info)
|
||||||
of "deadcodeelim": discard # deprecated, dead code elim always on
|
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 =
|
argsCount: var int; config: ConfigRef): bool =
|
||||||
if argsCount == 0:
|
if argsCount == 0:
|
||||||
# nim filename.nims is the same as "nim e filename.nims":
|
# nim filename.nims is the same as "nim e filename.nims":
|
||||||
if p.key.endswith(".nims"):
|
if p.key.endsWith(".nims"):
|
||||||
config.command = "e"
|
config.command = "e"
|
||||||
incl(config.globalOptions, optWasNimscript)
|
incl(config.globalOptions, optWasNimscript)
|
||||||
config.projectName = unixToNativePath(p.key)
|
config.projectName = unixToNativePath(p.key)
|
||||||
|
|
|
||||||
|
|
@ -96,3 +96,4 @@ proc initDefines*(symbols: StringTableRef) =
|
||||||
defineSymbol("nimHasHint" & s)
|
defineSymbol("nimHasHint" & s)
|
||||||
|
|
||||||
defineSymbol("nimFixedOwned")
|
defineSymbol("nimFixedOwned")
|
||||||
|
defineSymbol("nimHasStyleChecks")
|
||||||
|
|
|
||||||
|
|
@ -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])
|
localError(conf, info, "unknown C compiler: '$1'. Available options are: $2" % [ccname, ccList])
|
||||||
conf.compileOptions = getConfigVar(conf, conf.cCompiler, ".options.always")
|
conf.compileOptions = getConfigVar(conf, conf.cCompiler, ".options.always")
|
||||||
conf.linkOptions = ""
|
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)
|
for i in low(CC) .. high(CC): undefSymbol(conf.symbols, CC[i].name)
|
||||||
defineSymbol(conf.symbols, CC[conf.cCompiler].name)
|
defineSymbol(conf.symbols, CC[conf.cCompiler].name)
|
||||||
|
|
||||||
|
|
@ -443,10 +443,10 @@ proc initVars*(conf: ConfigRef) =
|
||||||
defineSymbol(conf.symbols, CC[conf.cCompiler].name)
|
defineSymbol(conf.symbols, CC[conf.cCompiler].name)
|
||||||
addCompileOption(conf, getConfigVar(conf, conf.cCompiler, ".options.always"))
|
addCompileOption(conf, getConfigVar(conf, conf.cCompiler, ".options.always"))
|
||||||
#addLinkOption(getConfigVar(cCompiler, ".options.linker"))
|
#addLinkOption(getConfigVar(cCompiler, ".options.linker"))
|
||||||
if len(conf.ccompilerpath) == 0:
|
if len(conf.cCompilerPath) == 0:
|
||||||
conf.ccompilerpath = getConfigVar(conf, conf.cCompiler, ".path")
|
conf.cCompilerPath = getConfigVar(conf, conf.cCompiler, ".path")
|
||||||
|
|
||||||
proc completeCFilePath*(conf: ConfigRef; cfile: AbsoluteFile,
|
proc completeCfilePath*(conf: ConfigRef; cfile: AbsoluteFile,
|
||||||
createSubDir: bool = true): AbsoluteFile =
|
createSubDir: bool = true): AbsoluteFile =
|
||||||
result = completeGeneratedFilePath(conf, cfile, createSubDir)
|
result = completeGeneratedFilePath(conf, cfile, createSubDir)
|
||||||
|
|
||||||
|
|
@ -591,7 +591,7 @@ proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile, isMainFile = false): str
|
||||||
for includeDir in items(conf.cIncludes):
|
for includeDir in items(conf.cIncludes):
|
||||||
includeCmd.add(join([CC[c].includeCmd, includeDir.quoteShell]))
|
includeCmd.add(join([CC[c].includeCmd, includeDir.quoteShell]))
|
||||||
|
|
||||||
compilePattern = joinPath(conf.ccompilerpath, exe)
|
compilePattern = joinPath(conf.cCompilerPath, exe)
|
||||||
else:
|
else:
|
||||||
includeCmd = ""
|
includeCmd = ""
|
||||||
compilePattern = getCompilerExe(conf, c, cfile.cname)
|
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):
|
if not cfile.flags.contains(CfileFlag.External) or noAbsolutePaths(conf):
|
||||||
toObjFile(conf, cf).string
|
toObjFile(conf, cf).string
|
||||||
else:
|
else:
|
||||||
completeCFilePath(conf, toObjFile(conf, cf)).string
|
completeCfilePath(conf, toObjFile(conf, cf)).string
|
||||||
elif noAbsolutePaths(conf):
|
elif noAbsolutePaths(conf):
|
||||||
extractFilename(cfile.obj.string)
|
extractFilename(cfile.obj.string)
|
||||||
else:
|
else:
|
||||||
|
|
@ -666,11 +666,11 @@ proc addExternalFileToCompile*(conf: ConfigRef; c: var Cfile) =
|
||||||
|
|
||||||
proc addExternalFileToCompile*(conf: ConfigRef; filename: AbsoluteFile) =
|
proc addExternalFileToCompile*(conf: ConfigRef; filename: AbsoluteFile) =
|
||||||
var c = Cfile(nimname: splitFile(filename).name, cname: filename,
|
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})
|
flags: {CfileFlag.External})
|
||||||
addExternalFileToCompile(conf, c)
|
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) =
|
prettyCmds: var TStringSeq) =
|
||||||
var currIdx = 0
|
var currIdx = 0
|
||||||
for it in list:
|
for it in list:
|
||||||
|
|
@ -704,7 +704,7 @@ proc getLinkCmd(conf: ConfigRef; output: AbsoluteFile,
|
||||||
# bug #6452: We must not use ``quoteShell`` here for ``linkerExe``
|
# bug #6452: We must not use ``quoteShell`` here for ``linkerExe``
|
||||||
if needsExeExt(conf): linkerExe = addFileExt(linkerExe, "exe")
|
if needsExeExt(conf): linkerExe = addFileExt(linkerExe, "exe")
|
||||||
if noAbsolutePaths(conf): result = linkerExe
|
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:
|
let buildgui = if optGenGuiApp in conf.globalOptions and conf.target.targetOS == osWindows:
|
||||||
CC[conf.cCompiler].buildGui
|
CC[conf.cCompiler].buildGui
|
||||||
else:
|
else:
|
||||||
|
|
@ -856,7 +856,7 @@ proc linkViaResponseFile(conf: ConfigRef; cmd: string) =
|
||||||
finally:
|
finally:
|
||||||
removeFile(linkerArgs)
|
removeFile(linkerArgs)
|
||||||
|
|
||||||
proc getObjFilePath(conf: ConfigRef, f: CFile): string =
|
proc getObjFilePath(conf: ConfigRef, f: Cfile): string =
|
||||||
if noAbsolutePaths(conf): f.obj.extractFilename
|
if noAbsolutePaths(conf): f.obj.extractFilename
|
||||||
else: f.obj.string
|
else: f.obj.string
|
||||||
|
|
||||||
|
|
@ -1041,7 +1041,7 @@ proc runJsonBuildInstructions*(conf: ConfigRef; projectfile: AbsoluteFile) =
|
||||||
echo getCurrentException().getStackTrace()
|
echo getCurrentException().getStackTrace()
|
||||||
quit "error evaluating JSON file: " & jsonFile.string
|
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:
|
for it in list:
|
||||||
addf(result, "--file:r\"$1\"$N", [rope(it.cname.string)])
|
addf(result, "--file:r\"$1\"$N", [rope(it.cname.string)])
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,7 @@ proc opGorge*(cmd, input, cache: string, info: TLineInfo; conf: ConfigRef): (str
|
||||||
var readSuccessful = false
|
var readSuccessful = false
|
||||||
try:
|
try:
|
||||||
var p = startProcess(cmd, workingDir,
|
var p = startProcess(cmd, workingDir,
|
||||||
options={poEvalCommand, poStderrToStdout})
|
options={poEvalCommand, poStdErrToStdOut})
|
||||||
if input.len != 0:
|
if input.len != 0:
|
||||||
p.inputStream.write(input)
|
p.inputStream.write(input)
|
||||||
p.inputStream.close()
|
p.inputStream.close()
|
||||||
|
|
@ -49,7 +49,7 @@ proc opGorge*(cmd, input, cache: string, info: TLineInfo; conf: ConfigRef): (str
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
var p = startProcess(cmd, workingDir,
|
var p = startProcess(cmd, workingDir,
|
||||||
options={poEvalCommand, poStderrToStdout})
|
options={poEvalCommand, poStdErrToStdOut})
|
||||||
if input.len != 0:
|
if input.len != 0:
|
||||||
p.inputStream.write(input)
|
p.inputStream.write(input)
|
||||||
p.inputStream.close()
|
p.inputStream.close()
|
||||||
|
|
|
||||||
|
|
@ -139,7 +139,7 @@ proc importModuleAs(c: PContext; n: PNode, realModule: PSym): PSym =
|
||||||
|
|
||||||
proc myImportModule(c: PContext, n: PNode; importStmtResult: PNode): PSym =
|
proc myImportModule(c: PContext, n: PNode; importStmtResult: PNode): PSym =
|
||||||
let f = checkModuleName(c.config, n)
|
let f = checkModuleName(c.config, n)
|
||||||
if f != InvalidFileIDX:
|
if f != InvalidFileIdx:
|
||||||
let L = c.graph.importStack.len
|
let L = c.graph.importStack.len
|
||||||
let recursion = c.graph.importStack.find(f)
|
let recursion = c.graph.importStack.find(f)
|
||||||
c.graph.importStack.add f
|
c.graph.importStack.add f
|
||||||
|
|
|
||||||
|
|
@ -540,7 +540,7 @@ proc pArg(arg: PNode; c: var Con; isSink: bool): PNode =
|
||||||
result.add p(arg[0], c)
|
result.add p(arg[0], c)
|
||||||
for i in 1..<arg.len:
|
for i in 1..<arg.len:
|
||||||
var branch: PNode
|
var branch: PNode
|
||||||
if arg[i].kind == nkOfbranch:
|
if arg[i].kind == nkOfBranch:
|
||||||
branch = arg[i] # of branch conditions are constants
|
branch = arg[i] # of branch conditions are constants
|
||||||
branch[^1] = pArgIfTyped(arg[i][^1])
|
branch[^1] = pArgIfTyped(arg[i][^1])
|
||||||
elif arg[i].kind in {nkElifBranch, nkElifExpr}:
|
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)
|
result.add p(ri[0], c)
|
||||||
for i in 1..<ri.len:
|
for i in 1..<ri.len:
|
||||||
var branch: PNode
|
var branch: PNode
|
||||||
if ri[i].kind == nkOfbranch:
|
if ri[i].kind == nkOfBranch:
|
||||||
branch = ri[i] # of branch conditions are constants
|
branch = ri[i] # of branch conditions are constants
|
||||||
branch[^1] = moveOrCopyIfTyped(ri[i][^1])
|
branch[^1] = moveOrCopyIfTyped(ri[i][^1])
|
||||||
elif ri[i].kind in {nkElifBranch, nkElifExpr}:
|
elif ri[i].kind in {nkElifBranch, nkElifExpr}:
|
||||||
|
|
|
||||||
|
|
@ -262,7 +262,7 @@ proc `*`*(a: Int128, b: int32): Int128 =
|
||||||
proc `*=`*(a: var Int128, b: int32): Int128 =
|
proc `*=`*(a: var Int128, b: int32): Int128 =
|
||||||
result = result * b
|
result = result * b
|
||||||
|
|
||||||
proc makeint128(high,low: uint64): Int128 =
|
proc makeInt128(high,low: uint64): Int128 =
|
||||||
result.udata[0] = cast[uint32](low)
|
result.udata[0] = cast[uint32](low)
|
||||||
result.udata[1] = cast[uint32](low shr 32)
|
result.udata[1] = cast[uint32](low shr 32)
|
||||||
result.udata[2] = cast[uint32](high)
|
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 = makeInt128(high64(lhs) * low64(rhs) + low64(lhs) * high64(rhs) + a32 * b32, a00 * b00)
|
||||||
result = result + toInt128(a32 * b00) shl 32
|
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):
|
if isNegative != isNegative(result):
|
||||||
echo result
|
echo result
|
||||||
|
|
|
||||||
|
|
@ -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 mMinF64: applyFormat("nimMin($1, $2)", "nimMin($1, $2)")
|
||||||
of mMaxF64: applyFormat("nimMax($1, $2)", "nimMax($1, $2)")
|
of mMaxF64: applyFormat("nimMax($1, $2)", "nimMax($1, $2)")
|
||||||
of mAddU: applyFormat("", "")
|
of mAddU: applyFormat("", "")
|
||||||
of msubU: applyFormat("", "")
|
of mSubU: applyFormat("", "")
|
||||||
of mmulU: applyFormat("", "")
|
of mMulU: applyFormat("", "")
|
||||||
of mdivU: applyFormat("", "")
|
of mDivU: applyFormat("", "")
|
||||||
of mmodU: applyFormat("($1 % $2)", "($1 % $2)")
|
of mModU: applyFormat("($1 % $2)", "($1 % $2)")
|
||||||
of mEqI: applyFormat("($1 == $2)", "($1 == $2)")
|
of mEqI: applyFormat("($1 == $2)", "($1 == $2)")
|
||||||
of mLeI: applyFormat("($1 <= $2)", "($1 <= $2)")
|
of mLeI: applyFormat("($1 <= $2)", "($1 <= $2)")
|
||||||
of mLtI: applyFormat("($1 < $2)", "($1 < $2)")
|
of mLtI: applyFormat("($1 < $2)", "($1 < $2)")
|
||||||
of mEqF64: applyFormat("($1 == $2)", "($1 == $2)")
|
of mEqF64: applyFormat("($1 == $2)", "($1 == $2)")
|
||||||
of mLeF64: applyFormat("($1 <= $2)", "($1 <= $2)")
|
of mLeF64: applyFormat("($1 <= $2)", "($1 <= $2)")
|
||||||
of mLtF64: applyFormat("($1 < $2)", "($1 < $2)")
|
of mLtF64: applyFormat("($1 < $2)", "($1 < $2)")
|
||||||
of mleU: applyFormat("($1 <= $2)", "($1 <= $2)")
|
of mLeU: applyFormat("($1 <= $2)", "($1 <= $2)")
|
||||||
of mltU: applyFormat("($1 < $2)", "($1 < $2)")
|
of mLtU: applyFormat("($1 < $2)", "($1 < $2)")
|
||||||
of mleU64: applyFormat("($1 <= $2)", "($1 <= $2)")
|
of mLeU64: applyFormat("($1 <= $2)", "($1 <= $2)")
|
||||||
of mltU64: applyFormat("($1 < $2)", "($1 < $2)")
|
of mLtU64: applyFormat("($1 < $2)", "($1 < $2)")
|
||||||
of mEqEnum: applyFormat("($1 == $2)", "($1 == $2)")
|
of mEqEnum: applyFormat("($1 == $2)", "($1 == $2)")
|
||||||
of mLeEnum: applyFormat("($1 <= $2)", "($1 <= $2)")
|
of mLeEnum: applyFormat("($1 <= $2)", "($1 <= $2)")
|
||||||
of mLtEnum: 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 tyInt, tyInt32: "Int32Array"
|
||||||
of tyInt16: "Int16Array"
|
of tyInt16: "Int16Array"
|
||||||
of tyInt8: "Int8Array"
|
of tyInt8: "Int8Array"
|
||||||
of tyUint, tyUint32: "Uint32Array"
|
of tyUInt, tyUInt32: "Uint32Array"
|
||||||
of tyUint16: "Uint16Array"
|
of tyUInt16: "Uint16Array"
|
||||||
of tyUint8: "Uint8Array"
|
of tyUInt8: "Uint8Array"
|
||||||
of tyFloat32: "Float32Array"
|
of tyFloat32: "Float32Array"
|
||||||
of tyFloat64, tyFloat: "Float64Array"
|
of tyFloat64, tyFloat: "Float64Array"
|
||||||
else: ""
|
else: ""
|
||||||
|
|
@ -2246,7 +2246,7 @@ proc genProc(oldProc: PProc, prc: PSym): Rope =
|
||||||
if prc.typ.sons[0] != nil and sfPure notin prc.flags:
|
if prc.typ.sons[0] != nil and sfPure notin prc.flags:
|
||||||
resultSym = prc.ast.sons[resultPos].sym
|
resultSym = prc.ast.sons[resultPos].sym
|
||||||
let mname = mangleName(p.module, resultSym)
|
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
|
resultSym.typ.kind in {tyVar, tyPtr, tyLent, tyRef, tyOwned} and
|
||||||
mapType(p, resultSym.typ) == etyBaseIndex:
|
mapType(p, resultSym.typ) == etyBaseIndex:
|
||||||
resultAsgn = p.indentLine(("var $# = null;$n") % [mname])
|
resultAsgn = p.indentLine(("var $# = null;$n") % [mname])
|
||||||
|
|
@ -2391,7 +2391,7 @@ proc gen(p: PProc, n: PNode, r: var TCompRes) =
|
||||||
of nkFloatLit..nkFloat64Lit:
|
of nkFloatLit..nkFloat64Lit:
|
||||||
let f = n.floatVal
|
let f = n.floatVal
|
||||||
case classify(f)
|
case classify(f)
|
||||||
of fcNaN:
|
of fcNan:
|
||||||
r.res = rope"NaN"
|
r.res = rope"NaN"
|
||||||
of fcNegZero:
|
of fcNegZero:
|
||||||
r.res = rope"-0.0"
|
r.res = rope"-0.0"
|
||||||
|
|
|
||||||
|
|
@ -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.
|
# 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
|
# This seems to be generally correct but since it's a bit risky it's only
|
||||||
# enabled for gcDestructors.
|
# 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
|
c.getEnvTypeForOwnerUp(dep, info) #getHiddenParam(dep).typ
|
||||||
else:
|
else:
|
||||||
c.getEnvTypeForOwner(dep, info)
|
c.getEnvTypeForOwner(dep, info)
|
||||||
|
|
@ -535,7 +535,7 @@ proc setupEnvVar(owner: PSym; d: DetectionPass;
|
||||||
c: var LiftingPass; info: TLineInfo): PNode =
|
c: var LiftingPass; info: TLineInfo): PNode =
|
||||||
if owner.isIterator:
|
if owner.isIterator:
|
||||||
return getHiddenParam(d.graph, owner).newSymNode
|
return getHiddenParam(d.graph, owner).newSymNode
|
||||||
result = c.envvars.getOrDefault(owner.id)
|
result = c.envVars.getOrDefault(owner.id)
|
||||||
if result.isNil:
|
if result.isNil:
|
||||||
let envVarType = d.ownerToType.getOrDefault(owner.id)
|
let envVarType = d.ownerToType.getOrDefault(owner.id)
|
||||||
if envVarType.isNil:
|
if envVarType.isNil:
|
||||||
|
|
@ -710,7 +710,7 @@ proc liftCapturedVars(n: PNode; owner: PSym; d: DetectionPass;
|
||||||
c.inContainer = 0
|
c.inContainer = 0
|
||||||
var body = transformBody(d.graph, s)
|
var body = transformBody(d.graph, s)
|
||||||
body = liftCapturedVars(body, s, d, c)
|
body = liftCapturedVars(body, s, d, c)
|
||||||
if c.envvars.getOrDefault(s.id).isNil:
|
if c.envVars.getOrDefault(s.id).isNil:
|
||||||
s.transformedBody = body
|
s.transformedBody = body
|
||||||
else:
|
else:
|
||||||
s.transformedBody = newTree(nkStmtList, rawClosureCreation(s, d, c, n.info), body)
|
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)
|
var c = initLiftingPass(fn)
|
||||||
result = liftCapturedVars(body, fn, d, c)
|
result = liftCapturedVars(body, fn, d, c)
|
||||||
# echo renderTree(result, {renderIds})
|
# 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)
|
result = newTree(nkStmtList, rawClosureCreation(fn, d, c, body.info), result)
|
||||||
finishClosureCreation(fn, d, c, body.info, result)
|
finishClosureCreation(fn, d, c, body.info, result)
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -219,7 +219,7 @@ proc fillToken(L: var TToken) =
|
||||||
proc openLexer*(lex: var TLexer, fileIdx: FileIndex, inputstream: PLLStream;
|
proc openLexer*(lex: var TLexer, fileIdx: FileIndex, inputstream: PLLStream;
|
||||||
cache: IdentCache; config: ConfigRef) =
|
cache: IdentCache; config: ConfigRef) =
|
||||||
openBaseLexer(lex, inputstream)
|
openBaseLexer(lex, inputstream)
|
||||||
lex.fileIdx = fileidx
|
lex.fileIdx = fileIdx
|
||||||
lex.indentAhead = -1
|
lex.indentAhead = -1
|
||||||
lex.currLineIndent = 0
|
lex.currLineIndent = 0
|
||||||
inc(lex.lineNumber, inputstream.lineOffset)
|
inc(lex.lineNumber, inputstream.lineOffset)
|
||||||
|
|
@ -565,7 +565,7 @@ proc getNumber(L: var TLexer, result: var TToken) =
|
||||||
case result.tokType
|
case result.tokType
|
||||||
of floatTypes:
|
of floatTypes:
|
||||||
result.fNumber = parseFloat(result.literal)
|
result.fNumber = parseFloat(result.literal)
|
||||||
of tkUint64Lit:
|
of tkUInt64Lit:
|
||||||
var iNumber: uint64
|
var iNumber: uint64
|
||||||
var len: int
|
var len: int
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -193,7 +193,7 @@ type
|
||||||
# used for better error messages and
|
# used for better error messages and
|
||||||
# embedding the original source in the
|
# embedding the original source in the
|
||||||
# generated code
|
# 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
|
# and parsed; usually "" but is used
|
||||||
# for 'nimsuggest'
|
# for 'nimsuggest'
|
||||||
hash*: string # the checksum of the file
|
hash*: string # the checksum of the file
|
||||||
|
|
@ -229,12 +229,12 @@ proc raiseRecoverableError*(msg: string) {.noinline.} =
|
||||||
raise newException(ERecoverableError, msg)
|
raise newException(ERecoverableError, msg)
|
||||||
|
|
||||||
const
|
const
|
||||||
InvalidFileIDX* = FileIndex(-1)
|
InvalidFileIdx* = FileIndex(-1)
|
||||||
|
|
||||||
proc unknownLineInfo*(): TLineInfo =
|
proc unknownLineInfo*(): TLineInfo =
|
||||||
result.line = uint16(0)
|
result.line = uint16(0)
|
||||||
result.col = int16(-1)
|
result.col = int16(-1)
|
||||||
result.fileIndex = InvalidFileIDX
|
result.fileIndex = InvalidFileIdx
|
||||||
|
|
||||||
type
|
type
|
||||||
Severity* {.pure.} = enum ## VS Code only supports these three
|
Severity* {.pure.} = enum ## VS Code only supports these three
|
||||||
|
|
|
||||||
|
|
@ -83,19 +83,13 @@ proc checkStyle(conf: ConfigRef; cache: IdentCache; info: TLineInfo, s: string,
|
||||||
if s != beau:
|
if s != beau:
|
||||||
lintReport(conf, info, beau, s)
|
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) =
|
proc nep1CheckDefImpl(conf: ConfigRef; info: TLineInfo; s: PSym; k: TSymKind) =
|
||||||
# operators stay as they are:
|
# operators stay as they are:
|
||||||
if k in {skResult, skTemp} or s.name.s[0] notin Letters: return
|
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 k in {skType, skGenericParam} and sfAnon in s.flags: return
|
||||||
if s.typ != nil and s.typ.kind == tyTypeDesc: return
|
if s.typ != nil and s.typ.kind == tyTypeDesc: return
|
||||||
if {sfImportc, sfExportc} * s.flags != {}: return
|
if {sfImportc, sfExportc} * s.flags != {}: return
|
||||||
|
if optStyleCheck notin s.options: return
|
||||||
let beau = beautifyName(s.name.s, k)
|
let beau = beautifyName(s.name.s, k)
|
||||||
if s.name.s != beau:
|
if s.name.s != beau:
|
||||||
lintReport(conf, info, beau, s.name.s)
|
lintReport(conf, info, beau, s.name.s)
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,7 @@ import ast, intsets, tables, options, lineinfos, hashes, idents,
|
||||||
incremental, btrees, md5
|
incremental, btrees, md5
|
||||||
|
|
||||||
type
|
type
|
||||||
SigHash* = distinct Md5Digest
|
SigHash* = distinct MD5Digest
|
||||||
|
|
||||||
ModuleGraph* = ref object
|
ModuleGraph* = ref object
|
||||||
modules*: seq[PSym] ## indexed by int32 fileIdx
|
modules*: seq[PSym] ## indexed by int32 fileIdx
|
||||||
|
|
|
||||||
|
|
@ -162,6 +162,6 @@ proc checkModuleName*(conf: ConfigRef; n: PNode; doLocalError=true): FileIndex =
|
||||||
if doLocalError:
|
if doLocalError:
|
||||||
let m = if modulename.len > 0: modulename else: $n
|
let m = if modulename.len > 0: modulename else: $n
|
||||||
localError(conf, n.info, "cannot open file: " & m)
|
localError(conf, n.info, "cannot open file: " & m)
|
||||||
result = InvalidFileIDX
|
result = InvalidFileIdx
|
||||||
else:
|
else:
|
||||||
result = fileInfoIdx(conf, fullPath)
|
result = fileInfoIdx(conf, fullPath)
|
||||||
|
|
|
||||||
|
|
@ -133,12 +133,12 @@ proc wantMainModule*(conf: ConfigRef) =
|
||||||
"command expects a filename")
|
"command expects a filename")
|
||||||
conf.projectMainIdx = fileInfoIdx(conf, addFileExt(conf.projectFull, NimExt))
|
conf.projectMainIdx = fileInfoIdx(conf, addFileExt(conf.projectFull, NimExt))
|
||||||
|
|
||||||
proc compileProject*(graph: ModuleGraph; projectFileIdx = InvalidFileIDX) =
|
proc compileProject*(graph: ModuleGraph; projectFileIdx = InvalidFileIdx) =
|
||||||
connectCallbacks(graph)
|
connectCallbacks(graph)
|
||||||
let conf = graph.config
|
let conf = graph.config
|
||||||
wantMainModule(conf)
|
wantMainModule(conf)
|
||||||
let systemFileIdx = fileInfoIdx(conf, conf.libpath / RelativeFile"system.nim")
|
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
|
graph.importStack.add projectFile
|
||||||
if projectFile == systemFileIdx:
|
if projectFile == systemFileIdx:
|
||||||
discard graph.compileModule(projectFile, {sfMainModule, sfSystemModule})
|
discard graph.compileModule(projectFile, {sfMainModule, sfSystemModule})
|
||||||
|
|
|
||||||
|
|
@ -108,7 +108,7 @@ proc newLineInfo*(conf: ConfigRef; filename: AbsoluteFile, line, col: int): TLin
|
||||||
result = newLineInfo(fileInfoIdx(conf, filename), line, col)
|
result = newLineInfo(fileInfoIdx(conf, filename), line, col)
|
||||||
|
|
||||||
|
|
||||||
proc concat(strings: openarray[string]): string =
|
proc concat(strings: openArray[string]): string =
|
||||||
var totalLen = 0
|
var totalLen = 0
|
||||||
for s in strings: totalLen += s.len
|
for s in strings: totalLen += s.len
|
||||||
result = newStringOfCap totalLen
|
result = newStringOfCap totalLen
|
||||||
|
|
@ -542,7 +542,7 @@ proc localError*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
|
||||||
proc localError*(conf: ConfigRef; info: TLineInfo, arg: string) =
|
proc localError*(conf: ConfigRef; info: TLineInfo, arg: string) =
|
||||||
liMessage(conf, info, errGenerated, arg, doNothing)
|
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)
|
localError(conf, info, format % params)
|
||||||
|
|
||||||
proc message*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
|
proc message*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,7 @@ proc processCmdLine(pass: TCmdLinePass, cmd: string; config: ConfigRef) =
|
||||||
parseopt.next(p)
|
parseopt.next(p)
|
||||||
case p.kind
|
case p.kind
|
||||||
of cmdEnd: break
|
of cmdEnd: break
|
||||||
of cmdLongoption, cmdShortOption:
|
of cmdLongOption, cmdShortOption:
|
||||||
if p.key == " ":
|
if p.key == " ":
|
||||||
p.key = "-"
|
p.key = "-"
|
||||||
if processArgument(pass, p, argsCount, config): break
|
if processArgument(pass, p, argsCount, config): break
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,7 @@ type # please make sure we have under 32 options
|
||||||
TOption* = enum # **keep binary compatible**
|
TOption* = enum # **keep binary compatible**
|
||||||
optNone, optObjCheck, optFieldCheck, optRangeCheck, optBoundsCheck,
|
optNone, optObjCheck, optFieldCheck, optRangeCheck, optBoundsCheck,
|
||||||
optOverflowCheck, optNilCheck,
|
optOverflowCheck, optNilCheck,
|
||||||
optNaNCheck, optInfCheck, optMoveCheck,
|
optNaNCheck, optInfCheck, optStyleCheck,
|
||||||
optAssert, optLineDir, optWarns, optHints,
|
optAssert, optLineDir, optWarns, optHints,
|
||||||
optOptimizeSpeed, optOptimizeSize, optStackTrace, # stack tracing support
|
optOptimizeSpeed, optOptimizeSize, optStackTrace, # stack tracing support
|
||||||
optLineTrace, # line tracing support (includes stack tracing)
|
optLineTrace, # line tracing support (includes stack tracing)
|
||||||
|
|
@ -149,7 +149,7 @@ type
|
||||||
Cfile* = object
|
Cfile* = object
|
||||||
nimname*: string
|
nimname*: string
|
||||||
cname*, obj*: AbsoluteFile
|
cname*, obj*: AbsoluteFile
|
||||||
flags*: set[CFileFlag]
|
flags*: set[CfileFlag]
|
||||||
CfileList* = seq[Cfile]
|
CfileList* = seq[Cfile]
|
||||||
|
|
||||||
Suggest* = ref object
|
Suggest* = ref object
|
||||||
|
|
@ -246,7 +246,7 @@ type
|
||||||
compileOptionsCmd*: seq[string]
|
compileOptionsCmd*: seq[string]
|
||||||
linkOptions*: string # (*)
|
linkOptions*: string # (*)
|
||||||
compileOptions*: string # (*)
|
compileOptions*: string # (*)
|
||||||
ccompilerpath*: string
|
cCompilerPath*: string
|
||||||
toCompile*: CfileList # (*)
|
toCompile*: CfileList # (*)
|
||||||
suggestionResultHook*: proc (result: Suggest) {.closure.}
|
suggestionResultHook*: proc (result: Suggest) {.closure.}
|
||||||
suggestVersion*: int
|
suggestVersion*: int
|
||||||
|
|
@ -270,12 +270,12 @@ const oldExperimentalFeatures* = {implicitDeref, dotOperators, callOperator, par
|
||||||
const
|
const
|
||||||
ChecksOptions* = {optObjCheck, optFieldCheck, optRangeCheck, optNilCheck,
|
ChecksOptions* = {optObjCheck, optFieldCheck, optRangeCheck, optNilCheck,
|
||||||
optOverflowCheck, optBoundsCheck, optAssert, optNaNCheck, optInfCheck,
|
optOverflowCheck, optBoundsCheck, optAssert, optNaNCheck, optInfCheck,
|
||||||
optMoveCheck}
|
optStyleCheck}
|
||||||
|
|
||||||
DefaultOptions* = {optObjCheck, optFieldCheck, optRangeCheck,
|
DefaultOptions* = {optObjCheck, optFieldCheck, optRangeCheck,
|
||||||
optBoundsCheck, optOverflowCheck, optAssert, optWarns,
|
optBoundsCheck, optOverflowCheck, optAssert, optWarns,
|
||||||
optHints, optStackTrace, optLineTrace,
|
optHints, optStackTrace, optLineTrace,
|
||||||
optTrMacros, optNilCheck, optMoveCheck}
|
optTrMacros, optNilCheck, optStyleCheck}
|
||||||
DefaultGlobalOptions* = {optThreadAnalysis,
|
DefaultGlobalOptions* = {optThreadAnalysis,
|
||||||
optExcessiveStackTrace, optListFullPaths}
|
optExcessiveStackTrace, optListFullPaths}
|
||||||
|
|
||||||
|
|
@ -498,7 +498,7 @@ proc setDefaultLibpath*(conf: ConfigRef) =
|
||||||
# Find out if $nim/../../lib/system.nim exists.
|
# Find out if $nim/../../lib/system.nim exists.
|
||||||
let parentNimLibPath = realNimPath.parentDir.parentDir / "lib"
|
let parentNimLibPath = realNimPath.parentDir.parentDir / "lib"
|
||||||
if not fileExists(conf.libpath.string / "system.nim") and
|
if not fileExists(conf.libpath.string / "system.nim") and
|
||||||
fileExists(parentNimlibPath / "system.nim"):
|
fileExists(parentNimLibPath / "system.nim"):
|
||||||
conf.libpath = AbsoluteDir parentNimLibPath
|
conf.libpath = AbsoluteDir parentNimLibPath
|
||||||
|
|
||||||
proc canonicalizePath*(conf: ConfigRef; path: AbsoluteFile): AbsoluteFile =
|
proc canonicalizePath*(conf: ConfigRef; path: AbsoluteFile): AbsoluteFile =
|
||||||
|
|
@ -590,7 +590,7 @@ proc rawFindFile2(conf: ConfigRef; f: RelativeFile): AbsoluteFile =
|
||||||
result = it / f
|
result = it / f
|
||||||
if fileExists(result):
|
if fileExists(result):
|
||||||
# bring to front
|
# bring to front
|
||||||
for j in countDown(i,1):
|
for j in countdown(i,1):
|
||||||
swap(conf.lazyPaths[j], conf.lazyPaths[j-1])
|
swap(conf.lazyPaths[j], conf.lazyPaths[j-1])
|
||||||
|
|
||||||
return canonicalizePath(conf, result)
|
return canonicalizePath(conf, result)
|
||||||
|
|
|
||||||
|
|
@ -346,7 +346,7 @@ proc parseSymbol(p: var TParser, mode = smNormal): PNode =
|
||||||
parMessage(p, errIdentifierExpected, p.tok)
|
parMessage(p, errIdentifierExpected, p.tok)
|
||||||
break
|
break
|
||||||
of tkOpr, tkDot, tkDotDot, tkEquals, tkParLe..tkParDotRi:
|
of tkOpr, tkDot, tkDotDot, tkEquals, tkParLe..tkParDotRi:
|
||||||
let lineinfo = parLineinfo(p)
|
let lineinfo = parLineInfo(p)
|
||||||
var accm = ""
|
var accm = ""
|
||||||
while p.tok.tokType in {tkOpr, tkDot, tkDotDot, tkEquals,
|
while p.tok.tokType in {tkOpr, tkDot, tkDotDot, tkEquals,
|
||||||
tkParLe..tkParDotRi}:
|
tkParLe..tkParDotRi}:
|
||||||
|
|
@ -981,7 +981,7 @@ proc parseIdentColonEquals(p: var TParser, flags: TDeclaredIdentFlags): PNode =
|
||||||
while true:
|
while true:
|
||||||
case p.tok.tokType
|
case p.tok.tokType
|
||||||
of tkSymbol, tkAccent:
|
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)
|
else: a = parseSymbol(p)
|
||||||
if a.kind == nkEmpty: return
|
if a.kind == nkEmpty: return
|
||||||
else: break
|
else: break
|
||||||
|
|
@ -1090,7 +1090,7 @@ proc parseParamList(p: var TParser, retColon = true): PNode =
|
||||||
getTok(p)
|
getTok(p)
|
||||||
optInd(p, result)
|
optInd(p, result)
|
||||||
result.sons[0] = parseTypeDesc(p)
|
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:
|
# Mark as "not there" in order to mark for deprecation in the semantic pass:
|
||||||
result = p.emptyNode
|
result = p.emptyNode
|
||||||
when defined(nimpretty):
|
when defined(nimpretty):
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,6 @@ proc verboseProcess(context: PPassContext, n: PNode): PNode =
|
||||||
# system.nim deactivates all hints, for verbosity:3 we want the processing
|
# system.nim deactivates all hints, for verbosity:3 we want the processing
|
||||||
# messages nonetheless, so we activate them again unconditionally:
|
# messages nonetheless, so we activate them again unconditionally:
|
||||||
incl(v.config.notes, hintProcessing)
|
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)
|
const verbosePass* = makePass(open = verboseOpen, process = verboseProcess)
|
||||||
|
|
|
||||||
|
|
@ -90,7 +90,7 @@ proc processTopLevelStmt(graph: ModuleGraph, n: PNode, a: var TPassContextArray)
|
||||||
proc resolveMod(conf: ConfigRef; module, relativeTo: string): FileIndex =
|
proc resolveMod(conf: ConfigRef; module, relativeTo: string): FileIndex =
|
||||||
let fullPath = findModule(conf, module, relativeTo)
|
let fullPath = findModule(conf, module, relativeTo)
|
||||||
if fullPath.isEmpty:
|
if fullPath.isEmpty:
|
||||||
result = InvalidFileIDX
|
result = InvalidFileIdx
|
||||||
else:
|
else:
|
||||||
result = fileInfoIdx(conf, fullPath)
|
result = fileInfoIdx(conf, fullPath)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ type
|
||||||
# conditionals to condsyms (end of module).
|
# conditionals to condsyms (end of module).
|
||||||
osNone, osDos, osWindows, osOs2, osLinux, osMorphos, osSkyos, osSolaris,
|
osNone, osDos, osWindows, osOs2, osLinux, osMorphos, osSkyos, osSolaris,
|
||||||
osIrix, osNetbsd, osFreebsd, osOpenbsd, osDragonfly, osAix, osPalmos, osQnx,
|
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
|
osGenode, osJS, osNimVM, osStandalone, osNintendoSwitch
|
||||||
|
|
||||||
type
|
type
|
||||||
|
|
|
||||||
|
|
@ -20,38 +20,38 @@ const
|
||||||
|
|
||||||
const
|
const
|
||||||
procPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl,
|
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,
|
wCompilerProc, wNonReloadable, wCore, wProcVar, wDeprecated, wVarargs, wCompileTime, wMerge,
|
||||||
wBorrow, wExtern, wImportCompilerProc, wThread, wImportCpp, wImportObjC,
|
wBorrow, wExtern, wImportCompilerProc, wThread, wImportCpp, wImportObjC,
|
||||||
wAsmNoStackFrame, wError, wDiscardable, wNoInit, wCodegenDecl,
|
wAsmNoStackFrame, wError, wDiscardable, wNoInit, wCodegenDecl,
|
||||||
wGensym, wInject, wRaises, wTags, wLocks, wDelegator, wGcSafe,
|
wGensym, wInject, wRaises, wTags, wLocks, wDelegator, wGcSafe,
|
||||||
wConstructor, wExportNims, wUsed, wLiftLocals, wStacktrace, wLinetrace, wNoDestroy}
|
wConstructor, wExportNims, wUsed, wLiftLocals, wStackTrace, wLineTrace, wNoDestroy}
|
||||||
converterPragmas* = procPragmas - {wNoDestroy}
|
converterPragmas* = procPragmas - {wNoDestroy}
|
||||||
methodPragmas* = procPragmas+{wBase}-{wImportCpp, wNoDestroy}
|
methodPragmas* = procPragmas+{wBase}-{wImportCpp, wNoDestroy}
|
||||||
templatePragmas* = {wDeprecated, wError, wGensym, wInject, wDirty,
|
templatePragmas* = {wDeprecated, wError, wGensym, wInject, wDirty,
|
||||||
wDelegator, wExportNims, wUsed, wPragma}
|
wDelegator, wExportNims, wUsed, wPragma}
|
||||||
macroPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc,
|
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,
|
wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wDelegator,
|
||||||
wExportNims, wUsed}
|
wExportNims, wUsed}
|
||||||
iteratorPragmas* = {FirstCallConv..LastCallConv, wNosideeffect, wSideeffect,
|
iteratorPragmas* = {FirstCallConv..LastCallConv, wNoSideEffect, wSideEffect,
|
||||||
wImportc, wExportc, wNodecl, wMagic, wDeprecated, wBorrow, wExtern,
|
wImportc, wExportc, wNodecl, wMagic, wDeprecated, wBorrow, wExtern,
|
||||||
wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wRaises,
|
wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wRaises,
|
||||||
wTags, wLocks, wGcSafe, wExportNims, wUsed}
|
wTags, wLocks, wGcSafe, wExportNims, wUsed}
|
||||||
exprPragmas* = {wLine, wLocks, wNoRewrite, wGcSafe, wNosideeffect}
|
exprPragmas* = {wLine, wLocks, wNoRewrite, wGcSafe, wNoSideEffect}
|
||||||
stmtPragmas* = {wChecks, wObjChecks, wFieldChecks, wRangechecks,
|
stmtPragmas* = {wChecks, wObjChecks, wFieldChecks, wRangeChecks,
|
||||||
wBoundchecks, wOverflowchecks, wNilchecks, wMovechecks, wAssertions,
|
wBoundChecks, wOverflowChecks, wNilChecks, wStyleChecks, wAssertions,
|
||||||
wWarnings, wHints,
|
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,
|
wFatal, wDefine, wUndef, wCompile, wLink, wLinksys, wPure, wPush, wPop,
|
||||||
wBreakpoint, wWatchPoint, wPassl, wPassc,
|
wBreakpoint, wWatchPoint, wPassl, wPassc,
|
||||||
wDeadCodeElimUnused, # deprecated, always on
|
wDeadCodeElimUnused, # deprecated, always on
|
||||||
wDeprecated,
|
wDeprecated,
|
||||||
wFloatchecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll,
|
wFloatChecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll,
|
||||||
wLinearScanEnd, wPatterns, wTrMacros, wEffects, wNoForward, wReorder, wComputedGoto,
|
wLinearScanEnd, wPatterns, wTrMacros, wEffects, wNoForward, wReorder, wComputedGoto,
|
||||||
wInjectStmt, wDeprecated, wExperimental, wThis}
|
wInjectStmt, wDeprecated, wExperimental, wThis}
|
||||||
lambdaPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl,
|
lambdaPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl,
|
||||||
wNosideeffect, wSideeffect, wNoreturn, wDynlib, wHeader,
|
wNoSideEffect, wSideEffect, wNoreturn, wDynlib, wHeader,
|
||||||
wDeprecated, wExtern, wThread, wImportCpp, wImportObjC, wAsmNoStackFrame,
|
wDeprecated, wExtern, wThread, wImportCpp, wImportObjC, wAsmNoStackFrame,
|
||||||
wRaises, wLocks, wTags, wGcSafe, wCodegenDecl}
|
wRaises, wLocks, wTags, wGcSafe, wCodegenDecl}
|
||||||
typePragmas* = {wImportc, wExportc, wDeprecated, wMagic, wAcyclic, wNodecl,
|
typePragmas* = {wImportc, wExportc, wDeprecated, wMagic, wAcyclic, wNodecl,
|
||||||
|
|
@ -69,7 +69,7 @@ const
|
||||||
wExtern, wImportCpp, wImportObjC, wError, wGensym, wInject, wExportNims,
|
wExtern, wImportCpp, wImportObjC, wError, wGensym, wInject, wExportNims,
|
||||||
wIntDefine, wStrDefine, wBoolDefine, wUsed, wCompilerProc, wCore}
|
wIntDefine, wStrDefine, wBoolDefine, wUsed, wCompilerProc, wCore}
|
||||||
letPragmas* = varPragmas
|
letPragmas* = varPragmas
|
||||||
procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNosideeffect,
|
procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNoSideEffect,
|
||||||
wThread, wRaises, wLocks, wTags, wGcSafe}
|
wThread, wRaises, wLocks, wTags, wGcSafe}
|
||||||
forVarPragmas* = {wInject, wGensym}
|
forVarPragmas* = {wInject, wGensym}
|
||||||
allRoutinePragmas* = methodPragmas + iteratorPragmas + lambdaPragmas
|
allRoutinePragmas* = methodPragmas + iteratorPragmas + lambdaPragmas
|
||||||
|
|
@ -161,7 +161,7 @@ proc processImportObjC(c: PContext; s: PSym, extname: string, info: TLineInfo) =
|
||||||
incl(s.flags, sfNamedParamCall)
|
incl(s.flags, sfNamedParamCall)
|
||||||
excl(s.flags, sfForward)
|
excl(s.flags, sfForward)
|
||||||
let m = s.getModule()
|
let m = s.getModule()
|
||||||
incl(m.flags, sfCompileToObjC)
|
incl(m.flags, sfCompileToObjc)
|
||||||
|
|
||||||
proc newEmptyStrNode(c: PContext; n: PNode): PNode {.noinline.} =
|
proc newEmptyStrNode(c: PContext; n: PNode): PNode {.noinline.} =
|
||||||
result = newNodeIT(nkStrLit, n.info, getSysType(c.graph, n.info, tyString))
|
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 wChecks: ChecksOptions
|
||||||
of wObjChecks: {optObjCheck}
|
of wObjChecks: {optObjCheck}
|
||||||
of wFieldChecks: {optFieldCheck}
|
of wFieldChecks: {optFieldCheck}
|
||||||
of wRangechecks: {optRangeCheck}
|
of wRangeChecks: {optRangeCheck}
|
||||||
of wBoundchecks: {optBoundsCheck}
|
of wBoundChecks: {optBoundsCheck}
|
||||||
of wOverflowchecks: {optOverflowCheck}
|
of wOverflowChecks: {optOverflowCheck}
|
||||||
of wNilchecks: {optNilCheck}
|
of wNilChecks: {optNilCheck}
|
||||||
of wFloatchecks: {optNaNCheck, optInfCheck}
|
of wFloatChecks: {optNaNCheck, optInfCheck}
|
||||||
of wNanChecks: {optNaNCheck}
|
of wNanChecks: {optNaNCheck}
|
||||||
of wInfChecks: {optInfCheck}
|
of wInfChecks: {optInfCheck}
|
||||||
of wMovechecks: {optMoveCheck}
|
of wStyleChecks: {optStyleCheck}
|
||||||
of wAssertions: {optAssert}
|
of wAssertions: {optAssert}
|
||||||
of wWarnings: {optWarns}
|
of wWarnings: {optWarns}
|
||||||
of wHints: {optHints}
|
of wHints: {optHints}
|
||||||
of wLinedir: {optLineDir}
|
of wLineDir: {optLineDir}
|
||||||
of wStacktrace: {optStackTrace}
|
of wStackTrace: {optStackTrace}
|
||||||
of wLinetrace: {optLineTrace}
|
of wLineTrace: {optLineTrace}
|
||||||
of wDebugger: {optEndb}
|
of wDebugger: {optEndb}
|
||||||
of wProfiler: {optProfiler, optMemTracker}
|
of wProfiler: {optProfiler, optMemTracker}
|
||||||
of wMemTracker: {optMemTracker}
|
of wMemTracker: {optMemTracker}
|
||||||
|
|
@ -491,7 +491,7 @@ proc processCompile(c: PContext, n: PNode) =
|
||||||
let dest = getStrLit(c, it, 1)
|
let dest = getStrLit(c, it, 1)
|
||||||
var found = parentDir(toFullPath(c.config, n.info)) / s
|
var found = parentDir(toFullPath(c.config, n.info)) / s
|
||||||
for f in os.walkFiles(found):
|
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)
|
docompile(c, it, AbsoluteFile f, obj)
|
||||||
else:
|
else:
|
||||||
let s = expectStrLit(c, n)
|
let s = expectStrLit(c, n)
|
||||||
|
|
@ -501,7 +501,7 @@ proc processCompile(c: PContext, n: PNode) =
|
||||||
else:
|
else:
|
||||||
found = findFile(c.config, s)
|
found = findFile(c.config, s)
|
||||||
if found.isEmpty: found = AbsoluteFile 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)
|
docompile(c, it, found, obj)
|
||||||
|
|
||||||
proc processLink(c: PContext, n: PNode) =
|
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)
|
incl(sym.loc.flags, lfNoDecl)
|
||||||
# implies nodecl, because otherwise header would not make sense
|
# implies nodecl, because otherwise header would not make sense
|
||||||
if sym.loc.r == nil: sym.loc.r = rope(sym.name.s)
|
if sym.loc.r == nil: sym.loc.r = rope(sym.name.s)
|
||||||
of wNosideeffect:
|
of wNoSideEffect:
|
||||||
noVal(c, it)
|
noVal(c, it)
|
||||||
if sym != nil:
|
if sym != nil:
|
||||||
incl(sym.flags, sfNoSideEffect)
|
incl(sym.flags, sfNoSideEffect)
|
||||||
if sym.typ != nil: incl(sym.typ.flags, tfNoSideEffect)
|
if sym.typ != nil: incl(sym.typ.flags, tfNoSideEffect)
|
||||||
of wSideeffect:
|
of wSideEffect:
|
||||||
noVal(c, it)
|
noVal(c, it)
|
||||||
incl(sym.flags, sfSideEffect)
|
incl(sym.flags, sfSideEffect)
|
||||||
of wNoreturn:
|
of wNoreturn:
|
||||||
|
|
@ -1011,12 +1011,12 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: var int,
|
||||||
noVal(c, it)
|
noVal(c, it)
|
||||||
if sym != nil: incl(sym.flags, sfNoInit)
|
if sym != nil: incl(sym.flags, sfNoInit)
|
||||||
of wCodegenDecl: processCodegenDecl(c, it, sym)
|
of wCodegenDecl: processCodegenDecl(c, it, sym)
|
||||||
of wChecks, wObjChecks, wFieldChecks, wRangechecks, wBoundchecks,
|
of wChecks, wObjChecks, wFieldChecks, wRangeChecks, wBoundChecks,
|
||||||
wOverflowchecks, wNilchecks, wAssertions, wWarnings, wHints,
|
wOverflowChecks, wNilChecks, wAssertions, wWarnings, wHints,
|
||||||
wLinedir, wOptimization, wMovechecks, wCallconv, wDebugger, wProfiler,
|
wLineDir, wOptimization, wStyleChecks, wCallconv, wDebugger, wProfiler,
|
||||||
wFloatchecks, wNanChecks, wInfChecks, wPatterns, wTrMacros:
|
wFloatChecks, wNanChecks, wInfChecks, wPatterns, wTrMacros:
|
||||||
processOption(c, it, c.config.options)
|
processOption(c, it, c.config.options)
|
||||||
of wStacktrace, wLinetrace:
|
of wStackTrace, wLineTrace:
|
||||||
if sym.kind in {skProc, skMethod, skConverter}:
|
if sym.kind in {skProc, skMethod, skConverter}:
|
||||||
processOption(c, it, sym.options)
|
processOption(c, it, sym.options)
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -151,7 +151,7 @@ proc expandIncludes(graph: ModuleGraph, module: PSym, n: PNode,
|
||||||
if a.kind == nkIncludeStmt:
|
if a.kind == nkIncludeStmt:
|
||||||
for i in 0..<a.len:
|
for i in 0..<a.len:
|
||||||
var f = checkModuleName(graph.config, a.sons[i])
|
var f = checkModuleName(graph.config, a.sons[i])
|
||||||
if f != InvalidFileIDX:
|
if f != InvalidFileIdx:
|
||||||
if containsOrIncl(includedFiles, f.int):
|
if containsOrIncl(includedFiles, f.int):
|
||||||
localError(graph.config, a.info, "recursive dependency: '$1'" %
|
localError(graph.config, a.info, "recursive dependency: '$1'" %
|
||||||
toMsgFilename(graph.config, f))
|
toMsgFilename(graph.config, f))
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,7 @@ proc c_snprintf(s: cstring; n:uint; frmt: cstring): cint {.importc: "snprintf",
|
||||||
|
|
||||||
proc toStrMaxPrecision*(f: BiggestFloat, literalPostfix = ""): string =
|
proc toStrMaxPrecision*(f: BiggestFloat, literalPostfix = ""): string =
|
||||||
case classify(f)
|
case classify(f)
|
||||||
of fcNaN:
|
of fcNan:
|
||||||
result = "NAN"
|
result = "NAN"
|
||||||
of fcNegZero:
|
of fcNegZero:
|
||||||
result = "-0.0" & literalPostfix
|
result = "-0.0" & literalPostfix
|
||||||
|
|
|
||||||
|
|
@ -152,7 +152,7 @@ proc checkConvertible(c: PContext, targetTyp: PType, src: PNode): TConvStatus =
|
||||||
src.intVal notin firstOrd(c.config, targetTyp)..lastOrd(c.config, targetTyp):
|
src.intVal notin firstOrd(c.config, targetTyp)..lastOrd(c.config, targetTyp):
|
||||||
result = convNotInRange
|
result = convNotInRange
|
||||||
elif src.kind in nkFloatLit..nkFloat64Lit and
|
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)):
|
src.floatVal.int64 notin firstOrd(c.config, targetTyp)..lastOrd(c.config, targetTyp)):
|
||||||
result = convNotInRange
|
result = convNotInRange
|
||||||
elif targetBaseTyp.kind in tyFloat..tyFloat64:
|
elif targetBaseTyp.kind in tyFloat..tyFloat64:
|
||||||
|
|
@ -160,7 +160,7 @@ proc checkConvertible(c: PContext, targetTyp: PType, src: PNode): TConvStatus =
|
||||||
not floatRangeCheck(src.floatVal, targetTyp):
|
not floatRangeCheck(src.floatVal, targetTyp):
|
||||||
result = convNotInRange
|
result = convNotInRange
|
||||||
elif src.kind in nkCharLit..nkUInt64Lit and
|
elif src.kind in nkCharLit..nkUInt64Lit and
|
||||||
not floatRangeCheck(src.intval.float, targetTyp):
|
not floatRangeCheck(src.intVal.float, targetTyp):
|
||||||
result = convNotInRange
|
result = convNotInRange
|
||||||
else:
|
else:
|
||||||
# we use d, s here to speed up that operation a bit:
|
# 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 =
|
template resultTypeIsInferrable(typ: PType): untyped =
|
||||||
typ.isMetaType and typ.kind != tyTypeDesc
|
typ.isMetaType and typ.kind != tyTypeDesc
|
||||||
|
|
||||||
proc goodLineInfo(arg: PNode): TLineinfo =
|
proc goodLineInfo(arg: PNode): TLineInfo =
|
||||||
if arg.kind == nkStmtListExpr and arg.len > 0:
|
if arg.kind == nkStmtListExpr and arg.len > 0:
|
||||||
goodLineInfo(arg[^1])
|
goodLineInfo(arg[^1])
|
||||||
else:
|
else:
|
||||||
|
|
@ -2108,7 +2108,7 @@ proc instantiateCreateFlowVarCall(c: PContext; t: PType;
|
||||||
# since it's an instantiation, we unmark it as a compilerproc. Otherwise
|
# since it's an instantiation, we unmark it as a compilerproc. Otherwise
|
||||||
# codegen would fail:
|
# codegen would fail:
|
||||||
if sfCompilerProc in result.flags:
|
if sfCompilerProc in result.flags:
|
||||||
result.flags = result.flags - {sfCompilerProc, sfExportC, sfImportC}
|
result.flags = result.flags - {sfCompilerProc, sfExportc, sfImportc}
|
||||||
result.loc.r = nil
|
result.loc.r = nil
|
||||||
|
|
||||||
proc setMs(n: PNode, s: PSym): PNode =
|
proc setMs(n: PNode, s: PSym): PNode =
|
||||||
|
|
|
||||||
|
|
@ -157,7 +157,7 @@ proc makeRange(typ: PType, first, last: BiggestInt; g: ModuleGraph): PType =
|
||||||
let lowerNode = newIntNode(nkIntLit, minA)
|
let lowerNode = newIntNode(nkIntLit, minA)
|
||||||
if typ.kind == tyInt and minA == maxA:
|
if typ.kind == tyInt and minA == maxA:
|
||||||
result = getIntLitType(g, lowerNode)
|
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:
|
# these are not ordinal types, so you get no subrange type for these:
|
||||||
result = typ
|
result = typ
|
||||||
else:
|
else:
|
||||||
|
|
@ -187,7 +187,7 @@ proc fitLiteral(c: ConfigRef, n: PNode): PNode =
|
||||||
result = n
|
result = n
|
||||||
|
|
||||||
let typ = n.typ.skipTypes(abstractRange)
|
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)
|
result.intVal = result.intVal and lastOrd(c, typ, fixedUnsigned=true)
|
||||||
|
|
||||||
proc evalOp(m: TMagic, n, a, b, c: PNode; g: ModuleGraph): PNode =
|
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?
|
# XXX range checks?
|
||||||
case dstTyp.kind
|
case dstTyp.kind
|
||||||
of tyInt..tyInt64, tyUint..tyUInt64:
|
of tyInt..tyInt64, tyUInt..tyUInt64:
|
||||||
case srcTyp.kind
|
case srcTyp.kind
|
||||||
of tyFloat..tyFloat64:
|
of tyFloat..tyFloat64:
|
||||||
result = newIntNodeT(int(getFloat(a)), n, g)
|
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
|
let toSigned = dstTyp.kind in tyInt..tyInt64
|
||||||
var val = a.getOrdValue
|
var val = a.getOrdValue
|
||||||
|
|
||||||
if dstTyp.kind in {tyInt, tyInt64, tyUint, tyUInt64}:
|
if dstTyp.kind in {tyInt, tyInt64, tyUInt, tyUInt64}:
|
||||||
# No narrowing needed
|
# No narrowing needed
|
||||||
discard
|
discard
|
||||||
elif dstTyp.kind in {tyInt..tyInt64}:
|
elif dstTyp.kind in {tyInt..tyInt64}:
|
||||||
|
|
|
||||||
|
|
@ -497,13 +497,13 @@ proc semGenericStmt(c: PContext, n: PNode,
|
||||||
|
|
||||||
proc semGenericStmt(c: PContext, n: PNode): PNode =
|
proc semGenericStmt(c: PContext, n: PNode): PNode =
|
||||||
var ctx: GenericCtx
|
var ctx: GenericCtx
|
||||||
ctx.toMixin = initIntset()
|
ctx.toMixin = initIntSet()
|
||||||
result = semGenericStmt(c, n, {}, ctx)
|
result = semGenericStmt(c, n, {}, ctx)
|
||||||
semIdeForTemplateOrGeneric(c, result, ctx.cursorInBody)
|
semIdeForTemplateOrGeneric(c, result, ctx.cursorInBody)
|
||||||
|
|
||||||
proc semConceptBody(c: PContext, n: PNode): PNode =
|
proc semConceptBody(c: PContext, n: PNode): PNode =
|
||||||
var ctx: GenericCtx
|
var ctx: GenericCtx
|
||||||
ctx.toMixin = initIntset()
|
ctx.toMixin = initIntSet()
|
||||||
result = semGenericStmt(c, n, {withinConcept}, ctx)
|
result = semGenericStmt(c, n, {withinConcept}, ctx)
|
||||||
semIdeForTemplateOrGeneric(c, result, ctx.cursorInBody)
|
semIdeForTemplateOrGeneric(c, result, ctx.cursorInBody)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -74,7 +74,7 @@ type
|
||||||
init: seq[int] # list of initialized variables
|
init: seq[int] # list of initialized variables
|
||||||
guards: TModel # nested guards
|
guards: TModel # nested guards
|
||||||
locked: seq[PNode] # locked locations
|
locked: seq[PNode] # locked locations
|
||||||
gcUnsafe, isRecursive, isToplevel, hasSideEffect, inEnforcedGcSafe: bool
|
gcUnsafe, isRecursive, isTopLevel, hasSideEffect, inEnforcedGcSafe: bool
|
||||||
inEnforcedNoSideEffects: bool
|
inEnforcedNoSideEffects: bool
|
||||||
maxLockLevel, currLockLevel: TLockLevel
|
maxLockLevel, currLockLevel: TLockLevel
|
||||||
config: ConfigRef
|
config: ConfigRef
|
||||||
|
|
@ -263,7 +263,7 @@ proc useVar(a: PEffects, n: PNode) =
|
||||||
# prevent superfluous warnings about the same variable:
|
# prevent superfluous warnings about the same variable:
|
||||||
a.init.add s.id
|
a.init.add s.id
|
||||||
if {sfGlobal, sfThread} * s.flags != {} and s.kind in {skVar, skLet} and
|
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 s.guard != nil: guardGlobal(a, n, s.guard)
|
||||||
if {sfGlobal, sfThread} * s.flags == {sfGlobal} and
|
if {sfGlobal, sfThread} * s.flags == {sfGlobal} and
|
||||||
(tfHasGCedMem in s.typ.flags or s.typ.isGCedMem):
|
(tfHasGCedMem in s.typ.flags or s.typ.isGCedMem):
|
||||||
|
|
@ -476,7 +476,7 @@ proc propagateEffects(tracked: PEffects, n: PNode, s: PSym) =
|
||||||
markSideEffect(tracked, s)
|
markSideEffect(tracked, s)
|
||||||
mergeLockLevels(tracked, n, s.getLockLevel)
|
mergeLockLevels(tracked, n, s.getLockLevel)
|
||||||
|
|
||||||
proc procVarcheck(n: PNode; conf: ConfigRef) =
|
proc procVarCheck(n: PNode; conf: ConfigRef) =
|
||||||
if n.kind in nkSymChoices:
|
if n.kind in nkSymChoices:
|
||||||
for x in n: procVarCheck(x, conf)
|
for x in n: procVarCheck(x, conf)
|
||||||
elif n.kind == nkSym and n.sym.magic != mNone and n.sym.kind in routineKinds:
|
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) =
|
proc notNilCheck(tracked: PEffects, n: PNode, paramType: PType) =
|
||||||
let n = n.skipConv
|
let n = n.skipConv
|
||||||
if paramType.isNil or paramType.kind != tyTypeDesc:
|
if paramType.isNil or paramType.kind != tyTypeDesc:
|
||||||
procVarcheck skipConvAndClosure(n), tracked.config
|
procVarCheck skipConvAndClosure(n), tracked.config
|
||||||
#elif n.kind in nkSymChoices:
|
#elif n.kind in nkSymChoices:
|
||||||
# echo "came here"
|
# echo "came here"
|
||||||
let paramType = paramType.skipTypesOrNil(abstractInst)
|
let paramType = paramType.skipTypesOrNil(abstractInst)
|
||||||
|
|
@ -833,7 +833,7 @@ proc track(tracked: PEffects, n: PNode) =
|
||||||
createTypeBoundOps(tracked.graph, tracked.c, it.typ, it.info)
|
createTypeBoundOps(tracked.graph, tracked.c, it.typ, it.info)
|
||||||
let iterCall = n[n.len-2]
|
let iterCall = n[n.len-2]
|
||||||
let loopBody = n[n.len-1]
|
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:
|
# XXX this is a bit hacky:
|
||||||
if iterCall[1].typ != nil and iterCall[1].typ.skipTypes(abstractVar).kind notin {tyVarargs, tyOpenArray}:
|
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)
|
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])
|
lockLocations(tracked, pragmaList.sons[i])
|
||||||
elif pragma == wGcSafe:
|
elif pragma == wGcSafe:
|
||||||
enforcedGcSafety = true
|
enforcedGcSafety = true
|
||||||
elif pragma == wNosideeffect:
|
elif pragma == wNoSideEffect:
|
||||||
enforceNoSideEffects = true
|
enforceNoSideEffects = true
|
||||||
if enforcedGcSafety: tracked.inEnforcedGcSafe = true
|
if enforcedGcSafety: tracked.inEnforcedGcSafe = true
|
||||||
if enforceNoSideEffects: tracked.inEnforcedNoSideEffects = 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 effects = newNode(nkEffectList, n.info)
|
||||||
var t: TEffects
|
var t: TEffects
|
||||||
initEffects(g, effects, module, t, c)
|
initEffects(g, effects, module, t, c)
|
||||||
t.isToplevel = true
|
t.isTopLevel = true
|
||||||
track(t, n)
|
track(t, n)
|
||||||
|
|
|
||||||
|
|
@ -333,7 +333,7 @@ proc semIdentDef(c: PContext, n: PNode, kind: TSymKind): PSym =
|
||||||
suggestSym(c.config, info, result, c.graph.usageSym)
|
suggestSym(c.config, info, result, c.graph.usageSym)
|
||||||
|
|
||||||
proc checkNilable(c: PContext; v: PSym) =
|
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 != {}:
|
{tfNotNil, tfNeedsInit} * v.typ.flags != {}:
|
||||||
if v.astdef.isNil:
|
if v.astdef.isNil:
|
||||||
message(c.config, v.info, warnProveInit, v.name.s)
|
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)
|
let typsym = pkg.tab.strTableGet(typName)
|
||||||
if typsym.isNil:
|
if typsym.isNil:
|
||||||
s = semIdentDef(c, name[1], skType)
|
s = semIdentDef(c, name[1], skType)
|
||||||
styleCheckDef(c.config, s)
|
|
||||||
onDef(name[1].info, s)
|
onDef(name[1].info, s)
|
||||||
s.typ = newTypeS(tyObject, c)
|
s.typ = newTypeS(tyObject, c)
|
||||||
s.typ.sym = s
|
s.typ.sym = s
|
||||||
|
|
@ -1024,7 +1023,6 @@ proc typeSectionLeftSidePass(c: PContext, n: PNode) =
|
||||||
s = typsym
|
s = typsym
|
||||||
else:
|
else:
|
||||||
s = semIdentDef(c, name, skType)
|
s = semIdentDef(c, name, skType)
|
||||||
styleCheckDef(c.config, s)
|
|
||||||
onDef(name.info, s)
|
onDef(name.info, s)
|
||||||
s.typ = newTypeS(tyForward, c)
|
s.typ = newTypeS(tyForward, c)
|
||||||
s.typ.sym = s # process pragmas:
|
s.typ.sym = s # process pragmas:
|
||||||
|
|
@ -1253,6 +1251,8 @@ proc typeSectionFinalPass(c: PContext, n: PNode) =
|
||||||
if a.kind == nkCommentStmt: continue
|
if a.kind == nkCommentStmt: continue
|
||||||
let name = typeSectionTypeName(c, a.sons[0])
|
let name = typeSectionTypeName(c, a.sons[0])
|
||||||
var s = name.sym
|
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:
|
# compute the type's size and check for illegal recursions:
|
||||||
if a.sons[1].kind == nkEmpty:
|
if a.sons[1].kind == nkEmpty:
|
||||||
var x = a[2]
|
var x = a[2]
|
||||||
|
|
@ -1286,7 +1286,7 @@ proc semAllTypeSections(c: PContext; n: PNode): PNode =
|
||||||
of nkIncludeStmt:
|
of nkIncludeStmt:
|
||||||
for i in 0..<n.len:
|
for i in 0..<n.len:
|
||||||
var f = checkModuleName(c.config, n.sons[i])
|
var f = checkModuleName(c.config, n.sons[i])
|
||||||
if f != InvalidFileIDX:
|
if f != InvalidFileIdx:
|
||||||
if containsOrIncl(c.includedFiles, f.int):
|
if containsOrIncl(c.includedFiles, f.int):
|
||||||
localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
|
localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
|
||||||
else:
|
else:
|
||||||
|
|
@ -2021,7 +2021,7 @@ proc semMacroDef(c: PContext, n: PNode): PNode =
|
||||||
|
|
||||||
proc incMod(c: PContext, n: PNode, it: PNode, includeStmtResult: PNode) =
|
proc incMod(c: PContext, n: PNode, it: PNode, includeStmtResult: PNode) =
|
||||||
var f = checkModuleName(c.config, it)
|
var f = checkModuleName(c.config, it)
|
||||||
if f != InvalidFileIDX:
|
if f != InvalidFileIdx:
|
||||||
if containsOrIncl(c.includedFiles, f.int):
|
if containsOrIncl(c.includedFiles, f.int):
|
||||||
localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
|
localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -1614,8 +1614,8 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType =
|
||||||
elif op.id == ord(wType):
|
elif op.id == ord(wType):
|
||||||
checkSonsLen(n, 2, c.config)
|
checkSonsLen(n, 2, c.config)
|
||||||
result = semTypeof(c, n[1], prev)
|
result = semTypeof(c, n[1], prev)
|
||||||
elif op.s == "typeof" and n[0].kind == nkSym and n[0].sym.magic == mTypeof:
|
elif op.s == "typeof" and n[0].kind == nkSym and n[0].sym.magic == mTypeOf:
|
||||||
result = semTypeOf2(c, n, prev)
|
result = semTypeof2(c, n, prev)
|
||||||
elif op.s == "owned" and optNimV2 notin c.config.globalOptions and n.len == 2:
|
elif op.s == "owned" and optNimV2 notin c.config.globalOptions and n.len == 2:
|
||||||
result = semTypeExpr(c, n[1], prev)
|
result = semTypeExpr(c, n[1], prev)
|
||||||
else:
|
else:
|
||||||
|
|
@ -1640,7 +1640,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType =
|
||||||
of mSet: result = semSet(c, n, prev)
|
of mSet: result = semSet(c, n, prev)
|
||||||
of mOrdinal: result = semOrdinal(c, n, prev)
|
of mOrdinal: result = semOrdinal(c, n, prev)
|
||||||
of mSeq:
|
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]
|
let s = c.graph.sysTypes[tySequence]
|
||||||
assert s != nil
|
assert s != nil
|
||||||
assert prev == nil
|
assert prev == nil
|
||||||
|
|
@ -1658,7 +1658,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType =
|
||||||
c.typesWithOps.add((result, result))
|
c.typesWithOps.add((result, result))
|
||||||
else:
|
else:
|
||||||
result = semContainer(c, n, tySequence, "seq", prev)
|
result = semContainer(c, n, tySequence, "seq", prev)
|
||||||
if c.config.selectedGc == gcDestructors:
|
if c.config.selectedGC == gcDestructors:
|
||||||
incl result.flags, tfHasAsgn
|
incl result.flags, tfHasAsgn
|
||||||
of mOpt: result = semContainer(c, n, tyOpt, "opt", prev)
|
of mOpt: result = semContainer(c, n, tyOpt, "opt", prev)
|
||||||
of mVarargs: result = semVarargs(c, n, prev)
|
of mVarargs: result = semVarargs(c, n, prev)
|
||||||
|
|
@ -1842,7 +1842,7 @@ proc processMagicType(c: PContext, m: PSym) =
|
||||||
of mString:
|
of mString:
|
||||||
setMagicType(c.config, m, tyString, szUncomputedSize)
|
setMagicType(c.config, m, tyString, szUncomputedSize)
|
||||||
rawAddSon(m.typ, getSysType(c.graph, m.info, tyChar))
|
rawAddSon(m.typ, getSysType(c.graph, m.info, tyChar))
|
||||||
if c.config.selectedGc == gcDestructors:
|
if c.config.selectedGC == gcDestructors:
|
||||||
incl m.typ.flags, tfHasAsgn
|
incl m.typ.flags, tfHasAsgn
|
||||||
of mCstring:
|
of mCstring:
|
||||||
setMagicIntegral(c.config, m, tyCString, c.config.target.ptrSize)
|
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)
|
setMagicIntegral(c.config, m, tyUncheckedArray, szUncomputedSize)
|
||||||
of mSeq:
|
of mSeq:
|
||||||
setMagicType(c.config, m, tySequence, szUncomputedSize)
|
setMagicType(c.config, m, tySequence, szUncomputedSize)
|
||||||
if c.config.selectedGc == gcDestructors:
|
if c.config.selectedGC == gcDestructors:
|
||||||
incl m.typ.flags, tfHasAsgn
|
incl m.typ.flags, tfHasAsgn
|
||||||
assert c.graph.sysTypes[tySequence] == nil
|
assert c.graph.sysTypes[tySequence] == nil
|
||||||
c.graph.sysTypes[tySequence] = m.typ
|
c.graph.sysTypes[tySequence] = m.typ
|
||||||
|
|
|
||||||
|
|
@ -598,7 +598,7 @@ proc replaceTypeVarsTAux(cl: var TReplTypeVars, t: PType): PType =
|
||||||
skipIntLiteralParams(result)
|
skipIntLiteralParams(result)
|
||||||
|
|
||||||
of tySequence:
|
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.attachedOps[attachedDestructor].isNil and
|
||||||
result[0].kind != tyEmpty and optNimV2 notin cl.c.config.globalOptions:
|
result[0].kind != tyEmpty and optNimV2 notin cl.c.config.globalOptions:
|
||||||
let s = cl.c.graph.sysTypes[tySequence]
|
let s = cl.c.graph.sysTypes[tySequence]
|
||||||
|
|
|
||||||
|
|
@ -249,7 +249,7 @@ proc hashType*(t: PType; flags: set[ConsiderFlag] = {CoType}): SigHash =
|
||||||
var c: MD5Context
|
var c: MD5Context
|
||||||
md5Init c
|
md5Init c
|
||||||
hashType c, t, flags+{CoOwnerSig}
|
hashType c, t, flags+{CoOwnerSig}
|
||||||
md5Final c, result.Md5Digest
|
md5Final c, result.MD5Digest
|
||||||
when defined(debugSigHashes):
|
when defined(debugSigHashes):
|
||||||
db.exec(sql"INSERT OR IGNORE INTO sighashes(type, hash) VALUES (?, ?)",
|
db.exec(sql"INSERT OR IGNORE INTO sighashes(type, hash) VALUES (?, ?)",
|
||||||
typeToString(t), $result)
|
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
|
# hash, we also hash the line information. This is pretty bad, but the best
|
||||||
# solution for now:
|
# solution for now:
|
||||||
#c &= s.info.line
|
#c &= s.info.line
|
||||||
md5Final c, result.Md5Digest
|
md5Final c, result.MD5Digest
|
||||||
|
|
||||||
proc hashNonProc*(s: PSym): SigHash =
|
proc hashNonProc*(s: PSym): SigHash =
|
||||||
var c: MD5Context
|
var c: MD5Context
|
||||||
|
|
@ -288,7 +288,7 @@ proc hashNonProc*(s: PSym): SigHash =
|
||||||
# might cause:
|
# might cause:
|
||||||
if s.kind == skParam:
|
if s.kind == skParam:
|
||||||
c &= s.position
|
c &= s.position
|
||||||
md5Final c, result.Md5Digest
|
md5Final c, result.MD5Digest
|
||||||
|
|
||||||
proc hashOwner*(s: PSym): SigHash =
|
proc hashOwner*(s: PSym): SigHash =
|
||||||
var c: MD5Context
|
var c: MD5Context
|
||||||
|
|
@ -301,7 +301,7 @@ proc hashOwner*(s: PSym): SigHash =
|
||||||
c &= "."
|
c &= "."
|
||||||
c &= m.name.s
|
c &= m.name.s
|
||||||
|
|
||||||
md5Final c, result.Md5Digest
|
md5Final c, result.MD5Digest
|
||||||
|
|
||||||
proc sigHash*(s: PSym): SigHash =
|
proc sigHash*(s: PSym): SigHash =
|
||||||
if s.kind in routineKinds and s.typ != nil:
|
if s.kind in routineKinds and s.typ != nil:
|
||||||
|
|
@ -368,14 +368,14 @@ proc symBodyDigest*(graph: ModuleGraph, sym: PSym): SigHash =
|
||||||
md5Init(c)
|
md5Init(c)
|
||||||
c.hashType(sym.typ, {CoProc})
|
c.hashType(sym.typ, {CoProc})
|
||||||
c &= char(sym.kind)
|
c &= char(sym.kind)
|
||||||
c.md5Final(result.Md5Digest)
|
c.md5Final(result.MD5Digest)
|
||||||
graph.symBodyHashes[sym.id] = result # protect from recursion in the body
|
graph.symBodyHashes[sym.id] = result # protect from recursion in the body
|
||||||
|
|
||||||
if sym.ast != nil:
|
if sym.ast != nil:
|
||||||
md5Init(c)
|
md5Init(c)
|
||||||
c.md5Update(cast[cstring](result.addr), sizeof(result))
|
c.md5Update(cast[cstring](result.addr), sizeof(result))
|
||||||
hashBodyTree(graph, c, sym.ast[bodyPos])
|
hashBodyTree(graph, c, sym.ast[bodyPos])
|
||||||
c.md5Final(result.Md5Digest)
|
c.md5Final(result.MD5Digest)
|
||||||
graph.symBodyHashes[sym.id] = result
|
graph.symBodyHashes[sym.id] = result
|
||||||
|
|
||||||
proc idOrSig*(s: PSym, currentModule: string,
|
proc idOrSig*(s: PSym, currentModule: string,
|
||||||
|
|
|
||||||
|
|
@ -1494,7 +1494,7 @@ proc typeRel(c: var TCandidate, f, aOrig: PType,
|
||||||
# Workaround for regression #4589
|
# Workaround for regression #4589
|
||||||
if f.sons[i].kind != tyTypeDesc: return
|
if f.sons[i].kind != tyTypeDesc: return
|
||||||
result = isGeneric
|
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)):
|
(sonsLen(x) - 1 == sonsLen(f)):
|
||||||
# do not recurse here in order to not K bind twice for this code:
|
# 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
|
# Here object inheriting from generic/specialized generic object
|
||||||
# crossing path with metatypes/aliases, so we need to separate them
|
# crossing path with metatypes/aliases, so we need to separate them
|
||||||
# by checking sym.id
|
# 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:
|
if not (genericSubtype and aobj.sym.id != fobj.sym.id) and aOrig.kind != tyGenericBody:
|
||||||
depth = -1
|
depth = -1
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -253,7 +253,7 @@ proc mapTypeToAstX(cache: IdentCache; t: PType; info: TLineInfo;
|
||||||
result.add t.n.sons[1].copyTree
|
result.add t.n.sons[1].copyTree
|
||||||
of tyPointer: result = atomicType("pointer", mPointer)
|
of tyPointer: result = atomicType("pointer", mPointer)
|
||||||
of tyString: result = atomicType("string", mString)
|
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 tyInt: result = atomicType("int", mInt)
|
||||||
of tyInt8: result = atomicType("int8", mInt8)
|
of tyInt8: result = atomicType("int8", mInt8)
|
||||||
of tyInt16: result = atomicType("int16", mInt16)
|
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 tyFloat32: result = atomicType("float32", mFloat32)
|
||||||
of tyFloat64: result = atomicType("float64", mFloat64)
|
of tyFloat64: result = atomicType("float64", mFloat64)
|
||||||
of tyFloat128: result = atomicType("float128", mFloat128)
|
of tyFloat128: result = atomicType("float128", mFloat128)
|
||||||
of tyUInt: result = atomicType("uint", mUint)
|
of tyUInt: result = atomicType("uint", mUInt)
|
||||||
of tyUInt8: result = atomicType("uint8", mUint8)
|
of tyUInt8: result = atomicType("uint8", mUInt8)
|
||||||
of tyUInt16: result = atomicType("uint16", mUint16)
|
of tyUInt16: result = atomicType("uint16", mUInt16)
|
||||||
of tyUInt32: result = atomicType("uint32", mUint32)
|
of tyUInt32: result = atomicType("uint32", mUInt32)
|
||||||
of tyUInt64: result = atomicType("uint64", mUint64)
|
of tyUInt64: result = atomicType("uint64", mUInt64)
|
||||||
of tyVarargs: result = mapTypeToBracket("varargs", mVarargs, t, info)
|
of tyVarargs: result = mapTypeToBracket("varargs", mVarargs, t, info)
|
||||||
of tyProxy: result = atomicType("error", mNone)
|
of tyProxy: result = atomicType("error", mNone)
|
||||||
of tyBuiltInTypeClass:
|
of tyBuiltInTypeClass:
|
||||||
|
|
|
||||||
|
|
@ -43,16 +43,16 @@ type
|
||||||
wImportCpp, wImportObjC,
|
wImportCpp, wImportObjC,
|
||||||
wImportCompilerProc,
|
wImportCompilerProc,
|
||||||
wImportc, wExportc, wExportNims, wIncompleteStruct, wRequiresInit,
|
wImportc, wExportc, wExportNims, wIncompleteStruct, wRequiresInit,
|
||||||
wAlign, wNodecl, wPure, wSideeffect, wHeader,
|
wAlign, wNodecl, wPure, wSideEffect, wHeader,
|
||||||
wNoSideEffect, wGcSafe, wNoreturn, wMerge, wLib, wDynlib,
|
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,
|
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,
|
wLinksys, wDeprecated, wVarargs, wCallconv, wBreakpoint, wDebugger,
|
||||||
wNimcall, wStdcall, wCdecl, wSafecall, wSyscall, wInline, wNoInline,
|
wNimcall, wStdcall, wCdecl, wSafecall, wSyscall, wInline, wNoInline,
|
||||||
wFastcall, wClosure, wNoconv, wOn, wOff, wChecks, wRangechecks,
|
wFastcall, wClosure, wNoconv, wOn, wOff, wChecks, wRangeChecks,
|
||||||
wBoundchecks, wOverflowchecks, wNilchecks,
|
wBoundChecks, wOverflowChecks, wNilChecks,
|
||||||
wFloatchecks, wNanChecks, wInfChecks, wMoveChecks,
|
wFloatChecks, wNanChecks, wInfChecks, wStyleChecks,
|
||||||
wNonReloadable, wExecuteOnReload,
|
wNonReloadable, wExecuteOnReload,
|
||||||
wAssertions, wPatterns, wTrMacros, wWarnings,
|
wAssertions, wPatterns, wTrMacros, wWarnings,
|
||||||
wHints, wOptimization, wRaises, wWrites, wReads, wSize, wEffects, wTags,
|
wHints, wOptimization, wRaises, wWrites, wReads, wSize, wEffects, wTags,
|
||||||
|
|
@ -142,7 +142,7 @@ const
|
||||||
"cdecl", "safecall", "syscall", "inline", "noinline", "fastcall", "closure",
|
"cdecl", "safecall", "syscall", "inline", "noinline", "fastcall", "closure",
|
||||||
"noconv", "on", "off", "checks", "rangechecks", "boundchecks",
|
"noconv", "on", "off", "checks", "rangechecks", "boundchecks",
|
||||||
"overflowchecks", "nilchecks",
|
"overflowchecks", "nilchecks",
|
||||||
"floatchecks", "nanchecks", "infchecks", "movechecks",
|
"floatchecks", "nanchecks", "infchecks", "stylechecks",
|
||||||
"nonreloadable", "executeonreload",
|
"nonreloadable", "executeonreload",
|
||||||
|
|
||||||
"assertions", "patterns", "trmacros", "warnings", "hints",
|
"assertions", "patterns", "trmacros", "warnings", "hints",
|
||||||
|
|
@ -192,7 +192,6 @@ proc canonPragmaSpelling*(w: TSpecialWord): string =
|
||||||
of wIncompleteStruct: "incompleteStruct"
|
of wIncompleteStruct: "incompleteStruct"
|
||||||
of wRequiresInit: "requiresInit"
|
of wRequiresInit: "requiresInit"
|
||||||
of wSideEffect: "sideEffect"
|
of wSideEffect: "sideEffect"
|
||||||
of wCompilerProc: "compilerProc"
|
|
||||||
of wLineDir: "lineDir"
|
of wLineDir: "lineDir"
|
||||||
of wStackTrace: "stackTrace"
|
of wStackTrace: "stackTrace"
|
||||||
of wLineTrace: "lineTrace"
|
of wLineTrace: "lineTrace"
|
||||||
|
|
@ -203,12 +202,11 @@ proc canonPragmaSpelling*(w: TSpecialWord): string =
|
||||||
of wFloatChecks: "floatChecks"
|
of wFloatChecks: "floatChecks"
|
||||||
of wNanChecks: "nanChecks"
|
of wNanChecks: "nanChecks"
|
||||||
of wInfChecks: "infChecks"
|
of wInfChecks: "infChecks"
|
||||||
of wMoveChecks: "moveChecks"
|
of wStyleChecks: "styleChecks"
|
||||||
of wNonReloadable: "nonReloadable"
|
of wNonReloadable: "nonReloadable"
|
||||||
of wExecuteOnReload: "executeOnReload"
|
of wExecuteOnReload: "executeOnReload"
|
||||||
of wDeadCodeElimUnused: "deadCodeElim"
|
of wDeadCodeElimUnused: "deadCodeElim"
|
||||||
of wCompileTime: "compileTime"
|
of wCompileTime: "compileTime"
|
||||||
of wNoInit: "noInit"
|
|
||||||
of wFieldChecks: "fieldChecks"
|
of wFieldChecks: "fieldChecks"
|
||||||
of wLinearScanEnd: "linearScanEnd"
|
of wLinearScanEnd: "linearScanEnd"
|
||||||
of wComputedGoto: "computedGoto"
|
of wComputedGoto: "computedGoto"
|
||||||
|
|
|
||||||
|
|
@ -499,7 +499,7 @@ type
|
||||||
filename*: string
|
filename*: string
|
||||||
line*,column*: int
|
line*,column*: int
|
||||||
|
|
||||||
proc `$`*(arg: Lineinfo): string =
|
proc `$`*(arg: LineInfo): string =
|
||||||
# BUG: without `result = `, gives compile error
|
# BUG: without `result = `, gives compile error
|
||||||
result = arg.filename & "(" & $arg.line & ", " & $arg.column & ")"
|
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
|
## Create a new block statement with label
|
||||||
return newNimNode(nnkBlockStmt).add(label, body)
|
return newNimNode(nnkBlockStmt).add(label, body)
|
||||||
|
|
||||||
proc newBlockStmt*(body: NimNode): NimNode {.compiletime.} =
|
proc newBlockStmt*(body: NimNode): NimNode {.compileTime.} =
|
||||||
## Create a new block: stmt
|
## Create a new block: stmt
|
||||||
return newNimNode(nnkBlockStmt).add(newEmptyNode(), body)
|
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
|
## Create a new var stmt
|
||||||
return newNimNode(nnkVarSection).add(
|
return newNimNode(nnkVarSection).add(
|
||||||
newNimNode(nnkIdentDefs).add(name, newNimNode(nnkEmpty), value))
|
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
|
## Create a new let stmt
|
||||||
return newNimNode(nnkLetSection).add(
|
return newNimNode(nnkLetSection).add(
|
||||||
newNimNode(nnkIdentDefs).add(name, newNimNode(nnkEmpty), value))
|
newNimNode(nnkIdentDefs).add(name, newNimNode(nnkEmpty), value))
|
||||||
|
|
@ -1095,7 +1095,7 @@ proc newProc*(name = newEmptyNode();
|
||||||
body)
|
body)
|
||||||
|
|
||||||
proc newIfStmt*(branches: varargs[tuple[cond, body: NimNode]]):
|
proc newIfStmt*(branches: varargs[tuple[cond, body: NimNode]]):
|
||||||
NimNode {.compiletime.} =
|
NimNode {.compileTime.} =
|
||||||
## Constructor for ``if`` statements.
|
## Constructor for ``if`` statements.
|
||||||
##
|
##
|
||||||
## .. code-block:: nim
|
## .. code-block:: nim
|
||||||
|
|
@ -1233,7 +1233,7 @@ proc `body=`*(someProc: NimNode, val: NimNode) {.compileTime.} =
|
||||||
else:
|
else:
|
||||||
badNodeKind someProc, "body="
|
badNodeKind someProc, "body="
|
||||||
|
|
||||||
proc basename*(a: NimNode): NimNode {.compiletime, benign.}
|
proc basename*(a: NimNode): NimNode {.compileTime, benign.}
|
||||||
|
|
||||||
proc `$`*(node: NimNode): string {.compileTime.} =
|
proc `$`*(node: NimNode): string {.compileTime.} =
|
||||||
## Get the string of an identifier node
|
## Get the string of an identifier node
|
||||||
|
|
@ -1396,7 +1396,7 @@ else:
|
||||||
else:
|
else:
|
||||||
result = false
|
result = false
|
||||||
|
|
||||||
proc hasArgOfName*(params: NimNode; name: string): bool {.compiletime.}=
|
proc hasArgOfName*(params: NimNode; name: string): bool {.compileTime.}=
|
||||||
## Search nnkFormalParams for an argument.
|
## Search nnkFormalParams for an argument.
|
||||||
expectKind(params, nnkFormalParams)
|
expectKind(params, nnkFormalParams)
|
||||||
for i in 1 ..< params.len:
|
for i in 1 ..< params.len:
|
||||||
|
|
@ -1404,7 +1404,7 @@ proc hasArgOfName*(params: NimNode; name: string): bool {.compiletime.}=
|
||||||
if name.eqIdent( $ node[0]):
|
if name.eqIdent( $ node[0]):
|
||||||
return true
|
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
|
## Add ident to dest if it is not present. This is intended for use
|
||||||
## with pragmas.
|
## with pragmas.
|
||||||
for node in dest.children:
|
for node in dest.children:
|
||||||
|
|
|
||||||
|
|
@ -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) =
|
proc setLen[T](s: var seq[T], newlen: Natural) =
|
||||||
{.noSideEffect.}:
|
{.noSideEffect.}:
|
||||||
if newlen < s.len:
|
if newlen < s.len:
|
||||||
shrink(s, newLen)
|
shrink(s, newlen)
|
||||||
else:
|
else:
|
||||||
let oldLen = s.len
|
let oldLen = s.len
|
||||||
if newLen <= oldLen: return
|
if newlen <= oldLen: return
|
||||||
var xu = cast[ptr NimSeqV2[T]](addr s)
|
var xu = cast[ptr NimSeqV2[T]](addr s)
|
||||||
if xu.p == nil or xu.p.cap < 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.p = cast[typeof(xu.p)](prepareSeqAdd(oldLen, xu.p, newlen - oldLen, sizeof(T)))
|
||||||
xu.len = newLen
|
xu.len = newlen
|
||||||
|
|
||||||
when false:
|
when false:
|
||||||
proc resize[T](s: var NimSeqV2[T]) =
|
proc resize[T](s: var NimSeqV2[T]) =
|
||||||
|
|
|
||||||
|
|
@ -12,12 +12,12 @@
|
||||||
when false:
|
when false:
|
||||||
# these are to be implemented or changed in the code generator.
|
# 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.
|
# seems to be unused.
|
||||||
proc copyDeepString(src: NimString): NimString {.inline.}
|
proc copyDeepString(src: NimString): NimString {.inline.}
|
||||||
# ----------------- sequences ----------------------------------------------
|
# ----------------- 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 {.
|
proc setLengthSeqV2(s: PGenericSeq, typ: PNimType, newLen: int): PGenericSeq {.
|
||||||
compilerRtl.}
|
compilerRtl.}
|
||||||
proc newSeq(typ: PNimType, len: int): pointer {.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'
|
s.p.data[s.len+1] = '\0'
|
||||||
inc s.len
|
inc s.len
|
||||||
|
|
||||||
proc toNimStr(str: cstring, len: int): NimStringV2 {.compilerProc.} =
|
proc toNimStr(str: cstring, len: int): NimStringV2 {.compilerproc.} =
|
||||||
if len <= 0:
|
if len <= 0:
|
||||||
result = NimStringV2(len: 0, p: nil)
|
result = NimStringV2(len: 0, p: nil)
|
||||||
else:
|
else:
|
||||||
|
|
@ -126,7 +126,7 @@ proc cstrToNimstr(str: cstring): NimStringV2 {.compilerRtl.} =
|
||||||
if str == nil: toNimStr(str, 0)
|
if str == nil: toNimStr(str, 0)
|
||||||
else: toNimStr(str, str.len)
|
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""
|
if s.len == 0: result = cstring""
|
||||||
else: result = cstring(unsafeAddr s.p.data)
|
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'
|
dest.p.data[dest.len+1] = '\0'
|
||||||
inc dest.len
|
inc dest.len
|
||||||
|
|
||||||
proc rawNewString(space: int): NimStringV2 {.compilerProc.} =
|
proc rawNewString(space: int): NimStringV2 {.compilerproc.} =
|
||||||
# this is also 'system.newStringOfCap'.
|
# this is also 'system.newStringOfCap'.
|
||||||
if space <= 0:
|
if space <= 0:
|
||||||
result = NimStringV2(len: 0, p: nil)
|
result = NimStringV2(len: 0, p: nil)
|
||||||
|
|
@ -152,7 +152,7 @@ proc rawNewString(space: int): NimStringV2 {.compilerProc.} =
|
||||||
p.cap = space
|
p.cap = space
|
||||||
result = NimStringV2(len: 0, p: p)
|
result = NimStringV2(len: 0, p: p)
|
||||||
|
|
||||||
proc mnewString(len: int): NimStringV2 {.compilerProc.} =
|
proc mnewString(len: int): NimStringV2 {.compilerproc.} =
|
||||||
if len <= 0:
|
if len <= 0:
|
||||||
result = NimStringV2(len: 0, p: nil)
|
result = NimStringV2(len: 0, p: nil)
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -865,7 +865,7 @@ proc yamlNextToken(g: var GeneralTokenizer) =
|
||||||
inc(pos)
|
inc(pos)
|
||||||
while g.buf[pos] in {'0'..'9', '+', '-'}: inc(pos)
|
while g.buf[pos] in {'0'..'9', '+', '-'}: inc(pos)
|
||||||
of '0'..'9': yamlPossibleNumber(g, pos)
|
of '0'..'9': yamlPossibleNumber(g, pos)
|
||||||
of '\0': g.kind = gtEOF
|
of '\0': g.kind = gtEof
|
||||||
else: yamlPlainStrLit(g, pos)
|
else: yamlPlainStrLit(g, pos)
|
||||||
else:
|
else:
|
||||||
# outside document
|
# outside document
|
||||||
|
|
@ -883,7 +883,7 @@ proc yamlNextToken(g: var GeneralTokenizer) =
|
||||||
of '#':
|
of '#':
|
||||||
g.kind = gtComment
|
g.kind = gtComment
|
||||||
while g.buf[pos] notin {'\0', '\x0A', '\x0D'}: inc(pos)
|
while g.buf[pos] notin {'\0', '\x0A', '\x0D'}: inc(pos)
|
||||||
of '\0': g.kind = gtEOF
|
of '\0': g.kind = gtEof
|
||||||
else:
|
else:
|
||||||
g.kind = gtNone
|
g.kind = gtNone
|
||||||
g.state = gtOther
|
g.state = gtOther
|
||||||
|
|
|
||||||
|
|
@ -32,6 +32,9 @@
|
||||||
# error only if they actualy try to use the missing declaration
|
# error only if they actualy try to use the missing declaration
|
||||||
{.deadCodeElim: on.} # dce option deprecated
|
{.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
|
# 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?
|
# platforms - where do they come from and why are they here?
|
||||||
when false:
|
when false:
|
||||||
|
|
@ -114,13 +117,13 @@ when StatHasNanoseconds:
|
||||||
## Second-granularity time of last status change.
|
## Second-granularity time of last status change.
|
||||||
result = s.st_ctim.tv_sec
|
result = s.st_ctim.tv_sec
|
||||||
else:
|
else:
|
||||||
proc st_atim*(s: Stat): TimeSpec {.inline.} =
|
proc st_atim*(s: Stat): Timespec {.inline.} =
|
||||||
## Nanosecond-granularity time of last access.
|
## Nanosecond-granularity time of last access.
|
||||||
result.tv_sec = s.st_atime
|
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.
|
## Nanosecond-granularity time of last data modification.
|
||||||
result.tv_sec = s.st_mtime
|
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.
|
## Nanosecond-granularity time of last data modification.
|
||||||
result.tv_sec = s.st_ctime
|
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 {.
|
proc pthread_atfork*(a1, a2, a3: proc () {.noconv.}): cint {.
|
||||||
importc, header: "<pthread.h>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
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>".}
|
importc, header: "<pthread.h>".}
|
||||||
proc pthread_barrier_destroy*(a1: ptr Pthread_barrier): cint {.
|
proc pthread_barrier_destroy*(a1: ptr Pthread_barrier): cint {.
|
||||||
importc, header: "<pthread.h>".}
|
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_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_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>".}
|
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_detach*(a1: Pthread): cint {.importc, header: "<pthread.h>".}
|
||||||
proc pthread_equal*(a1, a2: 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
|
proc getrlimit*(resource: cint, rlp: var RLimit): cint
|
||||||
{.importc: "getrlimit",header: "<sys/resource.h>".}
|
{.importc: "getrlimit",header: "<sys/resource.h>".}
|
||||||
## The getrlimit() system call gets resource limits.
|
## The getrlimit() system call gets resource limits.
|
||||||
|
|
||||||
|
when defined(nimHasStyleChecks):
|
||||||
|
{.pop.} # {.push styleChecks: off.}
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,10 @@ const
|
||||||
# On Linux:
|
# On Linux:
|
||||||
# timer_{create,delete,settime,gettime},
|
# timer_{create,delete,settime,gettime},
|
||||||
# clock_{getcpuclockid, getres, gettime, nanosleep, settime} lives in librt
|
# clock_{getcpuclockid, getres, gettime, nanosleep, settime} lives in librt
|
||||||
{.passL: "-lrt".}
|
{.passl: "-lrt".}
|
||||||
|
|
||||||
|
when defined(nimHasStyleChecks):
|
||||||
|
{.push styleChecks: off.}
|
||||||
|
|
||||||
# Types
|
# Types
|
||||||
|
|
||||||
|
|
@ -32,7 +35,7 @@ type
|
||||||
SocketHandle* = distinct cint # The type used to represent socket descriptors
|
SocketHandle* = distinct cint # The type used to represent socket descriptors
|
||||||
|
|
||||||
# not detected by detect.nim, guarded by #ifdef __USE_UNIX98 in glibc
|
# 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
|
type
|
||||||
Time* {.importc: "time_t", header: "<time.h>".} = distinct clong
|
Time* {.importc: "time_t", header: "<time.h>".} = distinct clong
|
||||||
|
|
@ -296,7 +299,7 @@ type
|
||||||
sigev_signo*: cint ## Signal number.
|
sigev_signo*: cint ## Signal number.
|
||||||
sigev_notify*: cint ## Notification type.
|
sigev_notify*: cint ## Notification type.
|
||||||
sigev_notify_function*: proc (x: SigVal) {.noconv.} ## Notification func.
|
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]
|
abi: array[12, int]
|
||||||
|
|
||||||
SigVal* {.importc: "union sigval",
|
SigVal* {.importc: "union sigval",
|
||||||
|
|
@ -579,4 +582,7 @@ proc WSTOPSIG*(s:cint): cint = WEXITSTATUS(s)
|
||||||
proc WIFEXITED*(s:cint) : bool = WTERMSIG(s) == 0
|
proc WIFEXITED*(s:cint) : bool = WTERMSIG(s) == 0
|
||||||
proc WIFSIGNALED*(s:cint) : bool = (cast[int8]((s and 0x7f) + 1) shr 1) > 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 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.}
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,9 @@
|
||||||
|
|
||||||
{.deadCodeElim: on.} # dce option deprecated
|
{.deadCodeElim: on.} # dce option deprecated
|
||||||
|
|
||||||
|
when defined(nimHasStyleChecks):
|
||||||
|
{.push styleChecks: off.}
|
||||||
|
|
||||||
const
|
const
|
||||||
hasSpawnH = true # should exist for every Posix system nowadays
|
hasSpawnH = true # should exist for every Posix system nowadays
|
||||||
hasAioH = false
|
hasAioH = false
|
||||||
|
|
@ -272,7 +275,7 @@ type
|
||||||
sigev_signo*: cint ## Signal number.
|
sigev_signo*: cint ## Signal number.
|
||||||
sigev_value*: SigVal ## Signal value.
|
sigev_value*: SigVal ## Signal value.
|
||||||
sigev_notify_function*: proc (x: SigVal) {.noconv.} ## Notification func.
|
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",
|
SigVal* {.importc: "union sigval",
|
||||||
header: "<signal.h>", final, pure.} = object ## struct 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.
|
## True if child is currently stopped.
|
||||||
proc WIFCONTINUED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
|
proc WIFCONTINUED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
|
||||||
## True if child has been continued.
|
## True if child has been continued.
|
||||||
|
|
||||||
|
when defined(nimHasStyleChecks):
|
||||||
|
{.pop.}
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,9 @@
|
||||||
|
|
||||||
{.deadCodeElim: on.} # dce option deprecated
|
{.deadCodeElim: on.} # dce option deprecated
|
||||||
|
|
||||||
|
when defined(nimHasStyleChecks):
|
||||||
|
{.push styleChecks: off.}
|
||||||
|
|
||||||
const
|
const
|
||||||
hasSpawnH = true # should exist for every Posix system nowadays
|
hasSpawnH = true # should exist for every Posix system nowadays
|
||||||
hasAioH = defined(linux)
|
hasAioH = defined(linux)
|
||||||
|
|
@ -281,7 +284,7 @@ type
|
||||||
sigev_signo*: cint ## Signal number.
|
sigev_signo*: cint ## Signal number.
|
||||||
sigev_value*: SigVal ## Signal value.
|
sigev_value*: SigVal ## Signal value.
|
||||||
sigev_notify_function*: proc (x: SigVal) {.noconv.} ## Notification func.
|
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",
|
SigVal* {.importc: "union sigval",
|
||||||
header: "<signal.h>", final, pure.} = object ## struct 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.
|
## True if child is currently stopped.
|
||||||
proc WIFCONTINUED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
|
proc WIFCONTINUED*(s: cint): bool {.importc, header: "<sys/wait.h>".}
|
||||||
## True if child has been continued.
|
## True if child has been continued.
|
||||||
|
|
||||||
|
when defined(nimHasStyleChecks):
|
||||||
|
{.pop.}
|
||||||
|
|
|
||||||
|
|
@ -532,7 +532,7 @@ func isSorted*[T](a: openArray[T],
|
||||||
if cmp(a[i],a[i+1]) * order > 0:
|
if cmp(a[i],a[i+1]) * order > 0:
|
||||||
return false
|
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.
|
## Shortcut version of ``isSorted`` that uses ``system.cmp[T]`` as the comparison function.
|
||||||
##
|
##
|
||||||
## **See also:**
|
## **See also:**
|
||||||
|
|
@ -588,7 +588,7 @@ proc product*[T](x: openArray[seq[T]]): seq[seq[T]] =
|
||||||
index = 0
|
index = 0
|
||||||
indexes[index] -= 1
|
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``.
|
## Calculates the next lexicographic permutation, directly modifying ``x``.
|
||||||
## The result is whether a permutation happened, otherwise we have reached
|
## The result is whether a permutation happened, otherwise we have reached
|
||||||
## the last-ordered permutation.
|
## the last-ordered permutation.
|
||||||
|
|
@ -628,7 +628,7 @@ proc nextPermutation*[T](x: var openarray[T]): bool {.discardable.} =
|
||||||
|
|
||||||
result = true
|
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
|
## Calculates the previous lexicographic permutation, directly modifying
|
||||||
## ``x``. The result is whether a permutation happened, otherwise we have
|
## ``x``. The result is whether a permutation happened, otherwise we have
|
||||||
## reached the first-ordered permutation.
|
## reached the first-ordered permutation.
|
||||||
|
|
@ -693,7 +693,7 @@ when isMainModule:
|
||||||
assert arr1.reversed(i, high(arr1)) == arr1.reversed()[0 .. high(arr1) - i]
|
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/>`_.
|
## A port of std::rotate from c++. Ported from `this reference <http://www.cplusplus.com/reference/algorithm/rotate/>`_.
|
||||||
result = first + last - middle
|
result = first + last - middle
|
||||||
|
|
||||||
|
|
@ -732,20 +732,20 @@ proc rotateInternal[T](arg: var openarray[T]; first, middle, last: int): int =
|
||||||
elif next == last:
|
elif next == last:
|
||||||
next = mMiddle
|
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)
|
result = newSeq[T](arg.len)
|
||||||
for i in 0 ..< first:
|
for i in 0 ..< first:
|
||||||
result[i] = arg[i]
|
result[i] = arg[i]
|
||||||
let N = last - middle
|
let n = last - middle
|
||||||
let M = middle - first
|
let m = middle - first
|
||||||
for i in 0 ..< N:
|
for i in 0 ..< n:
|
||||||
result[first+i] = arg[middle+i]
|
result[first+i] = arg[middle+i]
|
||||||
for i in 0 ..< M:
|
for i in 0 ..< m:
|
||||||
result[first+N+i] = arg[first+i]
|
result[first+n+i] = arg[first+i]
|
||||||
for i in last ..< arg.len:
|
for i in last ..< arg.len:
|
||||||
result[i] = arg[i]
|
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
|
## Performs a left rotation on a range of elements. If you want to rotate
|
||||||
## right, use a negative ``dist``. Specifically, ``rotateLeft`` rotates
|
## right, use a negative ``dist``. Specifically, ``rotateLeft`` rotates
|
||||||
## the elements at ``slice`` by ``dist`` positions.
|
## 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
|
let distLeft = ((dist mod sliceLen) + sliceLen) mod sliceLen
|
||||||
arg.rotateInternal(slice.a, slice.a+distLeft, slice.b + 1)
|
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
|
## Default arguments for slice, so that this procedure operates on the entire
|
||||||
## ``arg``, and not just on a part of it.
|
## ``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
|
let distLeft = ((dist mod arglen) + arglen) mod arglen
|
||||||
arg.rotateInternal(0, distLeft, 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
|
## Same as ``rotateLeft``, just with the difference that it does
|
||||||
## not modify the argument. It creates a new ``seq`` instead.
|
## 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
|
let distLeft = ((dist mod sliceLen) + sliceLen) mod sliceLen
|
||||||
arg.rotatedInternal(slice.a, slice.a+distLeft, slice.b+1)
|
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
|
## Same as ``rotateLeft``, just with the difference that it does
|
||||||
## not modify the argument. It creates a new ``seq`` instead.
|
## not modify the argument. It creates a new ``seq`` instead.
|
||||||
##
|
##
|
||||||
|
|
|
||||||
|
|
@ -232,7 +232,7 @@ when defined(windows) or defined(nimdoc):
|
||||||
|
|
||||||
CompletionData* = object
|
CompletionData* = object
|
||||||
fd*: AsyncFD # TODO: Rename this.
|
fd*: AsyncFD # TODO: Rename this.
|
||||||
cb*: owned(proc (fd: AsyncFD, bytesTransferred: Dword,
|
cb*: owned(proc (fd: AsyncFD, bytesTransferred: DWORD,
|
||||||
errcode: OSErrorCode) {.closure, gcsafe.})
|
errcode: OSErrorCode) {.closure, gcsafe.})
|
||||||
cell*: ForeignCell # we need this `cell` to protect our `cb` environment,
|
cell*: ForeignCell # we need this `cell` to protect our `cb` environment,
|
||||||
# when using RegisterWaitForSingleObject, because
|
# when using RegisterWaitForSingleObject, because
|
||||||
|
|
@ -328,7 +328,7 @@ when defined(windows) or defined(nimdoc):
|
||||||
if at == -1: winlean.INFINITE
|
if at == -1: winlean.INFINITE
|
||||||
else: at.int32
|
else: at.int32
|
||||||
|
|
||||||
var lpNumberOfBytesTransferred: Dword
|
var lpNumberOfBytesTransferred: DWORD
|
||||||
var lpCompletionKey: ULONG_PTR
|
var lpCompletionKey: ULONG_PTR
|
||||||
var customOverlapped: PCustomOverlapped
|
var customOverlapped: PCustomOverlapped
|
||||||
let res = getQueuedCompletionStatus(p.ioPort,
|
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 =
|
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
|
# Ref: https://github.com/powdahound/twisted/blob/master/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c
|
||||||
var bytesRet: Dword
|
var bytesRet: DWORD
|
||||||
fun = nil
|
fun = nil
|
||||||
result = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, addr guid,
|
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
|
addr bytesRet, nil, nil) == 0
|
||||||
|
|
||||||
proc initAll() =
|
proc initAll() =
|
||||||
|
|
@ -425,12 +425,12 @@ when defined(windows) or defined(nimdoc):
|
||||||
dataBuf.buf = cast[cstring](alloc0(size))
|
dataBuf.buf = cast[cstring](alloc0(size))
|
||||||
dataBuf.len = size.ULONG
|
dataBuf.len = size.ULONG
|
||||||
|
|
||||||
var bytesReceived: Dword
|
var bytesReceived: DWORD
|
||||||
var flagsio = flags.toOSFlags().Dword
|
var flagsio = flags.toOSFlags().DWORD
|
||||||
var ol = PCustomOverlapped()
|
var ol = PCustomOverlapped()
|
||||||
GC_ref(ol)
|
GC_ref(ol)
|
||||||
ol.data = CompletionData(fd: socket, cb:
|
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 not retFuture.finished:
|
||||||
if errcode == OSErrorCode(-1):
|
if errcode == OSErrorCode(-1):
|
||||||
if bytesCount == 0 and dataBuf.buf[0] == '\0':
|
if bytesCount == 0 and dataBuf.buf[0] == '\0':
|
||||||
|
|
@ -502,12 +502,12 @@ when defined(windows) or defined(nimdoc):
|
||||||
dataBuf.buf = cast[cstring](buf)
|
dataBuf.buf = cast[cstring](buf)
|
||||||
dataBuf.len = size.ULONG
|
dataBuf.len = size.ULONG
|
||||||
|
|
||||||
var bytesReceived: Dword
|
var bytesReceived: DWORD
|
||||||
var flagsio = flags.toOSFlags().Dword
|
var flagsio = flags.toOSFlags().DWORD
|
||||||
var ol = PCustomOverlapped()
|
var ol = PCustomOverlapped()
|
||||||
GC_ref(ol)
|
GC_ref(ol)
|
||||||
ol.data = CompletionData(fd: socket, cb:
|
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 not retFuture.finished:
|
||||||
if errcode == OSErrorCode(-1):
|
if errcode == OSErrorCode(-1):
|
||||||
retFuture.complete(bytesCount)
|
retFuture.complete(bytesCount)
|
||||||
|
|
@ -556,11 +556,11 @@ when defined(windows) or defined(nimdoc):
|
||||||
dataBuf.buf = cast[cstring](buf)
|
dataBuf.buf = cast[cstring](buf)
|
||||||
dataBuf.len = size.ULONG
|
dataBuf.len = size.ULONG
|
||||||
|
|
||||||
var bytesReceived, lowFlags: Dword
|
var bytesReceived, lowFlags: DWORD
|
||||||
var ol = PCustomOverlapped()
|
var ol = PCustomOverlapped()
|
||||||
GC_ref(ol)
|
GC_ref(ol)
|
||||||
ol.data = CompletionData(fd: socket, cb:
|
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 not retFuture.finished:
|
||||||
if errcode == OSErrorCode(-1):
|
if errcode == OSErrorCode(-1):
|
||||||
retFuture.complete()
|
retFuture.complete()
|
||||||
|
|
@ -589,7 +589,7 @@ when defined(windows) or defined(nimdoc):
|
||||||
return retFuture
|
return retFuture
|
||||||
|
|
||||||
proc sendTo*(socket: AsyncFD, data: pointer, size: int, saddr: ptr SockAddr,
|
proc sendTo*(socket: AsyncFD, data: pointer, size: int, saddr: ptr SockAddr,
|
||||||
saddrLen: Socklen,
|
saddrLen: SockLen,
|
||||||
flags = {SocketFlag.SafeDisconn}): owned(Future[void]) =
|
flags = {SocketFlag.SafeDisconn}): owned(Future[void]) =
|
||||||
## Sends ``data`` to specified destination ``saddr``, using
|
## Sends ``data`` to specified destination ``saddr``, using
|
||||||
## socket ``socket``. The returned future will complete once all data
|
## socket ``socket``. The returned future will complete once all data
|
||||||
|
|
@ -599,8 +599,8 @@ when defined(windows) or defined(nimdoc):
|
||||||
var dataBuf: TWSABuf
|
var dataBuf: TWSABuf
|
||||||
dataBuf.buf = cast[cstring](data)
|
dataBuf.buf = cast[cstring](data)
|
||||||
dataBuf.len = size.ULONG
|
dataBuf.len = size.ULONG
|
||||||
var bytesSent = 0.Dword
|
var bytesSent = 0.DWORD
|
||||||
var lowFlags = 0.Dword
|
var lowFlags = 0.DWORD
|
||||||
|
|
||||||
# we will preserve address in our stack
|
# we will preserve address in our stack
|
||||||
var staddr: array[128, char] # SOCKADDR_STORAGE size is 128 bytes
|
var staddr: array[128, char] # SOCKADDR_STORAGE size is 128 bytes
|
||||||
|
|
@ -611,7 +611,7 @@ when defined(windows) or defined(nimdoc):
|
||||||
var ol = PCustomOverlapped()
|
var ol = PCustomOverlapped()
|
||||||
GC_ref(ol)
|
GC_ref(ol)
|
||||||
ol.data = CompletionData(fd: socket, cb:
|
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 not retFuture.finished:
|
||||||
if errcode == OSErrorCode(-1):
|
if errcode == OSErrorCode(-1):
|
||||||
retFuture.complete()
|
retFuture.complete()
|
||||||
|
|
@ -647,13 +647,13 @@ when defined(windows) or defined(nimdoc):
|
||||||
|
|
||||||
var dataBuf = TWSABuf(buf: cast[cstring](data), len: size.ULONG)
|
var dataBuf = TWSABuf(buf: cast[cstring](data), len: size.ULONG)
|
||||||
|
|
||||||
var bytesReceived = 0.Dword
|
var bytesReceived = 0.DWORD
|
||||||
var lowFlags = 0.Dword
|
var lowFlags = 0.DWORD
|
||||||
|
|
||||||
var ol = PCustomOverlapped()
|
var ol = PCustomOverlapped()
|
||||||
GC_ref(ol)
|
GC_ref(ol)
|
||||||
ol.data = CompletionData(fd: socket, cb:
|
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 not retFuture.finished:
|
||||||
if errcode == OSErrorCode(-1):
|
if errcode == OSErrorCode(-1):
|
||||||
assert bytesCount <= size
|
assert bytesCount <= size
|
||||||
|
|
@ -704,10 +704,10 @@ when defined(windows) or defined(nimdoc):
|
||||||
|
|
||||||
const lpOutputLen = 1024
|
const lpOutputLen = 1024
|
||||||
var lpOutputBuf = newString(lpOutputLen)
|
var lpOutputBuf = newString(lpOutputLen)
|
||||||
var dwBytesReceived: Dword
|
var dwBytesReceived: DWORD
|
||||||
let dwReceiveDataLength = 0.Dword # We don't want any data to be read.
|
let dwReceiveDataLength = 0.DWORD # We don't want any data to be read.
|
||||||
let dwLocalAddressLength = Dword(sizeof(Sockaddr_in6) + 16)
|
let dwLocalAddressLength = DWORD(sizeof(Sockaddr_in6) + 16)
|
||||||
let dwRemoteAddressLength = Dword(sizeof(Sockaddr_in6) + 16)
|
let dwRemoteAddressLength = DWORD(sizeof(Sockaddr_in6) + 16)
|
||||||
|
|
||||||
template failAccept(errcode) =
|
template failAccept(errcode) =
|
||||||
if flags.isDisconnectionError(errcode):
|
if flags.isDisconnectionError(errcode):
|
||||||
|
|
@ -728,17 +728,17 @@ when defined(windows) or defined(nimdoc):
|
||||||
sizeof(listenSock).SockLen)
|
sizeof(listenSock).SockLen)
|
||||||
if setoptRet != 0:
|
if setoptRet != 0:
|
||||||
let errcode = osLastError()
|
let errcode = osLastError()
|
||||||
discard clientSock.closeSocket()
|
discard clientSock.closesocket()
|
||||||
failAccept(errcode)
|
failAccept(errcode)
|
||||||
else:
|
else:
|
||||||
var localSockaddr, remoteSockaddr: ptr SockAddr
|
var localSockaddr, remoteSockaddr: ptr SockAddr
|
||||||
var localLen, remoteLen: int32
|
var localLen, remoteLen: int32
|
||||||
getAcceptExSockaddrs(addr lpOutputBuf[0], dwReceiveDataLength,
|
getAcceptExSockAddrs(addr lpOutputBuf[0], dwReceiveDataLength,
|
||||||
dwLocalAddressLength, dwRemoteAddressLength,
|
dwLocalAddressLength, dwRemoteAddressLength,
|
||||||
addr localSockaddr, addr localLen,
|
addr localSockaddr, addr localLen,
|
||||||
addr remoteSockaddr, addr remoteLen)
|
addr remoteSockaddr, addr remoteLen)
|
||||||
try:
|
try:
|
||||||
let address = getAddrString(remoteSockAddr)
|
let address = getAddrString(remoteSockaddr)
|
||||||
register(clientSock.AsyncFD)
|
register(clientSock.AsyncFD)
|
||||||
retFuture.complete((address: address, client: clientSock.AsyncFD))
|
retFuture.complete((address: address, client: clientSock.AsyncFD))
|
||||||
except:
|
except:
|
||||||
|
|
@ -749,7 +749,7 @@ when defined(windows) or defined(nimdoc):
|
||||||
var ol = PCustomOverlapped()
|
var ol = PCustomOverlapped()
|
||||||
GC_ref(ol)
|
GC_ref(ol)
|
||||||
ol.data = CompletionData(fd: socket, cb:
|
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 not retFuture.finished:
|
||||||
if errcode == OSErrorCode(-1):
|
if errcode == OSErrorCode(-1):
|
||||||
completeAccept()
|
completeAccept()
|
||||||
|
|
@ -793,14 +793,14 @@ when defined(windows) or defined(nimdoc):
|
||||||
proc waitableCallback(param: pointer,
|
proc waitableCallback(param: pointer,
|
||||||
timerOrWaitFired: WINBOOL): void {.stdcall.} =
|
timerOrWaitFired: WINBOOL): void {.stdcall.} =
|
||||||
var p = cast[PostCallbackDataPtr](param)
|
var p = cast[PostCallbackDataPtr](param)
|
||||||
discard postQueuedCompletionStatus(p.ioPort, timerOrWaitFired.Dword,
|
discard postQueuedCompletionStatus(p.ioPort, timerOrWaitFired.DWORD,
|
||||||
ULONG_PTR(p.handleFd),
|
ULONG_PTR(p.handleFd),
|
||||||
cast[pointer](p.ovl))
|
cast[pointer](p.ovl))
|
||||||
{.pop.}
|
{.pop.}
|
||||||
|
|
||||||
proc registerWaitableEvent(fd: AsyncFD, cb: Callback; mask: Dword) =
|
proc registerWaitableEvent(fd: AsyncFD, cb: Callback; mask: DWORD) =
|
||||||
let p = getGlobalDispatcher()
|
let p = getGlobalDispatcher()
|
||||||
var flags = (WT_EXECUTEINWAITTHREAD or WT_EXECUTEONLYONCE).Dword
|
var flags = (WT_EXECUTEINWAITTHREAD or WT_EXECUTEONLYONCE).DWORD
|
||||||
var hEvent = wsaCreateEvent()
|
var hEvent = wsaCreateEvent()
|
||||||
if hEvent == 0:
|
if hEvent == 0:
|
||||||
raiseOSError(osLastError())
|
raiseOSError(osLastError())
|
||||||
|
|
@ -811,7 +811,7 @@ when defined(windows) or defined(nimdoc):
|
||||||
GC_ref(ol)
|
GC_ref(ol)
|
||||||
|
|
||||||
ol.data = CompletionData(fd: fd, cb:
|
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
|
# we excluding our `fd` because cb(fd) can register own handler
|
||||||
# for this `fd`
|
# for this `fd`
|
||||||
p.handles.excl(fd)
|
p.handles.excl(fd)
|
||||||
|
|
@ -934,7 +934,7 @@ when defined(windows) or defined(nimdoc):
|
||||||
pcd.ovl = ol
|
pcd.ovl = ol
|
||||||
if not registerWaitForSingleObject(addr(pcd.waitFd), hEvent,
|
if not registerWaitForSingleObject(addr(pcd.waitFd), hEvent,
|
||||||
cast[WAITORTIMERCALLBACK](waitableCallback),
|
cast[WAITORTIMERCALLBACK](waitableCallback),
|
||||||
cast[pointer](pcd), timeout.Dword, flags):
|
cast[pointer](pcd), timeout.DWORD, flags):
|
||||||
let err = osLastError()
|
let err = osLastError()
|
||||||
GC_unref(ol)
|
GC_unref(ol)
|
||||||
deallocShared(cast[pointer](pcd))
|
deallocShared(cast[pointer](pcd))
|
||||||
|
|
@ -972,10 +972,10 @@ when defined(windows) or defined(nimdoc):
|
||||||
raiseOSError(osLastError())
|
raiseOSError(osLastError())
|
||||||
|
|
||||||
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
|
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
|
||||||
var flags = WT_EXECUTEINWAITTHREAD.Dword
|
var flags = WT_EXECUTEINWAITTHREAD.DWORD
|
||||||
if oneshot: flags = flags or WT_EXECUTEONLYONCE
|
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)
|
let res = cb(fd)
|
||||||
if res or oneshot:
|
if res or oneshot:
|
||||||
closeWaitable(hEvent)
|
closeWaitable(hEvent)
|
||||||
|
|
@ -993,14 +993,14 @@ when defined(windows) or defined(nimdoc):
|
||||||
## ``pid`` exited.
|
## ``pid`` exited.
|
||||||
let p = getGlobalDispatcher()
|
let p = getGlobalDispatcher()
|
||||||
let procFlags = SYNCHRONIZE
|
let procFlags = SYNCHRONIZE
|
||||||
var hProcess = openProcess(procFlags, 0, pid.Dword)
|
var hProcess = openProcess(procFlags, 0, pid.DWORD)
|
||||||
if hProcess == INVALID_HANDLE_VALUE:
|
if hProcess == INVALID_HANDLE_VALUE:
|
||||||
raiseOSError(osLastError())
|
raiseOSError(osLastError())
|
||||||
|
|
||||||
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
|
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)
|
closeWaitable(hProcess)
|
||||||
discard cb(fd)
|
discard cb(fd)
|
||||||
|
|
||||||
|
|
@ -1052,9 +1052,9 @@ when defined(windows) or defined(nimdoc):
|
||||||
let hEvent = ev.hEvent
|
let hEvent = ev.hEvent
|
||||||
|
|
||||||
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
|
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 ev.hWaiter != 0:
|
||||||
if cb(fd):
|
if cb(fd):
|
||||||
# we need this check to avoid exception, if `unregister(event)` was
|
# we need this check to avoid exception, if `unregister(event)` was
|
||||||
|
|
@ -1615,7 +1615,7 @@ when defined(windows) or defined(nimdoc):
|
||||||
var ol = PCustomOverlapped()
|
var ol = PCustomOverlapped()
|
||||||
GC_ref(ol)
|
GC_ref(ol)
|
||||||
ol.data = CompletionData(fd: socket, cb:
|
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 not retFuture.finished:
|
||||||
if errcode == OSErrorCode(-1):
|
if errcode == OSErrorCode(-1):
|
||||||
retFuture.complete()
|
retFuture.complete()
|
||||||
|
|
@ -1708,7 +1708,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
|
||||||
curAddrInfo = curAddrInfo.ai_next
|
curAddrInfo = curAddrInfo.ai_next
|
||||||
|
|
||||||
if curAddrInfo == nil:
|
if curAddrInfo == nil:
|
||||||
freeAddrInfo(addrInfo)
|
freeaddrinfo(addrInfo)
|
||||||
when shouldCreateFd:
|
when shouldCreateFd:
|
||||||
closeUnusedFds()
|
closeUnusedFds()
|
||||||
if lastException != nil:
|
if lastException != nil:
|
||||||
|
|
@ -1724,7 +1724,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
|
||||||
try:
|
try:
|
||||||
curFd = createAsyncNativeSocket(domain, sockType, protocol)
|
curFd = createAsyncNativeSocket(domain, sockType, protocol)
|
||||||
except:
|
except:
|
||||||
freeAddrInfo(addrInfo)
|
freeaddrinfo(addrInfo)
|
||||||
closeUnusedFds()
|
closeUnusedFds()
|
||||||
raise getCurrentException()
|
raise getCurrentException()
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
|
|
@ -1734,7 +1734,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
|
||||||
doConnect(curFd, curAddrInfo).callback = tryNextAddrInfo
|
doConnect(curFd, curAddrInfo).callback = tryNextAddrInfo
|
||||||
curAddrInfo = curAddrInfo.ai_next
|
curAddrInfo = curAddrInfo.ai_next
|
||||||
else:
|
else:
|
||||||
freeAddrInfo(addrInfo)
|
freeaddrinfo(addrInfo)
|
||||||
when shouldCreateFd:
|
when shouldCreateFd:
|
||||||
closeUnusedFds(ord(domain))
|
closeUnusedFds(ord(domain))
|
||||||
retFuture.complete(curFd)
|
retFuture.complete(curFd)
|
||||||
|
|
|
||||||
|
|
@ -303,7 +303,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
|
||||||
# Find longest filename & line number combo for alignment purposes.
|
# Find longest filename & line number combo for alignment purposes.
|
||||||
var longestLeft = 0
|
var longestLeft = 0
|
||||||
for entry in entries:
|
for entry in entries:
|
||||||
if entry.procName.isNil: continue
|
if entry.procname.isNil: continue
|
||||||
|
|
||||||
let left = $entry.filename & $entry.line
|
let left = $entry.filename & $entry.line
|
||||||
if left.len > longestLeft:
|
if left.len > longestLeft:
|
||||||
|
|
@ -312,7 +312,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
|
||||||
var indent = 2
|
var indent = 2
|
||||||
# Format the entries.
|
# Format the entries.
|
||||||
for entry in entries:
|
for entry in entries:
|
||||||
if entry.procName.isNil:
|
if entry.procname.isNil:
|
||||||
if entry.line == -10:
|
if entry.line == -10:
|
||||||
result.add(spaces(indent) & "#[\n")
|
result.add(spaces(indent) & "#[\n")
|
||||||
indent.inc(2)
|
indent.inc(2)
|
||||||
|
|
@ -325,7 +325,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
|
||||||
result.add((spaces(indent) & "$#$# $#\n") % [
|
result.add((spaces(indent) & "$#$# $#\n") % [
|
||||||
left,
|
left,
|
||||||
spaces(longestLeft - left.len + 2),
|
spaces(longestLeft - left.len + 2),
|
||||||
$entry.procName
|
$entry.procname
|
||||||
])
|
])
|
||||||
let hint = getHint(entry)
|
let hint = getHint(entry)
|
||||||
if hint.len > 0:
|
if hint.len > 0:
|
||||||
|
|
|
||||||
|
|
@ -121,7 +121,7 @@ when defined(nimHasalignOf):
|
||||||
|
|
||||||
# #### Pure Nim version ####
|
# #### 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.
|
## 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
|
# 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,
|
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))
|
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
|
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.
|
## 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
|
# https://graphics.stanford.edu/%7Eseander/bithacks.html#ZerosOnRightMultLookup
|
||||||
var v = uint64(x)
|
var v = uint64(x)
|
||||||
|
|
@ -138,9 +138,9 @@ proc firstSetBit_nim(x: uint64): int {.inline, nosideeffect.} =
|
||||||
if k == 0:
|
if k == 0:
|
||||||
k = uint32(v shr 32'u32) and 0xFFFFFFFF'u32
|
k = uint32(v shr 32'u32) and 0xFFFFFFFF'u32
|
||||||
result = 32
|
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.
|
## Quickly find the log base 2 of a 32-bit or less integer.
|
||||||
# https://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogDeBruijn
|
# https://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogDeBruijn
|
||||||
# https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers
|
# 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
|
v = v or v shr 16
|
||||||
result = lookup[uint32(v * 0x07C4ACDD'u32) shr 27].int
|
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.
|
## Quickly find the log base 2 of a 64-bit integer.
|
||||||
# https://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogDeBruijn
|
# https://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogDeBruijn
|
||||||
# https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers
|
# 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.
|
# countBits32 and countBits64.
|
||||||
include system/sets
|
include system/sets
|
||||||
|
|
||||||
template countSetBits_nim(n: uint32): int = countBits32(n)
|
template countSetBitsNim(n: uint32): int = countBits32(n)
|
||||||
template countSetBits_nim(n: uint64): int = countBits64(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
|
# formula id from: https://graphics.stanford.edu/%7Eseander/bithacks.html#ParityParallel
|
||||||
var v = value
|
var v = value
|
||||||
when sizeof(T) == 8:
|
when sizeof(T) == 8:
|
||||||
|
|
@ -216,17 +216,17 @@ when useGCC_builtins:
|
||||||
|
|
||||||
elif useVCC_builtins:
|
elif useVCC_builtins:
|
||||||
# Counts the number of one bits (population count) in a 16-, 32-, or 64-byte unsigned integer.
|
# 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_popcnt16(a2: uint16): uint16 {.importc: "__popcnt16" header: "<intrin.h>", noSideEffect.}
|
||||||
proc builtin_popcnt32(a2: uint32): uint32 {.importc: "__popcnt" 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_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).
|
# 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 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 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).
|
# 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 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 bitScanForward64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanForward64", header: "<intrin.h>", noSideEffect.}
|
||||||
|
|
||||||
template vcc_scan_impl(fnc: untyped; v: untyped): int =
|
template vcc_scan_impl(fnc: untyped; v: untyped): int =
|
||||||
var index: culong
|
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
|
# 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
|
# 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.
|
# 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_popcnt32(a: cint): cint {.importc: "_popcnt" header: "<immintrin.h>", noSideEffect.}
|
||||||
proc builtin_popcnt64(a: uint64): cint {.importc: "_popcnt64" 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.
|
# 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 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 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.
|
# 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 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 bitScanReverse64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanReverse64", header: "<immintrin.h>", noSideEffect.}
|
||||||
|
|
||||||
template icc_scan_impl(fnc: untyped; v: untyped): int =
|
template icc_scan_impl(fnc: untyped; v: untyped): int =
|
||||||
var index: uint32
|
var index: uint32
|
||||||
|
|
@ -255,14 +255,14 @@ elif useICC_builtins:
|
||||||
index.int
|
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:.)
|
## Counts the set bits in integer. (also called `Hamming weight`:idx:.)
|
||||||
# TODO: figure out if ICC support _popcnt32/_popcnt64 on platform without POPCNT.
|
# TODO: figure out if ICC support _popcnt32/_popcnt64 on platform without POPCNT.
|
||||||
# like GCC and MSVC
|
# like GCC and MSVC
|
||||||
when x is SomeSignedInt:
|
when x is SomeSignedInt:
|
||||||
let x = x.toUnsigned
|
let x = x.toUnsigned
|
||||||
when nimvm:
|
when nimvm:
|
||||||
result = forwardImpl(countSetBits_nim, x)
|
result = forwardImpl(countSetBitsNim, x)
|
||||||
else:
|
else:
|
||||||
when useGCC_builtins:
|
when useGCC_builtins:
|
||||||
when sizeof(x) <= 4: result = builtin_popcount(x.cuint).int
|
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 +
|
else: result = builtin_popcnt32((x.uint64 and 0xFFFFFFFF'u64).cint ).int +
|
||||||
builtin_popcnt32((x.uint64 shr 32'u64).cint ).int
|
builtin_popcnt32((x.uint64 shr 32'u64).cint ).int
|
||||||
else:
|
else:
|
||||||
when sizeof(x) <= 4: result = countSetBits_nim(x.uint32)
|
when sizeof(x) <= 4: result = countSetBitsNim(x.uint32)
|
||||||
else: result = countSetBits_nim(x.uint64)
|
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.)
|
## Alias for for countSetBits (Hamming weight.)
|
||||||
result = countSetBits(x)
|
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
|
## Calculate the bit parity in integer. If number of 1-bit
|
||||||
## is odd parity is 1, otherwise 0.
|
## is odd parity is 1, otherwise 0.
|
||||||
# Can be used a base if creating ASM version.
|
# Can be used a base if creating ASM version.
|
||||||
|
|
@ -294,16 +294,16 @@ proc parityBits*(x: SomeInteger): int {.inline, nosideeffect.} =
|
||||||
when x is SomeSignedInt:
|
when x is SomeSignedInt:
|
||||||
let x = x.toUnsigned
|
let x = x.toUnsigned
|
||||||
when nimvm:
|
when nimvm:
|
||||||
result = forwardImpl(parity_impl, x)
|
result = forwardImpl(parityImpl, x)
|
||||||
else:
|
else:
|
||||||
when useGCC_builtins:
|
when useGCC_builtins:
|
||||||
when sizeof(x) <= 4: result = builtin_parity(x.uint32).int
|
when sizeof(x) <= 4: result = builtin_parity(x.uint32).int
|
||||||
else: result = builtin_parityll(x.uint64).int
|
else: result = builtin_parityll(x.uint64).int
|
||||||
else:
|
else:
|
||||||
when sizeof(x) <= 4: result = parity_impl(x.uint32)
|
when sizeof(x) <= 4: result = parityImpl(x.uint32)
|
||||||
else: result = parity_impl(x.uint64)
|
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.
|
## Returns the 1-based index of the least significant set bit of x.
|
||||||
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
|
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
|
||||||
## otherwise result is undefined.
|
## otherwise result is undefined.
|
||||||
|
|
@ -314,7 +314,7 @@ proc firstSetBit*(x: SomeInteger): int {.inline, nosideeffect.} =
|
||||||
when noUndefined:
|
when noUndefined:
|
||||||
if x == 0:
|
if x == 0:
|
||||||
return 0
|
return 0
|
||||||
result = forwardImpl(firstSetBit_nim, x)
|
result = forwardImpl(firstSetBitNim, x)
|
||||||
else:
|
else:
|
||||||
when noUndefined and not useGCC_builtins:
|
when noUndefined and not useGCC_builtins:
|
||||||
if x == 0:
|
if x == 0:
|
||||||
|
|
@ -328,19 +328,19 @@ proc firstSetBit*(x: SomeInteger): int {.inline, nosideeffect.} =
|
||||||
elif arch64:
|
elif arch64:
|
||||||
result = 1 + vcc_scan_impl(bitScanForward64, x.uint64)
|
result = 1 + vcc_scan_impl(bitScanForward64, x.uint64)
|
||||||
else:
|
else:
|
||||||
result = firstSetBit_nim(x.uint64)
|
result = firstSetBitNim(x.uint64)
|
||||||
elif useICC_builtins:
|
elif useICC_builtins:
|
||||||
when sizeof(x) <= 4:
|
when sizeof(x) <= 4:
|
||||||
result = 1 + icc_scan_impl(bitScanForward, x.uint32)
|
result = 1 + icc_scan_impl(bitScanForward, x.uint32)
|
||||||
elif arch64:
|
elif arch64:
|
||||||
result = 1 + icc_scan_impl(bitScanForward64, x.uint64)
|
result = 1 + icc_scan_impl(bitScanForward64, x.uint64)
|
||||||
else:
|
else:
|
||||||
result = firstSetBit_nim(x.uint64)
|
result = firstSetBitNim(x.uint64)
|
||||||
else:
|
else:
|
||||||
when sizeof(x) <= 4: result = firstSetBit_nim(x.uint32)
|
when sizeof(x) <= 4: result = firstSetBitNim(x.uint32)
|
||||||
else: result = firstSetBit_nim(x.uint64)
|
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.
|
## Quickly find the log base 2 of an integer.
|
||||||
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is -1,
|
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is -1,
|
||||||
## otherwise result is undefined.
|
## otherwise result is undefined.
|
||||||
|
|
@ -350,7 +350,7 @@ proc fastLog2*(x: SomeInteger): int {.inline, nosideeffect.} =
|
||||||
if x == 0:
|
if x == 0:
|
||||||
return -1
|
return -1
|
||||||
when nimvm:
|
when nimvm:
|
||||||
result = forwardImpl(fastlog2_nim, x)
|
result = forwardImpl(fastlog2Nim, x)
|
||||||
else:
|
else:
|
||||||
when useGCC_builtins:
|
when useGCC_builtins:
|
||||||
when sizeof(x) <= 4: result = 31 - builtin_clz(x.uint32).int
|
when sizeof(x) <= 4: result = 31 - builtin_clz(x.uint32).int
|
||||||
|
|
@ -361,19 +361,19 @@ proc fastLog2*(x: SomeInteger): int {.inline, nosideeffect.} =
|
||||||
elif arch64:
|
elif arch64:
|
||||||
result = vcc_scan_impl(bitScanReverse64, x.uint64)
|
result = vcc_scan_impl(bitScanReverse64, x.uint64)
|
||||||
else:
|
else:
|
||||||
result = fastlog2_nim(x.uint64)
|
result = fastlog2Nim(x.uint64)
|
||||||
elif useICC_builtins:
|
elif useICC_builtins:
|
||||||
when sizeof(x) <= 4:
|
when sizeof(x) <= 4:
|
||||||
result = icc_scan_impl(bitScanReverse, x.uint32)
|
result = icc_scan_impl(bitScanReverse, x.uint32)
|
||||||
elif arch64:
|
elif arch64:
|
||||||
result = icc_scan_impl(bitScanReverse64, x.uint64)
|
result = icc_scan_impl(bitScanReverse64, x.uint64)
|
||||||
else:
|
else:
|
||||||
result = fastlog2_nim(x.uint64)
|
result = fastlog2Nim(x.uint64)
|
||||||
else:
|
else:
|
||||||
when sizeof(x) <= 4: result = fastlog2_nim(x.uint32)
|
when sizeof(x) <= 4: result = fastlog2Nim(x.uint32)
|
||||||
else: result = fastlog2_nim(x.uint64)
|
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.
|
## Returns the number of leading zero bits in integer.
|
||||||
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
|
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
|
||||||
## otherwise result is undefined.
|
## otherwise result is undefined.
|
||||||
|
|
@ -383,16 +383,16 @@ proc countLeadingZeroBits*(x: SomeInteger): int {.inline, nosideeffect.} =
|
||||||
if x == 0:
|
if x == 0:
|
||||||
return 0
|
return 0
|
||||||
when nimvm:
|
when nimvm:
|
||||||
result = sizeof(x)*8 - 1 - forwardImpl(fastlog2_nim, x)
|
result = sizeof(x)*8 - 1 - forwardImpl(fastlog2Nim, x)
|
||||||
else:
|
else:
|
||||||
when useGCC_builtins:
|
when useGCC_builtins:
|
||||||
when sizeof(x) <= 4: result = builtin_clz(x.uint32).int - (32 - sizeof(x)*8)
|
when sizeof(x) <= 4: result = builtin_clz(x.uint32).int - (32 - sizeof(x)*8)
|
||||||
else: result = builtin_clzll(x.uint64).int
|
else: result = builtin_clzll(x.uint64).int
|
||||||
else:
|
else:
|
||||||
when sizeof(x) <= 4: result = sizeof(x)*8 - 1 - fastlog2_nim(x.uint32)
|
when sizeof(x) <= 4: result = sizeof(x)*8 - 1 - fastlog2Nim(x.uint32)
|
||||||
else: result = sizeof(x)*8 - 1 - fastlog2_nim(x.uint64)
|
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.
|
## Returns the number of trailing zeros in integer.
|
||||||
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
|
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
|
||||||
## otherwise result is undefined.
|
## otherwise result is undefined.
|
||||||
|
|
|
||||||
|
|
@ -286,7 +286,7 @@ proc enlarge[A, B](t: var Table[A, B]) =
|
||||||
# ------------------------------ Table ------------------------------
|
# ------------------------------ 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.
|
## Creates a new hash table that is empty.
|
||||||
##
|
##
|
||||||
## ``initialSize`` must be a power of two (default: 64).
|
## ``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.
|
## Creates a new ordered hash table that is empty.
|
||||||
##
|
##
|
||||||
## ``initialSize`` must be a power of two (default: 64).
|
## ``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.
|
## Creates a new count table that is empty.
|
||||||
##
|
##
|
||||||
## ``initialSize`` must be a power of two (default: 64).
|
## ``initialSize`` must be a power of two (default: 64).
|
||||||
|
|
|
||||||
|
|
@ -59,7 +59,7 @@ import strutils
|
||||||
type
|
type
|
||||||
LibHandle* = pointer ## a handle to a dynamically loaded library
|
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
|
## loads a library from `path`. Returns nil if the library could not
|
||||||
## be loaded.
|
## be loaded.
|
||||||
|
|
||||||
|
|
@ -96,14 +96,14 @@ proc libCandidates*(s: string, dest: var seq[string]) =
|
||||||
else:
|
else:
|
||||||
add(dest, s)
|
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`
|
## loads a library with name matching `pattern`, similar to what `dlimport`
|
||||||
## pragma does. Returns nil if the library could not be loaded.
|
## 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.
|
## Warning: this proc uses the GC and so cannot be used to load the GC.
|
||||||
var candidates = newSeq[string]()
|
var candidates = newSeq[string]()
|
||||||
libCandidates(pattern, candidates)
|
libCandidates(pattern, candidates)
|
||||||
for c in candidates:
|
for c in candidates:
|
||||||
result = loadLib(c, global_symbols)
|
result = loadLib(c, globalSymbols)
|
||||||
if not result.isNil: break
|
if not result.isNil: break
|
||||||
|
|
||||||
when defined(posix) and not defined(nintendoswitch):
|
when defined(posix) and not defined(nintendoswitch):
|
||||||
|
|
@ -117,9 +117,9 @@ when defined(posix) and not defined(nintendoswitch):
|
||||||
#
|
#
|
||||||
import posix
|
import posix
|
||||||
|
|
||||||
proc loadLib(path: string, global_symbols=false): LibHandle =
|
proc loadLib(path: string, globalSymbols=false): LibHandle =
|
||||||
let flags =
|
let flags =
|
||||||
if global_symbols: RTLD_NOW or RTLD_GLOBAL
|
if globalSymbols: RTLD_NOW or RTLD_GLOBAL
|
||||||
else: RTLD_NOW
|
else: RTLD_NOW
|
||||||
|
|
||||||
dlopen(path, flags)
|
dlopen(path, flags)
|
||||||
|
|
@ -170,7 +170,7 @@ elif defined(windows) or defined(dos):
|
||||||
proc getProcAddress(lib: THINSTANCE, name: cstring): pointer {.
|
proc getProcAddress(lib: THINSTANCE, name: cstring): pointer {.
|
||||||
importc: "GetProcAddress", header: "<windows.h>", stdcall.}
|
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))
|
result = cast[LibHandle](winLoadLibrary(path))
|
||||||
proc loadLib(): LibHandle =
|
proc loadLib(): LibHandle =
|
||||||
result = cast[LibHandle](winLoadLibrary(nil))
|
result = cast[LibHandle](winLoadLibrary(nil))
|
||||||
|
|
|
||||||
|
|
@ -13,33 +13,33 @@
|
||||||
when defined(gcc) or defined(llvm_gcc) or defined(clang):
|
when defined(gcc) or defined(llvm_gcc) or defined(clang):
|
||||||
const useBuiltinSwap = true
|
const useBuiltinSwap = true
|
||||||
proc builtin_bswap16(a: uint16): uint16 {.
|
proc builtin_bswap16(a: uint16): uint16 {.
|
||||||
importc: "__builtin_bswap16", nodecl, nosideeffect.}
|
importc: "__builtin_bswap16", nodecl, noSideEffect.}
|
||||||
|
|
||||||
proc builtin_bswap32(a: uint32): uint32 {.
|
proc builtin_bswap32(a: uint32): uint32 {.
|
||||||
importc: "__builtin_bswap32", nodecl, nosideeffect.}
|
importc: "__builtin_bswap32", nodecl, noSideEffect.}
|
||||||
|
|
||||||
proc builtin_bswap64(a: uint64): uint64 {.
|
proc builtin_bswap64(a: uint64): uint64 {.
|
||||||
importc: "__builtin_bswap64", nodecl, nosideeffect.}
|
importc: "__builtin_bswap64", nodecl, noSideEffect.}
|
||||||
elif defined(icc):
|
elif defined(icc):
|
||||||
const useBuiltinSwap = true
|
const useBuiltinSwap = true
|
||||||
proc builtin_bswap16(a: uint16): uint16 {.
|
proc builtin_bswap16(a: uint16): uint16 {.
|
||||||
importc: "_bswap16", nodecl, nosideeffect.}
|
importc: "_bswap16", nodecl, noSideEffect.}
|
||||||
|
|
||||||
proc builtin_bswap32(a: uint32): uint32 {.
|
proc builtin_bswap32(a: uint32): uint32 {.
|
||||||
importc: "_bswap", nodecl, nosideeffect.}
|
importc: "_bswap", nodecl, noSideEffect.}
|
||||||
|
|
||||||
proc builtin_bswap64(a: uint64): uint64 {.
|
proc builtin_bswap64(a: uint64): uint64 {.
|
||||||
importc: "_bswap64", nodecl, nosideeffect.}
|
importc: "_bswap64", nodecl, noSideEffect.}
|
||||||
elif defined(vcc):
|
elif defined(vcc):
|
||||||
const useBuiltinSwap = true
|
const useBuiltinSwap = true
|
||||||
proc builtin_bswap16(a: uint16): uint16 {.
|
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 {.
|
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 {.
|
proc builtin_bswap64(a: uint64): uint64 {.
|
||||||
importc: "_byteswap_uint64", nodecl, header: "<intrin.h>", nosideeffect.}
|
importc: "_byteswap_uint64", nodecl, header: "<intrin.h>", noSideEffect.}
|
||||||
else:
|
else:
|
||||||
const useBuiltinSwap = false
|
const useBuiltinSwap = false
|
||||||
|
|
||||||
|
|
@ -49,17 +49,17 @@ when useBuiltinSwap:
|
||||||
## may point to a unaligned address. A sufficiently smart compiler _should_
|
## may point to a unaligned address. A sufficiently smart compiler _should_
|
||||||
## be able to elide them when they're not necessary.
|
## be able to elide them when they're not necessary.
|
||||||
var tmp: T
|
var tmp: T
|
||||||
copyMem(addr tmp, inp, sizeOf(T))
|
copyMem(addr tmp, inp, sizeof(T))
|
||||||
tmp = op(tmp)
|
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)
|
swapOpImpl(uint64, builtin_bswap64)
|
||||||
|
|
||||||
proc swapEndian32*(outp, inp: pointer) {.inline, nosideeffect.}=
|
proc swapEndian32*(outp, inp: pointer) {.inline, noSideEffect.}=
|
||||||
swapOpImpl(uint32, builtin_bswap32)
|
swapOpImpl(uint32, builtin_bswap32)
|
||||||
|
|
||||||
proc swapEndian16*(outp, inp: pointer) {.inline, nosideeffect.}=
|
proc swapEndian16*(outp, inp: pointer) {.inline, noSideEffect.}=
|
||||||
swapOpImpl(uint16, builtin_bswap16)
|
swapOpImpl(uint16, builtin_bswap16)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -169,7 +169,7 @@ template hashImpl(result: Hash, x: typed, start, stop: int) =
|
||||||
var n = 0
|
var n = 0
|
||||||
when nimvm:
|
when nimvm:
|
||||||
# we cannot cast in VM, so we do it manually
|
# 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])
|
n = (n shl (8*elementSize)) or ord(x[i+j])
|
||||||
else:
|
else:
|
||||||
n = cast[ptr Hash](unsafeAddr x[i])[]
|
n = cast[ptr Hash](unsafeAddr x[i])[]
|
||||||
|
|
|
||||||
|
|
@ -324,7 +324,7 @@ proc `%`*(b: bool): JsonNode =
|
||||||
|
|
||||||
proc `%`*(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode =
|
proc `%`*(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode =
|
||||||
## Generic constructor for JSON data. Creates a new `JObject 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()
|
result = newJObject()
|
||||||
for key, val in items(keyVals): result.fields[key] = val
|
for key, val in items(keyVals): result.fields[key] = val
|
||||||
|
|
||||||
|
|
@ -380,7 +380,7 @@ proc `%`*(o: enum): JsonNode =
|
||||||
## string. Creates a new ``JString JsonNode``.
|
## string. Creates a new ``JString JsonNode``.
|
||||||
result = %($o)
|
result = %($o)
|
||||||
|
|
||||||
proc toJson(x: NimNode): NimNode {.compiletime.} =
|
proc toJson(x: NimNode): NimNode {.compileTime.} =
|
||||||
case x.kind
|
case x.kind
|
||||||
of nnkBracket: # array
|
of nnkBracket: # array
|
||||||
if x.len == 0: return newCall(bindSym"newJArray")
|
if x.len == 0: return newCall(bindSym"newJArray")
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,9 @@
|
||||||
## * `hashes module<hashes.html>`_ for efficient computations of hash values
|
## * `hashes module<hashes.html>`_ for efficient computations of hash values
|
||||||
## for diverse Nim types
|
## for diverse Nim types
|
||||||
|
|
||||||
|
when defined(nimHasStyleChecks):
|
||||||
|
{.push styleChecks: off.}
|
||||||
|
|
||||||
type
|
type
|
||||||
MD5State = array[0..3, uint32]
|
MD5State = array[0..3, uint32]
|
||||||
MD5Block = array[0..15, uint32]
|
MD5Block = array[0..15, uint32]
|
||||||
|
|
@ -232,7 +235,7 @@ proc md5Init*(c: var MD5Context) =
|
||||||
c.state[3] = 0x10325476'u32
|
c.state[3] = 0x10325476'u32
|
||||||
c.count[0] = 0'u32
|
c.count[0] = 0'u32
|
||||||
c.count[1] = 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) =
|
proc md5Update*(c: var MD5Context, input: cstring, len: int) =
|
||||||
## Updates the `MD5Context` with the `input` data of length `len`.
|
## 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") ==
|
assert(getMD5("Frank jagt im komplett verwahrlosten Taxi quer durch Bayern") ==
|
||||||
"7e716d0e702df0505fc72e2b89467910")
|
"7e716d0e702df0505fc72e2b89467910")
|
||||||
assert($toMD5("") == "d41d8cd98f00b204e9800998ecf8427e")
|
assert($toMD5("") == "d41d8cd98f00b204e9800998ecf8427e")
|
||||||
|
|
||||||
|
when defined(nimHasStyleChecks):
|
||||||
|
{.pop.} #{.push styleChecks: off.}
|
||||||
|
|
|
||||||
|
|
@ -354,11 +354,11 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} =
|
||||||
else:
|
else:
|
||||||
raiseOSError(osLastError(), "unknown h_addrtype")
|
raiseOSError(osLastError(), "unknown h_addrtype")
|
||||||
if result.addrtype == AF_INET:
|
if result.addrtype == AF_INET:
|
||||||
result.addrlist = @[]
|
result.addrList = @[]
|
||||||
var i = 0
|
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])
|
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)
|
inc(i)
|
||||||
else:
|
else:
|
||||||
result.addrList = cstringArrayToSeq(s.h_addr_list)
|
result.addrList = cstringArrayToSeq(s.h_addr_list)
|
||||||
|
|
@ -383,11 +383,11 @@ proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} =
|
||||||
else:
|
else:
|
||||||
raiseOSError(osLastError(), "unknown h_addrtype")
|
raiseOSError(osLastError(), "unknown h_addrtype")
|
||||||
if result.addrtype == AF_INET:
|
if result.addrtype == AF_INET:
|
||||||
result.addrlist = @[]
|
result.addrList = @[]
|
||||||
var i = 0
|
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])
|
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)
|
inc(i)
|
||||||
else:
|
else:
|
||||||
result.addrList = cstringArrayToSeq(s.h_addr_list)
|
result.addrList = cstringArrayToSeq(s.h_addr_list)
|
||||||
|
|
@ -400,7 +400,7 @@ proc getHostname*(): string {.tags: [ReadIOEffect].} =
|
||||||
const size = 64
|
const size = 64
|
||||||
result = newString(size)
|
result = newString(size)
|
||||||
when useWinVersion:
|
when useWinVersion:
|
||||||
let success = winlean.getHostname(result, size)
|
let success = winlean.gethostname(result, size)
|
||||||
else:
|
else:
|
||||||
# Posix
|
# Posix
|
||||||
let success = posix.getHostname(result, size)
|
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
|
## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
|
||||||
## an unlimited time.
|
## an unlimited time.
|
||||||
var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
|
var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
|
||||||
|
|
||||||
var rd: TFdSet
|
var rd: TFdSet
|
||||||
var m = 0
|
var m = 0
|
||||||
|
|
@ -635,7 +635,7 @@ proc selectWrite*(writefds: var seq[SocketHandle],
|
||||||
##
|
##
|
||||||
## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
|
## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
|
||||||
## an unlimited time.
|
## an unlimited time.
|
||||||
var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
|
var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
|
||||||
|
|
||||||
var wr: TFdSet
|
var wr: TFdSet
|
||||||
var m = 0
|
var m = 0
|
||||||
|
|
|
||||||
|
|
@ -398,35 +398,35 @@ proc isIpAddress*(addressStr: string): bool {.tags: [].} =
|
||||||
return true
|
return true
|
||||||
|
|
||||||
proc toSockAddr*(address: IpAddress, port: Port, sa: var Sockaddr_storage,
|
proc toSockAddr*(address: IpAddress, port: Port, sa: var Sockaddr_storage,
|
||||||
sl: var Socklen) =
|
sl: var SockLen) =
|
||||||
## Converts `IpAddress` and `Port` to `SockAddr` and `Socklen`
|
## Converts `IpAddress` and `Port` to `SockAddr` and `Socklen`
|
||||||
let port = htons(uint16(port))
|
let port = htons(uint16(port))
|
||||||
case address.family
|
case address.family
|
||||||
of IpAddressFamily.IPv4:
|
of IpAddressFamily.IPv4:
|
||||||
sl = sizeof(Sockaddr_in).Socklen
|
sl = sizeof(Sockaddr_in).SockLen
|
||||||
let s = cast[ptr Sockaddr_in](addr sa)
|
let s = cast[ptr Sockaddr_in](addr sa)
|
||||||
s.sin_family = type(s.sin_family)(toInt(AF_INET))
|
s.sin_family = type(s.sin_family)(toInt(AF_INET))
|
||||||
s.sin_port = port
|
s.sin_port = port
|
||||||
copyMem(addr s.sin_addr, unsafeAddr address.address_v4[0],
|
copyMem(addr s.sin_addr, unsafeAddr address.address_v4[0],
|
||||||
sizeof(s.sin_addr))
|
sizeof(s.sin_addr))
|
||||||
of IpAddressFamily.IPv6:
|
of IpAddressFamily.IPv6:
|
||||||
sl = sizeof(Sockaddr_in6).Socklen
|
sl = sizeof(Sockaddr_in6).SockLen
|
||||||
let s = cast[ptr Sockaddr_in6](addr sa)
|
let s = cast[ptr Sockaddr_in6](addr sa)
|
||||||
s.sin6_family = type(s.sin6_family)(toInt(AF_INET6))
|
s.sin6_family = type(s.sin6_family)(toInt(AF_INET6))
|
||||||
s.sin6_port = port
|
s.sin6_port = port
|
||||||
copyMem(addr s.sin6_addr, unsafeAddr address.address_v6[0],
|
copyMem(addr s.sin6_addr, unsafeAddr address.address_v6[0],
|
||||||
sizeof(s.sin6_addr))
|
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) =
|
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)
|
address = IpAddress(family: IpAddressFamily.IPv4)
|
||||||
let s = cast[ptr Sockaddr_in](sa)
|
let s = cast[ptr Sockaddr_in](sa)
|
||||||
copyMem(addr address.address_v4[0], addr s.sin_addr,
|
copyMem(addr address.address_v4[0], addr s.sin_addr,
|
||||||
sizeof(address.address_v4))
|
sizeof(address.address_v4))
|
||||||
port = ntohs(s.sin_port).Port
|
port = ntohs(s.sin_port).Port
|
||||||
elif sa.ss_family.cint == toInt(AF_INET6) and
|
elif sa.ss_family.cint == toInt(AF_INET6) and
|
||||||
sl == sizeof(Sockaddr_in6).Socklen:
|
sl == sizeof(Sockaddr_in6).SockLen:
|
||||||
address = IpAddress(family: IpAddressFamily.IPv6)
|
address = IpAddress(family: IpAddressFamily.IPv6)
|
||||||
let s = cast[ptr Sockaddr_in6](sa)
|
let s = cast[ptr Sockaddr_in6](sa)
|
||||||
copyMem(addr address.address_v6[0], addr s.sin6_addr,
|
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")
|
raise newException(ValueError, "Neither IPv4 nor IPv6")
|
||||||
|
|
||||||
proc fromSockAddr*(sa: Sockaddr_storage | SockAddr | Sockaddr_in | Sockaddr_in6,
|
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
|
## Converts `SockAddr` and `Socklen` to `IpAddress` and `Port`. Raises
|
||||||
## `ObjectConversionError` in case of invalid `sa` and `sl` arguments.
|
## `ObjectConversionError` in case of invalid `sa` and `sl` arguments.
|
||||||
fromSockAddrAux(cast[ptr Sockaddr_storage](unsafeAddr sa), sl, address, port)
|
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)
|
var aiList = getAddrInfo(realaddr, port, socket.domain)
|
||||||
if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
|
if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
|
||||||
freeAddrInfo(aiList)
|
freeaddrinfo(aiList)
|
||||||
raiseOSError(osLastError())
|
raiseOSError(osLastError())
|
||||||
freeAddrInfo(aiList)
|
freeaddrinfo(aiList)
|
||||||
|
|
||||||
proc acceptAddr*(server: Socket, client: var owned(Socket), address: var string,
|
proc acceptAddr*(server: Socket, client: var owned(Socket), address: var string,
|
||||||
flags = {SocketFlag.SafeDisconn}) {.
|
flags = {SocketFlag.SafeDisconn}) {.
|
||||||
|
|
@ -1378,7 +1378,7 @@ proc sendTo*(socket: Socket, address: string, port: Port, data: pointer,
|
||||||
it = it.ai_next
|
it = it.ai_next
|
||||||
|
|
||||||
let osError = osLastError()
|
let osError = osLastError()
|
||||||
freeAddrInfo(aiList)
|
freeaddrinfo(aiList)
|
||||||
|
|
||||||
if not success:
|
if not success:
|
||||||
raiseOSError(osError)
|
raiseOSError(osError)
|
||||||
|
|
@ -1405,6 +1405,9 @@ proc isSsl*(socket: Socket): bool =
|
||||||
proc getFd*(socket: Socket): SocketHandle = return socket.fd
|
proc getFd*(socket: Socket): SocketHandle = return socket.fd
|
||||||
## Returns the socket's file descriptor
|
## Returns the socket's file descriptor
|
||||||
|
|
||||||
|
when defined(nimHasStyleChecks):
|
||||||
|
{.push styleChecks: off.}
|
||||||
|
|
||||||
proc IPv4_any*(): IpAddress =
|
proc IPv4_any*(): IpAddress =
|
||||||
## Returns the IPv4 any address, which can be used to listen on all available
|
## Returns the IPv4 any address, which can be used to listen on all available
|
||||||
## network adapters
|
## network adapters
|
||||||
|
|
@ -1437,6 +1440,9 @@ proc IPv6_loopback*(): IpAddress =
|
||||||
family: IpAddressFamily.IPv6,
|
family: IpAddressFamily.IPv6,
|
||||||
address_v6: [0'u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
|
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 =
|
proc `==`*(lhs, rhs: IpAddress): bool =
|
||||||
## Compares two IpAddresses for Equality. Returns true if the addresses are equal
|
## Compares two IpAddresses for Equality. Returns true if the addresses are equal
|
||||||
if lhs.family != rhs.family: return false
|
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
|
# network system problem (e.g. not enough FDs), and not an unreachable
|
||||||
# address.
|
# address.
|
||||||
let err = osLastError()
|
let err = osLastError()
|
||||||
freeAddrInfo(aiList)
|
freeaddrinfo(aiList)
|
||||||
closeUnusedFds()
|
closeUnusedFds()
|
||||||
raiseOSError(err)
|
raiseOSError(err)
|
||||||
fdPerDomain[ord(domain)] = lastFd
|
fdPerDomain[ord(domain)] = lastFd
|
||||||
|
|
@ -1556,7 +1562,7 @@ proc dial*(address: string, port: Port,
|
||||||
break
|
break
|
||||||
lastError = osLastError()
|
lastError = osLastError()
|
||||||
it = it.ai_next
|
it = it.ai_next
|
||||||
freeAddrInfo(aiList)
|
freeaddrinfo(aiList)
|
||||||
closeUnusedFds(ord(domain))
|
closeUnusedFds(ord(domain))
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
|
|
@ -1586,7 +1592,7 @@ proc connect*(socket: Socket, address: string,
|
||||||
else: lastError = osLastError()
|
else: lastError = osLastError()
|
||||||
it = it.ai_next
|
it = it.ai_next
|
||||||
|
|
||||||
freeAddrInfo(aiList)
|
freeaddrinfo(aiList)
|
||||||
if not success: raiseOSError(lastError)
|
if not success: raiseOSError(lastError)
|
||||||
|
|
||||||
when defineSsl:
|
when defineSsl:
|
||||||
|
|
@ -1634,7 +1640,7 @@ proc connectAsync(socket: Socket, name: string, port = Port(0),
|
||||||
|
|
||||||
it = it.ai_next
|
it = it.ai_next
|
||||||
|
|
||||||
freeAddrInfo(aiList)
|
freeaddrinfo(aiList)
|
||||||
if not success: raiseOSError(lastError)
|
if not success: raiseOSError(lastError)
|
||||||
|
|
||||||
proc connect*(socket: Socket, address: string, port = Port(0),
|
proc connect*(socket: Socket, address: string, port = Port(0),
|
||||||
|
|
|
||||||
|
|
@ -934,13 +934,13 @@ when defined(windows) and not weirdTarget:
|
||||||
template getCommandLine(): untyped = getCommandLineW()
|
template getCommandLine(): untyped = getCommandLineW()
|
||||||
|
|
||||||
template getFilename(f: untyped): untyped =
|
template getFilename(f: untyped): untyped =
|
||||||
$cast[WideCString](addr(f.cFilename[0]))
|
$cast[WideCString](addr(f.cFileName[0]))
|
||||||
else:
|
else:
|
||||||
template findFirstFile(a, b: untyped): untyped = findFirstFileA(a, b)
|
template findFirstFile(a, b: untyped): untyped = findFirstFileA(a, b)
|
||||||
template findNextFile(a, b: untyped): untyped = findNextFileA(a, b)
|
template findNextFile(a, b: untyped): untyped = findNextFileA(a, b)
|
||||||
template getCommandLine(): untyped = getCommandLineA()
|
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.} =
|
proc skipFindData(f: WIN32_FIND_DATA): bool {.inline.} =
|
||||||
# Note - takes advantage of null delimiter in the cstring
|
# Note - takes advantage of null delimiter in the cstring
|
||||||
|
|
@ -1035,7 +1035,7 @@ const
|
||||||
when defined(windows): ["exe", "cmd", "bat"] else: [""]
|
when defined(windows): ["exe", "cmd", "bat"] else: [""]
|
||||||
|
|
||||||
proc findExe*(exe: string, followSymlinks: bool = true;
|
proc findExe*(exe: string, followSymlinks: bool = true;
|
||||||
extensions: openarray[string]=ExeExts): string {.
|
extensions: openArray[string]=ExeExts): string {.
|
||||||
tags: [ReadDirEffect, ReadEnvEffect, ReadIOEffect], noNimScript.} =
|
tags: [ReadDirEffect, ReadEnvEffect, ReadIOEffect], noNimScript.} =
|
||||||
## Searches for `exe` in the current working directory and then
|
## Searches for `exe` in the current working directory and then
|
||||||
## in directories listed in the ``PATH`` environment variable.
|
## in directories listed in the ``PATH`` environment variable.
|
||||||
|
|
@ -2867,7 +2867,7 @@ template rawToFormalFileInfo(rawInfo, path, formalInfo): untyped =
|
||||||
formalInfo.permissions.incl(formalMode)
|
formalInfo.permissions.incl(formalMode)
|
||||||
formalInfo.id = (rawInfo.st_dev, rawInfo.st_ino)
|
formalInfo.id = (rawInfo.st_dev, rawInfo.st_ino)
|
||||||
formalInfo.size = rawInfo.st_size
|
formalInfo.size = rawInfo.st_size
|
||||||
formalInfo.linkCount = rawInfo.st_Nlink.BiggestInt
|
formalInfo.linkCount = rawInfo.st_nlink.BiggestInt
|
||||||
formalInfo.lastAccessTime = rawInfo.st_atim.toTime
|
formalInfo.lastAccessTime = rawInfo.st_atim.toTime
|
||||||
formalInfo.lastWriteTime = rawInfo.st_mtim.toTime
|
formalInfo.lastWriteTime = rawInfo.st_mtim.toTime
|
||||||
formalInfo.creationTime = rawInfo.st_ctim.toTime
|
formalInfo.creationTime = rawInfo.st_ctim.toTime
|
||||||
|
|
|
||||||
|
|
@ -501,7 +501,7 @@ when defined(Windows) and not defined(useNimRtl):
|
||||||
#var
|
#var
|
||||||
# O_WRONLY {.importc: "_O_WRONLY", header: "<fcntl.h>".}: int
|
# O_WRONLY {.importc: "_O_WRONLY", header: "<fcntl.h>".}: int
|
||||||
# O_RDONLY {.importc: "_O_RDONLY", 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()
|
let thisProc = getCurrentProcess()
|
||||||
if duplicateHandle(thisProc, h,
|
if duplicateHandle(thisProc, h,
|
||||||
thisProc, addr result,0,inherit,
|
thisProc, addr result,0,inherit,
|
||||||
|
|
@ -594,11 +594,11 @@ when defined(Windows) and not defined(useNimRtl):
|
||||||
else:
|
else:
|
||||||
createPipeHandles(he, si.hStdError)
|
createPipeHandles(he, si.hStdError)
|
||||||
if setHandleInformation(he, DWORD(1), DWORD(0)) == 0'i32:
|
if setHandleInformation(he, DWORD(1), DWORD(0)) == 0'i32:
|
||||||
raiseOsError(osLastError())
|
raiseOSError(osLastError())
|
||||||
if setHandleInformation(hi, DWORD(1), DWORD(0)) == 0'i32:
|
if setHandleInformation(hi, DWORD(1), DWORD(0)) == 0'i32:
|
||||||
raiseOsError(osLastError())
|
raiseOSError(osLastError())
|
||||||
if setHandleInformation(ho, DWORD(1), DWORD(0)) == 0'i32:
|
if setHandleInformation(ho, DWORD(1), DWORD(0)) == 0'i32:
|
||||||
raiseOsError(osLastError())
|
raiseOSError(osLastError())
|
||||||
else:
|
else:
|
||||||
createAllPipeHandles(si, hi, ho, he, cast[int](result))
|
createAllPipeHandles(si, hi, ho, he, cast[int](result))
|
||||||
result.inHandle = FileHandle(hi)
|
result.inHandle = FileHandle(hi)
|
||||||
|
|
@ -1086,10 +1086,10 @@ elif not defined(useNimRtl):
|
||||||
discard close(p.errHandle)
|
discard close(p.errHandle)
|
||||||
|
|
||||||
proc suspend(p: Process) =
|
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) =
|
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 =
|
proc running(p: Process): bool =
|
||||||
if p.exitFlag:
|
if p.exitFlag:
|
||||||
|
|
@ -1111,11 +1111,11 @@ elif not defined(useNimRtl):
|
||||||
|
|
||||||
proc terminate(p: Process) =
|
proc terminate(p: Process) =
|
||||||
if kill(p.id, SIGTERM) != 0'i32:
|
if kill(p.id, SIGTERM) != 0'i32:
|
||||||
raiseOsError(osLastError())
|
raiseOSError(osLastError())
|
||||||
|
|
||||||
proc kill(p: Process) =
|
proc kill(p: Process) =
|
||||||
if kill(p.id, SIGKILL) != 0'i32:
|
if kill(p.id, SIGKILL) != 0'i32:
|
||||||
raiseOsError(osLastError())
|
raiseOSError(osLastError())
|
||||||
|
|
||||||
when defined(macosx) or defined(freebsd) or defined(netbsd) or
|
when defined(macosx) or defined(freebsd) or defined(netbsd) or
|
||||||
defined(openbsd) or defined(dragonfly):
|
defined(openbsd) or defined(dragonfly):
|
||||||
|
|
|
||||||
|
|
@ -505,7 +505,7 @@ proc formatValue*(result: var string; value: string; specifier: string) =
|
||||||
"invalid type in format string for string, expected 's', but got " &
|
"invalid type in format string for string, expected 's', but got " &
|
||||||
spec.typ)
|
spec.typ)
|
||||||
if spec.precision != -1:
|
if spec.precision != -1:
|
||||||
if spec.precision < runelen(value):
|
if spec.precision < runeLen(value):
|
||||||
setLen(value, runeOffset(value, spec.precision))
|
setLen(value, runeOffset(value, spec.precision))
|
||||||
result.add alignString(value, spec.minimumWidth, spec.align, spec.fill)
|
result.add alignString(value, spec.minimumWidth, spec.align, spec.fill)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -115,7 +115,7 @@ const
|
||||||
IdentStartChars* = {'a'..'z', 'A'..'Z', '_'}
|
IdentStartChars* = {'a'..'z', 'A'..'Z', '_'}
|
||||||
## the set of characters an identifier can start with
|
## 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
|
## the set of characters a newline terminator can start with (carriage
|
||||||
## return, line feed)
|
## return, line feed)
|
||||||
|
|
||||||
|
|
@ -2360,7 +2360,7 @@ proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault,
|
||||||
for i in 0 ..< L:
|
for i in 0 ..< L:
|
||||||
# Depending on the locale either dot or comma is produced,
|
# Depending on the locale either dot or comma is produced,
|
||||||
# but nothing else is possible:
|
# but nothing else is possible:
|
||||||
if buf[i] in {'.', ','}: result[i] = decimalsep
|
if buf[i] in {'.', ','}: result[i] = decimalSep
|
||||||
else: result[i] = buf[i]
|
else: result[i] = buf[i]
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
# VS pre 2015 violates the C standard: "The exponent always contains at
|
# VS pre 2015 violates the C standard: "The exponent always contains at
|
||||||
|
|
@ -2447,7 +2447,7 @@ proc formatSize*(bytes: int64,
|
||||||
var
|
var
|
||||||
xb: int64 = bytes
|
xb: int64 = bytes
|
||||||
fbytes: float
|
fbytes: float
|
||||||
last_xb: int64 = bytes
|
lastXb: int64 = bytes
|
||||||
matchedIndex: int
|
matchedIndex: int
|
||||||
prefixes: array[9, string]
|
prefixes: array[9, string]
|
||||||
if prefix == bpColloquial:
|
if prefix == bpColloquial:
|
||||||
|
|
@ -2458,11 +2458,11 @@ proc formatSize*(bytes: int64,
|
||||||
# Iterate through prefixes seeing if value will be greater than
|
# Iterate through prefixes seeing if value will be greater than
|
||||||
# 0 in each case
|
# 0 in each case
|
||||||
for index in 1..<prefixes.len:
|
for index in 1..<prefixes.len:
|
||||||
last_xb = xb
|
lastXb = xb
|
||||||
xb = bytes div (1'i64 shl (index*10))
|
xb = bytes div (1'i64 shl (index*10))
|
||||||
matchedIndex = index
|
matchedIndex = index
|
||||||
if xb == 0:
|
if xb == 0:
|
||||||
xb = last_xb
|
xb = lastXb
|
||||||
matchedIndex = index - 1
|
matchedIndex = index - 1
|
||||||
break
|
break
|
||||||
# xb has the integer number for the latest value; index should be correct
|
# 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:
|
for i in 1 .. len1 - 1:
|
||||||
var char1 = a[i + s - 1]
|
var char1 = a[i + s - 1]
|
||||||
var char2p: int
|
var char2p: int
|
||||||
var D, x: int
|
var diff, x: int
|
||||||
var p: int
|
var p: int
|
||||||
if i >= len1 - half:
|
if i >= len1 - half:
|
||||||
# skip the upper triangle:
|
# skip the upper triangle:
|
||||||
|
|
@ -2913,33 +2913,33 @@ proc editDistance*(a, b: string): int {.noSideEffect,
|
||||||
inc(p)
|
inc(p)
|
||||||
inc(char2p)
|
inc(char2p)
|
||||||
x = row[p] + 1
|
x = row[p] + 1
|
||||||
D = x
|
diff = x
|
||||||
if x > c3: x = c3
|
if x > c3: x = c3
|
||||||
row[p] = x
|
row[p] = x
|
||||||
inc(p)
|
inc(p)
|
||||||
else:
|
else:
|
||||||
p = 1
|
p = 1
|
||||||
char2p = 0
|
char2p = 0
|
||||||
D = i
|
diff = i
|
||||||
x = i
|
x = i
|
||||||
if i <= half + 1:
|
if i <= half + 1:
|
||||||
# skip the lower triangle:
|
# skip the lower triangle:
|
||||||
e = len2 + i - half - 2
|
e = len2 + i - half - 2
|
||||||
# main:
|
# main:
|
||||||
while p <= e:
|
while p <= e:
|
||||||
dec(D)
|
dec(diff)
|
||||||
var c3 = D + ord(char1 != b[char2p + s])
|
var c3 = diff + ord(char1 != b[char2p + s])
|
||||||
inc(char2p)
|
inc(char2p)
|
||||||
inc(x)
|
inc(x)
|
||||||
if x > c3: x = c3
|
if x > c3: x = c3
|
||||||
D = row[p] + 1
|
diff = row[p] + 1
|
||||||
if x > D: x = D
|
if x > diff: x = diff
|
||||||
row[p] = x
|
row[p] = x
|
||||||
inc(p)
|
inc(p)
|
||||||
# lower triangle sentinel:
|
# lower triangle sentinel:
|
||||||
if i <= half:
|
if i <= half:
|
||||||
dec(D)
|
dec(diff)
|
||||||
var c3 = D + ord(char1 != b[char2p + s])
|
var c3 = diff + ord(char1 != b[char2p + s])
|
||||||
inc(x)
|
inc(x)
|
||||||
if x > c3: x = c3
|
if x > c3: x = c3
|
||||||
row[p] = x
|
row[p] = x
|
||||||
|
|
|
||||||
|
|
@ -91,22 +91,22 @@ when defined(windows):
|
||||||
dwSize: DWORD
|
dwSize: DWORD
|
||||||
bVisible: WINBOOL
|
bVisible: WINBOOL
|
||||||
|
|
||||||
proc duplicateHandle(hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE,
|
proc duplicateHandle(hSourceProcessHandle: Handle, hSourceHandle: Handle,
|
||||||
hTargetProcessHandle: HANDLE, lpTargetHandle: ptr HANDLE,
|
hTargetProcessHandle: Handle, lpTargetHandle: ptr Handle,
|
||||||
dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
|
dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
|
||||||
dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32",
|
dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32",
|
||||||
importc: "DuplicateHandle".}
|
importc: "DuplicateHandle".}
|
||||||
proc getCurrentProcess(): HANDLE{.stdcall, dynlib: "kernel32",
|
proc getCurrentProcess(): Handle{.stdcall, dynlib: "kernel32",
|
||||||
importc: "GetCurrentProcess".}
|
importc: "GetCurrentProcess".}
|
||||||
proc getConsoleScreenBufferInfo(hConsoleOutput: HANDLE,
|
proc getConsoleScreenBufferInfo(hConsoleOutput: Handle,
|
||||||
lpConsoleScreenBufferInfo: ptr CONSOLE_SCREEN_BUFFER_INFO): WINBOOL{.stdcall,
|
lpConsoleScreenBufferInfo: ptr CONSOLE_SCREEN_BUFFER_INFO): WINBOOL{.stdcall,
|
||||||
dynlib: "kernel32", importc: "GetConsoleScreenBufferInfo".}
|
dynlib: "kernel32", importc: "GetConsoleScreenBufferInfo".}
|
||||||
|
|
||||||
proc getConsoleCursorInfo(hConsoleOutput: HANDLE,
|
proc getConsoleCursorInfo(hConsoleOutput: Handle,
|
||||||
lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
|
lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
|
||||||
stdcall, dynlib: "kernel32", importc: "GetConsoleCursorInfo".}
|
stdcall, dynlib: "kernel32", importc: "GetConsoleCursorInfo".}
|
||||||
|
|
||||||
proc setConsoleCursorInfo(hConsoleOutput: HANDLE,
|
proc setConsoleCursorInfo(hConsoleOutput: Handle,
|
||||||
lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
|
lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
|
||||||
stdcall, dynlib: "kernel32", importc: "SetConsoleCursorInfo".}
|
stdcall, dynlib: "kernel32", importc: "SetConsoleCursorInfo".}
|
||||||
|
|
||||||
|
|
@ -140,21 +140,21 @@ when defined(windows):
|
||||||
if h > 0: return h
|
if h > 0: return h
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
proc setConsoleCursorPosition(hConsoleOutput: HANDLE,
|
proc setConsoleCursorPosition(hConsoleOutput: Handle,
|
||||||
dwCursorPosition: COORD): WINBOOL{.
|
dwCursorPosition: COORD): WINBOOL{.
|
||||||
stdcall, dynlib: "kernel32", importc: "SetConsoleCursorPosition".}
|
stdcall, dynlib: "kernel32", importc: "SetConsoleCursorPosition".}
|
||||||
|
|
||||||
proc fillConsoleOutputCharacter(hConsoleOutput: Handle, cCharacter: char,
|
proc fillConsoleOutputCharacter(hConsoleOutput: Handle, cCharacter: char,
|
||||||
nLength: DWORD, dwWriteCoord: Coord,
|
nLength: DWORD, dwWriteCoord: COORD,
|
||||||
lpNumberOfCharsWritten: ptr DWORD): WINBOOL{.
|
lpNumberOfCharsWritten: ptr DWORD): WINBOOL{.
|
||||||
stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".}
|
stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".}
|
||||||
|
|
||||||
proc fillConsoleOutputAttribute(hConsoleOutput: HANDLE, wAttribute: int16,
|
proc fillConsoleOutputAttribute(hConsoleOutput: Handle, wAttribute: int16,
|
||||||
nLength: DWORD, dwWriteCoord: COORD,
|
nLength: DWORD, dwWriteCoord: COORD,
|
||||||
lpNumberOfAttrsWritten: ptr DWORD): WINBOOL{.
|
lpNumberOfAttrsWritten: ptr DWORD): WINBOOL{.
|
||||||
stdcall, dynlib: "kernel32", importc: "FillConsoleOutputAttribute".}
|
stdcall, dynlib: "kernel32", importc: "FillConsoleOutputAttribute".}
|
||||||
|
|
||||||
proc setConsoleTextAttribute(hConsoleOutput: HANDLE,
|
proc setConsoleTextAttribute(hConsoleOutput: Handle,
|
||||||
wAttributes: int16): WINBOOL{.
|
wAttributes: int16): WINBOOL{.
|
||||||
stdcall, dynlib: "kernel32", importc: "SetConsoleTextAttribute".}
|
stdcall, dynlib: "kernel32", importc: "SetConsoleTextAttribute".}
|
||||||
|
|
||||||
|
|
@ -165,7 +165,7 @@ when defined(windows):
|
||||||
stdcall, dynlib: "kernel32", importc: "SetConsoleMode".}
|
stdcall, dynlib: "kernel32", importc: "SetConsoleMode".}
|
||||||
|
|
||||||
proc getCursorPos(h: Handle): tuple [x,y: int] =
|
proc getCursorPos(h: Handle): tuple [x,y: int] =
|
||||||
var c: CONSOLESCREENBUFFERINFO
|
var c: CONSOLE_SCREEN_BUFFER_INFO
|
||||||
if getConsoleScreenBufferInfo(h, addr(c)) == 0:
|
if getConsoleScreenBufferInfo(h, addr(c)) == 0:
|
||||||
raiseOSError(osLastError())
|
raiseOSError(osLastError())
|
||||||
return (int(c.dwCursorPosition.X), int(c.dwCursorPosition.Y))
|
return (int(c.dwCursorPosition.X), int(c.dwCursorPosition.Y))
|
||||||
|
|
@ -178,7 +178,7 @@ when defined(windows):
|
||||||
raiseOSError(osLastError())
|
raiseOSError(osLastError())
|
||||||
|
|
||||||
proc getAttributes(h: Handle): int16 =
|
proc getAttributes(h: Handle): int16 =
|
||||||
var c: CONSOLESCREENBUFFERINFO
|
var c: CONSOLE_SCREEN_BUFFER_INFO
|
||||||
# workaround Windows bugs: try several times
|
# workaround Windows bugs: try several times
|
||||||
if getConsoleScreenBufferInfo(h, addr(c)) != 0:
|
if getConsoleScreenBufferInfo(h, addr(c)) != 0:
|
||||||
return c.wAttributes
|
return c.wAttributes
|
||||||
|
|
@ -207,7 +207,7 @@ else:
|
||||||
|
|
||||||
proc setRaw(fd: FileHandle, time: cint = TCSAFLUSH) =
|
proc setRaw(fd: FileHandle, time: cint = TCSAFLUSH) =
|
||||||
var mode: Termios
|
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
|
mode.c_iflag = mode.c_iflag and not Cflag(BRKINT or ICRNL or INPCK or
|
||||||
ISTRIP or IXON)
|
ISTRIP or IXON)
|
||||||
mode.c_oflag = mode.c_oflag and not Cflag(OPOST)
|
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_lflag = mode.c_lflag and not Cflag(ECHO or ICANON or IEXTEN or ISIG)
|
||||||
mode.c_cc[VMIN] = 1.cuchar
|
mode.c_cc[VMIN] = 1.cuchar
|
||||||
mode.c_cc[VTIME] = 0.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 =
|
proc terminalWidthIoctl*(fds: openArray[int]): int =
|
||||||
## Returns terminal width from first fd that supports the ioctl.
|
## 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.
|
## The y position is not changed.
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
let h = conHandle(f)
|
let h = conHandle(f)
|
||||||
var scrbuf: CONSOLESCREENBUFFERINFO
|
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
|
||||||
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
|
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
|
||||||
raiseOSError(osLastError())
|
raiseOSError(osLastError())
|
||||||
var origin = scrbuf.dwCursorPosition
|
var origin = scrbuf.dwCursorPosition
|
||||||
|
|
@ -332,7 +332,7 @@ when defined(windows):
|
||||||
## **Warning**: This is not supported on UNIX!
|
## **Warning**: This is not supported on UNIX!
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
let h = conHandle(f)
|
let h = conHandle(f)
|
||||||
var scrbuf: CONSOLESCREENBUFFERINFO
|
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
|
||||||
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
|
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
|
||||||
raiseOSError(osLastError())
|
raiseOSError(osLastError())
|
||||||
var origin = scrbuf.dwCursorPosition
|
var origin = scrbuf.dwCursorPosition
|
||||||
|
|
@ -417,7 +417,7 @@ proc eraseLine*(f: File) =
|
||||||
## Erases the entire current line.
|
## Erases the entire current line.
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
let h = conHandle(f)
|
let h = conHandle(f)
|
||||||
var scrbuf: CONSOLESCREENBUFFERINFO
|
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
|
||||||
var numwrote: DWORD
|
var numwrote: DWORD
|
||||||
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
|
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
|
||||||
raiseOSError(osLastError())
|
raiseOSError(osLastError())
|
||||||
|
|
@ -440,7 +440,7 @@ proc eraseScreen*(f: File) =
|
||||||
## Erases the screen with the background colour and moves the cursor to home.
|
## Erases the screen with the background colour and moves the cursor to home.
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
let h = conHandle(f)
|
let h = conHandle(f)
|
||||||
var scrbuf: CONSOLESCREENBUFFERINFO
|
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
|
||||||
var numwrote: DWORD
|
var numwrote: DWORD
|
||||||
var origin: COORD # is inititalized to 0, 0
|
var origin: COORD # is inititalized to 0, 0
|
||||||
|
|
||||||
|
|
@ -759,10 +759,10 @@ proc getch*(): char =
|
||||||
else:
|
else:
|
||||||
let fd = getFileHandle(stdin)
|
let fd = getFileHandle(stdin)
|
||||||
var oldMode: Termios
|
var oldMode: Termios
|
||||||
discard fd.tcgetattr(addr oldMode)
|
discard fd.tcGetAttr(addr oldMode)
|
||||||
fd.setRaw()
|
fd.setRaw()
|
||||||
result = stdin.readChar()
|
result = stdin.readChar()
|
||||||
discard fd.tcsetattr(TCSADRAIN, addr oldMode)
|
discard fd.tcSetAttr(TCSADRAIN, addr oldMode)
|
||||||
|
|
||||||
when defined(windows):
|
when defined(windows):
|
||||||
from unicode import toUTF8, Rune, runeLenAt
|
from unicode import toUTF8, Rune, runeLenAt
|
||||||
|
|
@ -803,14 +803,14 @@ else:
|
||||||
password.string.setLen(0)
|
password.string.setLen(0)
|
||||||
let fd = stdin.getFileHandle()
|
let fd = stdin.getFileHandle()
|
||||||
var cur, old: Termios
|
var cur, old: Termios
|
||||||
discard fd.tcgetattr(cur.addr)
|
discard fd.tcGetAttr(cur.addr)
|
||||||
old = cur
|
old = cur
|
||||||
cur.c_lflag = cur.c_lflag and not Cflag(ECHO)
|
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
|
stdout.write prompt
|
||||||
result = stdin.readLine(password)
|
result = stdin.readLine(password)
|
||||||
stdout.write "\n"
|
stdout.write "\n"
|
||||||
discard fd.tcsetattr(TCSADRAIN, old.addr)
|
discard fd.tcSetAttr(TCSADRAIN, old.addr)
|
||||||
|
|
||||||
proc readPasswordFromStdin*(prompt = "password: "): TaintedString =
|
proc readPasswordFromStdin*(prompt = "password: "): TaintedString =
|
||||||
## Reads a password from stdin without printing it.
|
## Reads a password from stdin without printing it.
|
||||||
|
|
|
||||||
|
|
@ -222,9 +222,9 @@ elif defined(posix):
|
||||||
type CTime = posix.Time
|
type CTime = posix.Time
|
||||||
|
|
||||||
var
|
var
|
||||||
realTimeClockId {.importc: "CLOCK_REALTIME", header: "<time.h>".}: Clockid
|
realTimeClockId {.importc: "CLOCK_REALTIME", header: "<time.h>".}: ClockId
|
||||||
cpuClockId
|
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):
|
when not defined(freebsd) and not defined(netbsd) and not defined(openbsd):
|
||||||
var timezone {.importc, header: "<time.h>".}: int
|
var timezone {.importc, header: "<time.h>".}: int
|
||||||
|
|
@ -689,7 +689,7 @@ proc getDayOfWeek*(monthday: MonthdayRange, month: Month, year: int): WeekDay
|
||||||
|
|
||||||
assertValidDate monthday, month, year
|
assertValidDate monthday, month, year
|
||||||
# 1970-01-01 is a Thursday, we adjust to the previous Monday
|
# 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 weeks = floorDiv(days, 7)
|
||||||
let wd = days - weeks * 7
|
let wd = days - weeks * 7
|
||||||
# The value of d is 0 for a Sunday, 1 for a Monday, 2 for a Tuesday, etc.
|
# 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.} =
|
proc toTime*(dt: DateTime): Time {.tags: [], raises: [], benign.} =
|
||||||
## Converts a ``DateTime`` to a ``Time`` representing the same point in time.
|
## 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
|
var seconds = epochDay * secondsInDay
|
||||||
seconds.inc dt.hour * secondsInHour
|
seconds.inc dt.hour * secondsInHour
|
||||||
seconds.inc dt.minute * 60
|
seconds.inc dt.minute * 60
|
||||||
|
|
@ -950,7 +950,7 @@ proc initDateTime(zt: ZonedTime, zone: Timezone): DateTime =
|
||||||
rem = rem - minute * secondsInMin
|
rem = rem - minute * secondsInMin
|
||||||
let second = rem
|
let second = rem
|
||||||
|
|
||||||
let (d, m, y) = fromEpochday(epochday)
|
let (d, m, y) = fromEpochDay(epochday)
|
||||||
|
|
||||||
DateTime(
|
DateTime(
|
||||||
year: y,
|
year: y,
|
||||||
|
|
@ -1011,7 +1011,7 @@ proc zonedTimeFromTime*(zone: Timezone, time: Time): ZonedTime =
|
||||||
## Returns the ``ZonedTime`` for some point in time.
|
## Returns the ``ZonedTime`` for some point in time.
|
||||||
zone.zonedTimeFromTimeImpl(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.
|
## Returns the ``ZonedTime`` for some local time.
|
||||||
##
|
##
|
||||||
## Note that the ``Time`` argument does not represent a point in time, it
|
## 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)
|
dt.toTime.inZone(zone)
|
||||||
|
|
||||||
proc toAdjTime(dt: DateTime): Time =
|
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
|
var seconds = epochDay * secondsInDay
|
||||||
seconds.inc dt.hour * secondsInHour
|
seconds.inc dt.hour * secondsInHour
|
||||||
seconds.inc dt.minute * secondsInMin
|
seconds.inc dt.minute * secondsInMin
|
||||||
|
|
@ -1081,7 +1081,7 @@ when defined(JS):
|
||||||
|
|
||||||
else:
|
else:
|
||||||
proc toAdjUnix(tm: Tm): int64 =
|
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)
|
tm.tm_year.int + 1900)
|
||||||
result = epochDay * secondsInDay
|
result = epochDay * secondsInDay
|
||||||
result.inc tm.tm_hour * secondsInHour
|
result.inc tm.tm_hour * secondsInHour
|
||||||
|
|
@ -1147,7 +1147,7 @@ proc utcTzInfo(time: Time): ZonedTime =
|
||||||
var utcInstance {.threadvar.}: Timezone
|
var utcInstance {.threadvar.}: Timezone
|
||||||
var localInstance {.threadvar.}: Timezone
|
var localInstance {.threadvar.}: Timezone
|
||||||
|
|
||||||
proc utc*(): TimeZone =
|
proc utc*(): Timezone =
|
||||||
## Get the ``Timezone`` implementation for the UTC timezone.
|
## Get the ``Timezone`` implementation for the UTC timezone.
|
||||||
runnableExamples:
|
runnableExamples:
|
||||||
doAssert now().utc.timezone == utc()
|
doAssert now().utc.timezone == utc()
|
||||||
|
|
@ -1156,7 +1156,7 @@ proc utc*(): TimeZone =
|
||||||
utcInstance = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo)
|
utcInstance = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo)
|
||||||
result = utcInstance
|
result = utcInstance
|
||||||
|
|
||||||
proc local*(): TimeZone =
|
proc local*(): Timezone =
|
||||||
## Get the ``Timezone`` implementation for the local timezone.
|
## Get the ``Timezone`` implementation for the local timezone.
|
||||||
runnableExamples:
|
runnableExamples:
|
||||||
doAssert now().timezone == local()
|
doAssert now().timezone == local()
|
||||||
|
|
@ -1389,7 +1389,7 @@ proc evaluateInterval(dt: DateTime, interval: TimeInterval):
|
||||||
var curMonth = dt.month
|
var curMonth = dt.month
|
||||||
# Subtracting
|
# Subtracting
|
||||||
if months < 0:
|
if months < 0:
|
||||||
for mth in countDown(-1 * months, 1):
|
for mth in countdown(-1 * months, 1):
|
||||||
if curMonth == mJan:
|
if curMonth == mJan:
|
||||||
curMonth = mDec
|
curMonth = mDec
|
||||||
curYear.dec
|
curYear.dec
|
||||||
|
|
@ -2111,7 +2111,7 @@ proc parsePattern(input: string, pattern: FormatPattern, i: var int,
|
||||||
i.inc 1
|
i.inc 1
|
||||||
of tt:
|
of tt:
|
||||||
if input.substr(i, i+1).cmpIgnoreCase("AM") == 0:
|
if input.substr(i, i+1).cmpIgnoreCase("AM") == 0:
|
||||||
parsed.amPm = apAM
|
parsed.amPm = apAm
|
||||||
i.inc 2
|
i.inc 2
|
||||||
elif input.substr(i, i+1).cmpIgnoreCase("PM") == 0:
|
elif input.substr(i, i+1).cmpIgnoreCase("PM") == 0:
|
||||||
parsed.amPm = apPm
|
parsed.amPm = apPm
|
||||||
|
|
|
||||||
|
|
@ -169,7 +169,7 @@ proc runeAt*(s: string, i: Natural): Rune =
|
||||||
doAssert a.runeAt(3) == "y".runeAt(0)
|
doAssert a.runeAt(3) == "y".runeAt(0)
|
||||||
fastRuneAt(s, i, result, false)
|
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
|
## Returns the position of the invalid byte in ``s`` if the string ``s`` does
|
||||||
## not hold valid UTF-8 data. Otherwise ``-1`` is returned.
|
## 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``.
|
## with an additional amount equal to the byte length of ``c``.
|
||||||
##
|
##
|
||||||
## See also:
|
## See also:
|
||||||
## * `validateUTF8 proc <#validateUTF8,string>`_
|
## * `validateUtf8 proc <#validateUtf8,string>`_
|
||||||
## * `toUTF8 proc <#toUTF8,Rune>`_
|
## * `toUTF8 proc <#toUTF8,Rune>`_
|
||||||
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
|
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
|
||||||
var i = RuneImpl(c)
|
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.
|
## Converts a rune into its UTF-8 representation.
|
||||||
##
|
##
|
||||||
## See also:
|
## See also:
|
||||||
## * `validateUTF8 proc <#validateUTF8,string>`_
|
## * `validateUtf8 proc <#validateUtf8,string>`_
|
||||||
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
|
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
|
||||||
## * `utf8 iterator <#utf8.i,string>`_
|
## * `utf8 iterator <#utf8.i,string>`_
|
||||||
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
|
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
|
||||||
|
|
@ -287,7 +287,7 @@ proc `$`*(rune: Rune): string =
|
||||||
## An alias for `toUTF8 <#toUTF8,Rune>`_.
|
## An alias for `toUTF8 <#toUTF8,Rune>`_.
|
||||||
##
|
##
|
||||||
## See also:
|
## See also:
|
||||||
## * `validateUTF8 proc <#validateUTF8,string>`_
|
## * `validateUtf8 proc <#validateUtf8,string>`_
|
||||||
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
|
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
|
||||||
rune.toUTF8
|
rune.toUTF8
|
||||||
|
|
||||||
|
|
@ -487,12 +487,12 @@ proc toLower*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
|
||||||
## * `toTitle proc <#toTitle,Rune>`_
|
## * `toTitle proc <#toTitle,Rune>`_
|
||||||
## * `isLower proc <#isLower,Rune>`_
|
## * `isLower proc <#isLower,Rune>`_
|
||||||
var c = RuneImpl(c)
|
var c = RuneImpl(c)
|
||||||
var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
|
var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
|
||||||
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
|
if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
|
||||||
return Rune(c + tolowerRanges[p+2] - 500)
|
return Rune(c + toLowerRanges[p+2] - 500)
|
||||||
p = binarySearch(c, tolowerSinglets, len(tolowerSinglets) div 2, 2)
|
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
|
||||||
if p >= 0 and c == tolowerSinglets[p]:
|
if p >= 0 and c == toLowerSinglets[p]:
|
||||||
return Rune(c + tolowerSinglets[p+1] - 500)
|
return Rune(c + toLowerSinglets[p+1] - 500)
|
||||||
return Rune(c)
|
return Rune(c)
|
||||||
|
|
||||||
proc toUpper*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
|
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>`_
|
## * `toTitle proc <#toTitle,Rune>`_
|
||||||
## * `isUpper proc <#isUpper,Rune>`_
|
## * `isUpper proc <#isUpper,Rune>`_
|
||||||
var c = RuneImpl(c)
|
var c = RuneImpl(c)
|
||||||
var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
|
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
|
||||||
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
|
if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
|
||||||
return Rune(c + toupperRanges[p+2] - 500)
|
return Rune(c + toUpperRanges[p+2] - 500)
|
||||||
p = binarySearch(c, toupperSinglets, len(toupperSinglets) div 2, 2)
|
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
|
||||||
if p >= 0 and c == toupperSinglets[p]:
|
if p >= 0 and c == toUpperSinglets[p]:
|
||||||
return Rune(c + toupperSinglets[p+1] - 500)
|
return Rune(c + toUpperSinglets[p+1] - 500)
|
||||||
return Rune(c)
|
return Rune(c)
|
||||||
|
|
||||||
proc toTitle*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
|
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>`_
|
## * `isTitle proc <#isTitle,Rune>`_
|
||||||
var c = RuneImpl(c)
|
var c = RuneImpl(c)
|
||||||
# Note: toUpperRanges is correct here!
|
# Note: toUpperRanges is correct here!
|
||||||
var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
|
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
|
||||||
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
|
if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
|
||||||
return true
|
return true
|
||||||
p = binarySearch(c, toupperSinglets, len(toupperSinglets) div 2, 2)
|
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
|
||||||
if p >= 0 and c == toupperSinglets[p]:
|
if p >= 0 and c == toUpperSinglets[p]:
|
||||||
return true
|
return true
|
||||||
|
|
||||||
proc isUpper*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
|
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>`_
|
## * `isWhiteSpace proc <#isWhiteSpace,Rune>`_
|
||||||
var c = RuneImpl(c)
|
var c = RuneImpl(c)
|
||||||
# Note: toLowerRanges is correct here!
|
# Note: toLowerRanges is correct here!
|
||||||
var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
|
var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
|
||||||
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
|
if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
|
||||||
return true
|
return true
|
||||||
p = binarySearch(c, tolowerSinglets, len(tolowerSinglets) div 2, 2)
|
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
|
||||||
if p >= 0 and c == tolowerSinglets[p]:
|
if p >= 0 and c == toLowerSinglets[p]:
|
||||||
return true
|
return true
|
||||||
|
|
||||||
proc isAlpha*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
|
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.
|
## Iterates over any rune of the string ``s`` returning utf8 values.
|
||||||
##
|
##
|
||||||
## See also:
|
## See also:
|
||||||
## * `validateUTF8 proc <#validateUTF8,string>`_
|
## * `validateUtf8 proc <#validateUtf8,string>`_
|
||||||
## * `toUTF8 proc <#toUTF8,Rune>`_
|
## * `toUTF8 proc <#toUTF8,Rune>`_
|
||||||
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
|
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
|
||||||
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
|
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
|
||||||
|
|
@ -928,7 +928,7 @@ proc size*(r: Rune): int {.noSideEffect.} =
|
||||||
else: result = 1
|
else: result = 1
|
||||||
|
|
||||||
# --------- Private templates for different split separators -----------
|
# --------- 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
|
var rune: Rune
|
||||||
fastRuneAt(s, index, rune, false)
|
fastRuneAt(s, index, rune, false)
|
||||||
return seps.contains(rune)
|
return seps.contains(rune)
|
||||||
|
|
@ -960,7 +960,7 @@ template splitCommon(s, sep, maxsplit: untyped, sepLen: int = -1) =
|
||||||
else:
|
else:
|
||||||
inc(last, if last < len(s): runeLenAt(s, last) else: 1)
|
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 =
|
maxsplit: int = -1): string =
|
||||||
## Splits the unicode string ``s`` into substrings using a group of separators.
|
## 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)
|
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".} =
|
noSideEffect, rtl, extern: "nucSplitRunes".} =
|
||||||
## The same as the `split iterator <#split.i,string,openArray[Rune],int>`_,
|
## The same as the `split iterator <#split.i,string,openArray[Rune],int>`_,
|
||||||
## but is a proc that returns a sequence of substrings.
|
## 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))
|
accResult(split(s, sep, maxsplit))
|
||||||
|
|
||||||
proc strip*(s: string, leading = true, trailing = true,
|
proc strip*(s: string, leading = true, trailing = true,
|
||||||
runes: openarray[Rune] = unicodeSpaces): string {.noSideEffect,
|
runes: openArray[Rune] = unicodeSpaces): string {.noSideEffect,
|
||||||
rtl, extern: "nucStrip".} =
|
rtl, extern: "nucStrip".} =
|
||||||
## Strips leading or trailing ``runes`` from ``s`` and returns
|
## Strips leading or trailing ``runes`` from ``s`` and returns
|
||||||
## the resulting string.
|
## the resulting string.
|
||||||
|
|
@ -1072,46 +1072,46 @@ proc strip*(s: string, leading = true, trailing = true,
|
||||||
doAssert a.strip(trailing = false) == "áñyóng "
|
doAssert a.strip(trailing = false) == "áñyóng "
|
||||||
|
|
||||||
var
|
var
|
||||||
s_i = 0 ## starting index into string ``s``
|
sI = 0 ## starting index into string ``s``
|
||||||
e_i = len(s) - 1 ## ending index into ``s``, where the last ``Rune`` starts
|
eI = len(s) - 1 ## ending index into ``s``, where the last ``Rune`` starts
|
||||||
if leading:
|
if leading:
|
||||||
var
|
var
|
||||||
i = 0
|
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
|
rune: Rune
|
||||||
while i < len(s):
|
while i < len(s):
|
||||||
l_i = i
|
xI = i
|
||||||
fastRuneAt(s, i, rune)
|
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):
|
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
|
break
|
||||||
if trailing:
|
if trailing:
|
||||||
var
|
var
|
||||||
i = e_i
|
i = eI
|
||||||
l_i: int
|
xI: int
|
||||||
rune: Rune
|
rune: Rune
|
||||||
while i >= 0:
|
while i >= 0:
|
||||||
l_i = i
|
xI = i
|
||||||
fastRuneAt(s, l_i, rune)
|
fastRuneAt(s, xI, rune)
|
||||||
var p_i = i - 1
|
var yI = i - 1
|
||||||
while p_i >= 0:
|
while yI >= 0:
|
||||||
var
|
var
|
||||||
p_i_end = p_i
|
yIend = yI
|
||||||
p_rune: Rune
|
pRune: Rune
|
||||||
fastRuneAt(s, p_i_end, p_rune)
|
fastRuneAt(s, yIend, pRune)
|
||||||
if p_i_end < l_i: break
|
if yIend < xI: break
|
||||||
i = p_i
|
i = yI
|
||||||
rune = p_rune
|
rune = pRune
|
||||||
dec(p_i)
|
dec(yI)
|
||||||
if not runes.contains(rune):
|
if not runes.contains(rune):
|
||||||
e_i = l_i - 1
|
eI = xI - 1
|
||||||
break
|
break
|
||||||
dec(i)
|
dec(i)
|
||||||
let newLen = e_i - s_i + 1
|
let newLen = eI - sI + 1
|
||||||
result = newStringOfCap(newLen)
|
result = newStringOfCap(newLen)
|
||||||
if newLen > 0:
|
if newLen > 0:
|
||||||
result.add s[s_i .. e_i]
|
result.add s[sI .. eI]
|
||||||
|
|
||||||
proc repeat*(c: Rune, count: Natural): string {.noSideEffect,
|
proc repeat*(c: Rune, count: Natural): string {.noSideEffect,
|
||||||
rtl, extern: "nucRepeatRune".} =
|
rtl, extern: "nucRepeatRune".} =
|
||||||
|
|
|
||||||
|
|
@ -445,7 +445,7 @@ proc `$`*(u: Uri): string =
|
||||||
result.add(":")
|
result.add(":")
|
||||||
result.add(u.password)
|
result.add(u.password)
|
||||||
result.add("@")
|
result.add("@")
|
||||||
if u.hostname.endswith('/'):
|
if u.hostname.endsWith('/'):
|
||||||
result.add(u.hostname[0..^2])
|
result.add(u.hostname[0..^2])
|
||||||
else:
|
else:
|
||||||
result.add(u.hostname)
|
result.add(u.hostname)
|
||||||
|
|
|
||||||
|
|
@ -462,7 +462,7 @@ proc shallowCopy*[T](x: var T, y: T) {.noSideEffect, magic: "ShallowCopy".}
|
||||||
## and strings.
|
## and strings.
|
||||||
|
|
||||||
when defined(nimArrIdx):
|
when defined(nimArrIdx):
|
||||||
# :array|openarray|string|seq|cstring|tuple
|
# :array|openArray|string|seq|cstring|tuple
|
||||||
proc `[]`*[I: Ordinal;T](a: T; i: I): T {.
|
proc `[]`*[I: Ordinal;T](a: T; i: I): T {.
|
||||||
noSideEffect, magic: "ArrGet".}
|
noSideEffect, magic: "ArrGet".}
|
||||||
proc `[]=`*[I: Ordinal;T,S](a: T; i: I;
|
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
|
## is an `int` type ranging from one to the maximum value
|
||||||
## of an `int`. This type is often useful for documentation and debugging.
|
## 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.
|
object ## The root of Nim's object hierarchy.
|
||||||
##
|
##
|
||||||
## Objects should inherit from `RootObj` or one of its descendants.
|
## 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 {.
|
proc len*[TOpenArray: openArray|varargs](x: TOpenArray): int {.
|
||||||
magic: "LengthOpenArray", noSideEffect.}
|
magic: "LengthOpenArray", noSideEffect.}
|
||||||
## Returns the length of an openarray.
|
## Returns the length of an openArray.
|
||||||
##
|
##
|
||||||
## .. code-block:: Nim
|
## .. code-block:: Nim
|
||||||
## var s = [1, 1, 1, 1, 1]
|
## var s = [1, 1, 1, 1, 1]
|
||||||
|
|
@ -2002,7 +2002,7 @@ else:
|
||||||
## turned on.
|
## turned on.
|
||||||
|
|
||||||
when defined(profiler) and not defined(nimscript):
|
when defined(profiler) and not defined(nimscript):
|
||||||
proc nimProfile() {.compilerProc, noinline.}
|
proc nimProfile() {.compilerproc, noinline.}
|
||||||
when hasThreadSupport:
|
when hasThreadSupport:
|
||||||
{.pragma: rtlThreadVar, threadvar.}
|
{.pragma: rtlThreadVar, threadvar.}
|
||||||
else:
|
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":
|
when not defined(JS) and not defined(nimscript) and hostOS != "standalone":
|
||||||
include "system/cgprocs"
|
include "system/cgprocs"
|
||||||
when not defined(JS) and not defined(nimscript) and hasAlloc and not defined(gcDestructors):
|
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):
|
when not defined(gcDestructors):
|
||||||
proc add*[T](x: var seq[T], y: T) {.magic: "AppendSeqElem", noSideEffect.}
|
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
|
## assert b == 5
|
||||||
|
|
||||||
when not defined(js) and not defined(booting) and defined(nimTrMacros):
|
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
|
# Optimize swapping of array elements if they are refs. Default swap
|
||||||
# implementation will cause unsureAsgnRef to be emitted which causes
|
# implementation will cause unsureAsgnRef to be emitted which causes
|
||||||
# unnecessary slow down in this case.
|
# unnecessary slow down in this case.
|
||||||
|
|
@ -2919,7 +2919,7 @@ proc `==`*[I, T](x, y: array[I, T]): bool =
|
||||||
return
|
return
|
||||||
result = true
|
result = true
|
||||||
|
|
||||||
proc `==`*[T](x, y: openarray[T]): bool =
|
proc `==`*[T](x, y: openArray[T]): bool =
|
||||||
if x.len != y.len:
|
if x.len != y.len:
|
||||||
return false
|
return false
|
||||||
|
|
||||||
|
|
@ -2930,7 +2930,7 @@ proc `==`*[T](x, y: openarray[T]): bool =
|
||||||
result = true
|
result = true
|
||||||
|
|
||||||
proc `@`*[T](a: openArray[T]): seq[T] =
|
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
|
## This is not as efficient as turning a fixed length array into a sequence
|
||||||
## as it always copies every element of `a`.
|
## as it always copies every element of `a`.
|
||||||
|
|
@ -3081,9 +3081,9 @@ when not defined(js):
|
||||||
|
|
||||||
when defined(nimV2):
|
when defined(nimV2):
|
||||||
type
|
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.}
|
DestructorProc = proc (p: pointer) {.nimcall, benign.}
|
||||||
TNimType {.compilerProc.} = object
|
TNimType {.compilerproc.} = object
|
||||||
destructor: pointer
|
destructor: pointer
|
||||||
size: int
|
size: int
|
||||||
name: cstring
|
name: cstring
|
||||||
|
|
@ -3427,7 +3427,7 @@ template newException*(exceptn: typedesc, message: string;
|
||||||
e
|
e
|
||||||
|
|
||||||
when hostOS == "standalone" and defined(nogc):
|
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""
|
if s == nil or s.len == 0: result = cstring""
|
||||||
else: result = cstring(addr s.data)
|
else: result = cstring(addr s.data)
|
||||||
|
|
||||||
|
|
@ -3844,7 +3844,7 @@ elif defined(JS):
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
|
||||||
proc quit*(errormsg: string, errorcode = QuitFailure) {.noReturn.} =
|
proc quit*(errormsg: string, errorcode = QuitFailure) {.noreturn.} =
|
||||||
## A shorthand for ``echo(errormsg); quit(errorcode)``.
|
## A shorthand for ``echo(errormsg); quit(errorcode)``.
|
||||||
when defined(nimscript) or defined(js) or (hostOS == "standalone"):
|
when defined(nimscript) or defined(js) or (hostOS == "standalone"):
|
||||||
echo errormsg
|
echo errormsg
|
||||||
|
|
@ -4484,21 +4484,21 @@ when defined(windows) and appType == "console" and defined(nimSetUtf8CodePage) a
|
||||||
discard setConsoleOutputCP(65001) # 65001 - utf-8 codepage
|
discard setConsoleOutputCP(65001) # 65001 - utf-8 codepage
|
||||||
|
|
||||||
when not defined(js):
|
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".}
|
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".}
|
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".}
|
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".}
|
magic: "Slice".}
|
||||||
proc toOpenArray*(x: string; first, last: int): openarray[char] {.
|
proc toOpenArray*(x: string; first, last: int): openArray[char] {.
|
||||||
magic: "Slice".}
|
magic: "Slice".}
|
||||||
proc toOpenArrayByte*(x: string; first, last: int): openarray[byte] {.
|
proc toOpenArrayByte*(x: string; first, last: int): openArray[byte] {.
|
||||||
magic: "Slice".}
|
magic: "Slice".}
|
||||||
|
|
||||||
type
|
type
|
||||||
ForLoopStmt* {.compilerProc.} = object ## \
|
ForLoopStmt* {.compilerproc.} = object ## \
|
||||||
## A special type that marks a macro as a `for-loop macro`:idx:.
|
## A special type that marks a macro as a `for-loop macro`:idx:.
|
||||||
## See `"For Loop Macro" <manual.html#macros-for-loop-macro>`_.
|
## See `"For Loop Macro" <manual.html#macros-for-loop-macro>`_.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1007,7 +1007,7 @@ template instantiateForRegion(allocator: untyped) =
|
||||||
dealloc(allocator, p)
|
dealloc(allocator, p)
|
||||||
|
|
||||||
proc realloc(p: pointer, newsize: Natural): pointer =
|
proc realloc(p: pointer, newsize: Natural): pointer =
|
||||||
result = realloc(allocator, p, newSize)
|
result = realloc(allocator, p, newsize)
|
||||||
|
|
||||||
when false:
|
when false:
|
||||||
proc countFreeMem(): int =
|
proc countFreeMem(): int =
|
||||||
|
|
@ -1060,7 +1060,7 @@ template instantiateForRegion(allocator: untyped) =
|
||||||
result = realloc(sharedHeap, p, newsize)
|
result = realloc(sharedHeap, p, newsize)
|
||||||
releaseSys(heapLock)
|
releaseSys(heapLock)
|
||||||
else:
|
else:
|
||||||
result = realloc(p, newSize)
|
result = realloc(p, newsize)
|
||||||
|
|
||||||
when hasThreadSupport:
|
when hasThreadSupport:
|
||||||
template sharedMemStatsShared(v: int) =
|
template sharedMemStatsShared(v: int) =
|
||||||
|
|
|
||||||
|
|
@ -113,7 +113,7 @@ proc c_signal*(sign: cint, handler: proc (a: cint) {.noconv.}): CSighandlerT {.
|
||||||
|
|
||||||
type
|
type
|
||||||
CFile {.importc: "FILE", header: "<stdio.h>",
|
CFile {.importc: "FILE", header: "<stdio.h>",
|
||||||
incompletestruct.} = object
|
incompleteStruct.} = object
|
||||||
CFilePtr* = ptr CFile ## The type representing a file handle.
|
CFilePtr* = ptr CFile ## The type representing a file handle.
|
||||||
|
|
||||||
var
|
var
|
||||||
|
|
@ -142,7 +142,7 @@ proc c_realloc*(p: pointer, newsize: csize): pointer {.
|
||||||
proc c_fwrite*(buf: pointer, size, n: csize, f: CFilePtr): cint {.
|
proc c_fwrite*(buf: pointer, size, n: csize, f: CFilePtr): cint {.
|
||||||
importc: "fwrite", header: "<stdio.h>".}
|
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!
|
# we cannot throw an exception here!
|
||||||
discard c_fwrite(s, 1, s.len, f)
|
discard c_fwrite(s, 1, s.len, f)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -59,11 +59,11 @@ when defined(builtinOverflow):
|
||||||
proc mulIntOverflow(a, b: int, c: var int): bool {.
|
proc mulIntOverflow(a, b: int, c: var int): bool {.
|
||||||
importc: "__builtin_smul_overflow", nodecl, nosideeffect.}
|
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):
|
if addInt64Overflow(a, b, result):
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
proc subInt64(a, b: int64): int64 {.compilerProc, inline.} =
|
proc subInt64(a, b: int64): int64 {.compilerproc, inline.} =
|
||||||
if subInt64Overflow(a, b, result):
|
if subInt64Overflow(a, b, result):
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
|
|
@ -71,13 +71,13 @@ when defined(builtinOverflow):
|
||||||
if mulInt64Overflow(a, b, result):
|
if mulInt64Overflow(a, b, result):
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
else:
|
else:
|
||||||
proc addInt64(a, b: int64): int64 {.compilerProc, inline.} =
|
proc addInt64(a, b: int64): int64 {.compilerproc, inline.} =
|
||||||
result = a +% b
|
result = a +% b
|
||||||
if (result xor a) >= int64(0) or (result xor b) >= int64(0):
|
if (result xor a) >= int64(0) or (result xor b) >= int64(0):
|
||||||
return result
|
return result
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
proc subInt64(a, b: int64): int64 {.compilerProc, inline.} =
|
proc subInt64(a, b: int64): int64 {.compilerproc, inline.} =
|
||||||
result = a -% b
|
result = a -% b
|
||||||
if (result xor a) >= int64(0) or (result xor not b) >= int64(0):
|
if (result xor a) >= int64(0) or (result xor not b) >= int64(0):
|
||||||
return result
|
return result
|
||||||
|
|
@ -126,29 +126,29 @@ else:
|
||||||
return result
|
return result
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
proc negInt64(a: int64): int64 {.compilerProc, inline.} =
|
proc negInt64(a: int64): int64 {.compilerproc, inline.} =
|
||||||
if a != low(int64): return -a
|
if a != low(int64): return -a
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
proc absInt64(a: int64): int64 {.compilerProc, inline.} =
|
proc absInt64(a: int64): int64 {.compilerproc, inline.} =
|
||||||
if a != low(int64):
|
if a != low(int64):
|
||||||
if a >= 0: return a
|
if a >= 0: return a
|
||||||
else: return -a
|
else: return -a
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
proc divInt64(a, b: int64): int64 {.compilerProc, inline.} =
|
proc divInt64(a, b: int64): int64 {.compilerproc, inline.} =
|
||||||
if b == int64(0):
|
if b == int64(0):
|
||||||
raiseDivByZero()
|
raiseDivByZero()
|
||||||
if a == low(int64) and b == int64(-1):
|
if a == low(int64) and b == int64(-1):
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
return a div b
|
return a div b
|
||||||
|
|
||||||
proc modInt64(a, b: int64): int64 {.compilerProc, inline.} =
|
proc modInt64(a, b: int64): int64 {.compilerproc, inline.} =
|
||||||
if b == int64(0):
|
if b == int64(0):
|
||||||
raiseDivByZero()
|
raiseDivByZero()
|
||||||
return a mod b
|
return a mod b
|
||||||
|
|
||||||
proc absInt(a: int): int {.compilerProc, inline.} =
|
proc absInt(a: int): int {.compilerproc, inline.} =
|
||||||
if a != low(int):
|
if a != low(int):
|
||||||
if a >= 0: return a
|
if a >= 0: return a
|
||||||
else: return -a
|
else: return -a
|
||||||
|
|
@ -164,7 +164,7 @@ const
|
||||||
when asmVersion and not defined(gcc) and not defined(llvm_gcc):
|
when asmVersion and not defined(gcc) and not defined(llvm_gcc):
|
||||||
# assembler optimized versions for compilers that
|
# assembler optimized versions for compilers that
|
||||||
# have an intel syntax assembler:
|
# 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
|
# a in eax, and b in edx
|
||||||
asm """
|
asm """
|
||||||
mov eax, ecx
|
mov eax, ecx
|
||||||
|
|
@ -175,7 +175,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
|
||||||
ret
|
ret
|
||||||
"""
|
"""
|
||||||
|
|
||||||
proc subInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
|
proc subInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
|
||||||
asm """
|
asm """
|
||||||
mov eax, ecx
|
mov eax, ecx
|
||||||
sub eax, edx
|
sub eax, edx
|
||||||
|
|
@ -185,7 +185,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
|
||||||
ret
|
ret
|
||||||
"""
|
"""
|
||||||
|
|
||||||
proc negInt(a: int): int {.compilerProc, asmNoStackFrame.} =
|
proc negInt(a: int): int {.compilerproc, asmNoStackFrame.} =
|
||||||
asm """
|
asm """
|
||||||
mov eax, ecx
|
mov eax, ecx
|
||||||
neg eax
|
neg eax
|
||||||
|
|
@ -195,7 +195,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
|
||||||
ret
|
ret
|
||||||
"""
|
"""
|
||||||
|
|
||||||
proc divInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
|
proc divInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
|
||||||
asm """
|
asm """
|
||||||
test edx, edx
|
test edx, edx
|
||||||
jne L_NOT_ZERO
|
jne L_NOT_ZERO
|
||||||
|
|
@ -214,7 +214,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
|
||||||
ret
|
ret
|
||||||
"""
|
"""
|
||||||
|
|
||||||
proc modInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
|
proc modInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
|
||||||
asm """
|
asm """
|
||||||
test edx, edx
|
test edx, edx
|
||||||
jne L_NOT_ZERO
|
jne L_NOT_ZERO
|
||||||
|
|
@ -234,7 +234,7 @@ when asmVersion and not defined(gcc) and not defined(llvm_gcc):
|
||||||
ret
|
ret
|
||||||
"""
|
"""
|
||||||
|
|
||||||
proc mulInt(a, b: int): int {.compilerProc, asmNoStackFrame.} =
|
proc mulInt(a, b: int): int {.compilerproc, asmNoStackFrame.} =
|
||||||
asm """
|
asm """
|
||||||
mov eax, ecx
|
mov eax, ecx
|
||||||
mov ecx, edx
|
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)):
|
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!
|
# don't use a pure proc here!
|
||||||
asm """
|
asm """
|
||||||
"addl %%ecx, %%eax\n"
|
"addl %%ecx, %%eax\n"
|
||||||
|
|
@ -261,7 +261,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
|
||||||
#/* Intel syntax here */
|
#/* Intel syntax here */
|
||||||
#".att_syntax"
|
#".att_syntax"
|
||||||
|
|
||||||
proc subInt(a, b: int): int {.compilerProc, inline.} =
|
proc subInt(a, b: int): int {.compilerproc, inline.} =
|
||||||
asm """ "subl %%ecx,%%eax\n"
|
asm """ "subl %%ecx,%%eax\n"
|
||||||
"jno 1\n"
|
"jno 1\n"
|
||||||
"call _raiseOverflow\n"
|
"call _raiseOverflow\n"
|
||||||
|
|
@ -270,7 +270,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
|
||||||
:"a"(`a`), "c"(`b`)
|
:"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"
|
asm """ "xorl %%edx, %%edx\n"
|
||||||
"imull %%ecx\n"
|
"imull %%ecx\n"
|
||||||
"jno 1\n"
|
"jno 1\n"
|
||||||
|
|
@ -281,7 +281,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
|
||||||
:"%edx"
|
:"%edx"
|
||||||
"""
|
"""
|
||||||
|
|
||||||
proc negInt(a: int): int {.compilerProc, inline.} =
|
proc negInt(a: int): int {.compilerproc, inline.} =
|
||||||
asm """ "negl %%eax\n"
|
asm """ "negl %%eax\n"
|
||||||
"jno 1\n"
|
"jno 1\n"
|
||||||
"call _raiseOverflow\n"
|
"call _raiseOverflow\n"
|
||||||
|
|
@ -290,7 +290,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
|
||||||
:"a"(`a`)
|
:"a"(`a`)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
proc divInt(a, b: int): int {.compilerProc, inline.} =
|
proc divInt(a, b: int): int {.compilerproc, inline.} =
|
||||||
asm """ "xorl %%edx, %%edx\n"
|
asm """ "xorl %%edx, %%edx\n"
|
||||||
"idivl %%ecx\n"
|
"idivl %%ecx\n"
|
||||||
"jno 1\n"
|
"jno 1\n"
|
||||||
|
|
@ -301,7 +301,7 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)):
|
||||||
:"%edx"
|
:"%edx"
|
||||||
"""
|
"""
|
||||||
|
|
||||||
proc modInt(a, b: int): int {.compilerProc, inline.} =
|
proc modInt(a, b: int): int {.compilerproc, inline.} =
|
||||||
asm """ "xorl %%edx, %%edx\n"
|
asm """ "xorl %%edx, %%edx\n"
|
||||||
"idivl %%ecx\n"
|
"idivl %%ecx\n"
|
||||||
"jno 1\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):
|
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):
|
if addIntOverflow(a, b, result):
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
when not declared(subInt) and defined(builtinOverflow):
|
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):
|
if subIntOverflow(a, b, result):
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
when not declared(mulInt) and defined(builtinOverflow):
|
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):
|
if mulIntOverflow(a, b, result):
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
# Platform independent versions of the above (slower!)
|
# Platform independent versions of the above (slower!)
|
||||||
when not declared(addInt):
|
when not declared(addInt):
|
||||||
proc addInt(a, b: int): int {.compilerProc, inline.} =
|
proc addInt(a, b: int): int {.compilerproc, inline.} =
|
||||||
result = a +% b
|
result = a +% b
|
||||||
if (result xor a) >= 0 or (result xor b) >= 0:
|
if (result xor a) >= 0 or (result xor b) >= 0:
|
||||||
return result
|
return result
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
when not declared(subInt):
|
when not declared(subInt):
|
||||||
proc subInt(a, b: int): int {.compilerProc, inline.} =
|
proc subInt(a, b: int): int {.compilerproc, inline.} =
|
||||||
result = a -% b
|
result = a -% b
|
||||||
if (result xor a) >= 0 or (result xor not b) >= 0:
|
if (result xor a) >= 0 or (result xor not b) >= 0:
|
||||||
return result
|
return result
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
when not declared(negInt):
|
when not declared(negInt):
|
||||||
proc negInt(a: int): int {.compilerProc, inline.} =
|
proc negInt(a: int): int {.compilerproc, inline.} =
|
||||||
if a != low(int): return -a
|
if a != low(int): return -a
|
||||||
raiseOverflow()
|
raiseOverflow()
|
||||||
|
|
||||||
when not declared(divInt):
|
when not declared(divInt):
|
||||||
proc divInt(a, b: int): int {.compilerProc, inline.} =
|
proc divInt(a, b: int): int {.compilerproc, inline.} =
|
||||||
if b == 0:
|
if b == 0:
|
||||||
raiseDivByZero()
|
raiseDivByZero()
|
||||||
if a == low(int) and b == -1:
|
if a == low(int) and b == -1:
|
||||||
|
|
@ -357,7 +357,7 @@ when not declared(divInt):
|
||||||
return a div b
|
return a div b
|
||||||
|
|
||||||
when not declared(modInt):
|
when not declared(modInt):
|
||||||
proc modInt(a, b: int): int {.compilerProc, inline.} =
|
proc modInt(a, b: int): int {.compilerproc, inline.} =
|
||||||
if b == 0:
|
if b == 0:
|
||||||
raiseDivByZero()
|
raiseDivByZero()
|
||||||
return a mod b
|
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
|
# the only one that can lose catastrophic amounts of information, it's the
|
||||||
# native int product that must have overflowed.
|
# native int product that must have overflowed.
|
||||||
#
|
#
|
||||||
proc mulInt(a, b: int): int {.compilerProc.} =
|
proc mulInt(a, b: int): int {.compilerproc.} =
|
||||||
var
|
var
|
||||||
resAsFloat, floatProd: float
|
resAsFloat, floatProd: float
|
||||||
|
|
||||||
|
|
@ -412,7 +412,7 @@ when not declared(mulInt):
|
||||||
proc raiseFloatInvalidOp {.noinline.} =
|
proc raiseFloatInvalidOp {.noinline.} =
|
||||||
sysFatal(FloatInvalidOpError, "FPU operation caused a NaN result")
|
sysFatal(FloatInvalidOpError, "FPU operation caused a NaN result")
|
||||||
|
|
||||||
proc nanCheck(x: float64) {.compilerProc, inline.} =
|
proc nanCheck(x: float64) {.compilerproc, inline.} =
|
||||||
if x != x: raiseFloatInvalidOp()
|
if x != x: raiseFloatInvalidOp()
|
||||||
|
|
||||||
proc raiseFloatOverflow(x: float64) {.noinline.} =
|
proc raiseFloatOverflow(x: float64) {.noinline.} =
|
||||||
|
|
@ -421,5 +421,5 @@ proc raiseFloatOverflow(x: float64) {.noinline.} =
|
||||||
else:
|
else:
|
||||||
sysFatal(FloatUnderflowError, "FPU operations caused an underflow")
|
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)
|
if x != 0.0 and x*0.5 == x: raiseFloatOverflow(x)
|
||||||
|
|
|
||||||
|
|
@ -11,12 +11,12 @@ proc `$`(x: int): string {.magic: "IntToStr", noSideEffect.}
|
||||||
proc `$`(info: InstantiationInfo): string =
|
proc `$`(info: InstantiationInfo): string =
|
||||||
# The +1 is needed here
|
# The +1 is needed here
|
||||||
# instead of overriding `$` (and changing its meaning), consider explicit name.
|
# 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)
|
sysFatal(AssertionError, msg)
|
||||||
|
|
||||||
proc failedAssertImpl*(msg: string) {.raises: [], tags: [].} =
|
proc failedAssertImpl*(msg: string) {.raises: [], tags: [].} =
|
||||||
|
|
|
||||||
|
|
@ -107,10 +107,10 @@ proc genericAssignAux(dest, src: pointer, mt: PNimType, shallow: bool) =
|
||||||
else:
|
else:
|
||||||
copyMem(dest, src, mt.size) # copy raw bits
|
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)
|
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)
|
genericAssignAux(dest, src, mt, true)
|
||||||
|
|
||||||
when false:
|
when false:
|
||||||
|
|
@ -142,7 +142,7 @@ when false:
|
||||||
cprintf("%s %ld\n", k, t.size)
|
cprintf("%s %ld\n", k, t.size)
|
||||||
debugNimType(t.base)
|
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 :-)
|
var src = src # ugly, but I like to stress the parser sometimes :-)
|
||||||
genericAssign(dest, addr(src), mt)
|
genericAssign(dest, addr(src), mt)
|
||||||
|
|
||||||
|
|
@ -155,7 +155,7 @@ proc genericAssignOpenArray(dest, src: pointer, len: int,
|
||||||
genericAssign(cast[pointer](d +% i *% mt.base.size),
|
genericAssign(cast[pointer](d +% i *% mt.base.size),
|
||||||
cast[pointer](s +% i *% mt.base.size), mt.base)
|
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.} =
|
proc objectInitAux(dest: pointer, n: ptr TNimNode) {.benign.} =
|
||||||
var d = cast[ByteAddress](dest)
|
var d = cast[ByteAddress](dest)
|
||||||
case n.kind
|
case n.kind
|
||||||
|
|
@ -188,7 +188,7 @@ proc objectInit(dest: pointer, typ: PNimType) =
|
||||||
|
|
||||||
# ---------------------- assign zero -----------------------------------------
|
# ---------------------- 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) =
|
proc genericResetAux(dest: pointer, n: ptr TNimNode) =
|
||||||
var d = cast[ByteAddress](dest)
|
var d = cast[ByteAddress](dest)
|
||||||
case n.kind
|
case n.kind
|
||||||
|
|
@ -229,7 +229,7 @@ proc selectBranch(discVal, L: int,
|
||||||
|
|
||||||
proc FieldDiscriminantCheck(oldDiscVal, newDiscVal: int,
|
proc FieldDiscriminantCheck(oldDiscVal, newDiscVal: int,
|
||||||
a: ptr array[0x7fff, ptr TNimNode],
|
a: ptr array[0x7fff, ptr TNimNode],
|
||||||
L: int) {.compilerProc.} =
|
L: int) {.compilerproc.} =
|
||||||
let oldBranch = selectBranch(oldDiscVal, L, a)
|
let oldBranch = selectBranch(oldDiscVal, L, a)
|
||||||
let newBranch = selectBranch(newDiscVal, L, a)
|
let newBranch = selectBranch(newDiscVal, L, a)
|
||||||
when defined(nimOldCaseObjects):
|
when defined(nimOldCaseObjects):
|
||||||
|
|
|
||||||
|
|
@ -154,7 +154,7 @@ proc contains(s: CellSet, cell: PCell): bool =
|
||||||
else:
|
else:
|
||||||
result = false
|
result = false
|
||||||
|
|
||||||
proc incl(s: var CellSet, cell: PCell) {.noinline.} =
|
proc incl(s: var CellSet, cell: PCell) =
|
||||||
var u = cast[uint](cell)
|
var u = cast[uint](cell)
|
||||||
var t = cellSetPut(s, u shr PageShift)
|
var t = cellSetPut(s, u shr PageShift)
|
||||||
u = (u mod PageSize) div MemAlign
|
u = (u mod PageSize) div MemAlign
|
||||||
|
|
|
||||||
|
|
@ -99,7 +99,7 @@ when not defined(nimV2):
|
||||||
return true
|
return true
|
||||||
|
|
||||||
proc isObjWithCache(obj, subclass: PNimType;
|
proc isObjWithCache(obj, subclass: PNimType;
|
||||||
cache: var ObjCheckCache): bool {.compilerProc, inline.} =
|
cache: var ObjCheckCache): bool {.compilerproc, inline.} =
|
||||||
if obj == subclass: return true
|
if obj == subclass: return true
|
||||||
if obj.base == subclass: return true
|
if obj.base == subclass: return true
|
||||||
if cache[0] == obj: return false
|
if cache[0] == obj: return false
|
||||||
|
|
@ -116,6 +116,6 @@ when not defined(nimV2):
|
||||||
return true
|
return true
|
||||||
|
|
||||||
when defined(nimV2):
|
when defined(nimV2):
|
||||||
proc nimFieldDiscriminantCheckV2(oldDiscVal, newDiscVal: uint8) {.compilerProc.} =
|
proc nimFieldDiscriminantCheckV2(oldDiscVal, newDiscVal: uint8) {.compilerproc.} =
|
||||||
if oldDiscVal != newDiscVal:
|
if oldDiscVal != newDiscVal:
|
||||||
sysFatal(FieldError, "assignment to discriminant changes object branch")
|
sysFatal(FieldError, "assignment to discriminant changes object branch")
|
||||||
|
|
|
||||||
|
|
@ -165,14 +165,14 @@ proc genericDeepCopyAux(dest, src: pointer, mt: PNimType; tab: var PtrTable) =
|
||||||
else:
|
else:
|
||||||
copyMem(dest, src, mt.size)
|
copyMem(dest, src, mt.size)
|
||||||
|
|
||||||
proc genericDeepCopy(dest, src: pointer, mt: PNimType) {.compilerProc.} =
|
proc genericDeepCopy(dest, src: pointer, mt: PNimType) {.compilerproc.} =
|
||||||
GC_disable()
|
GC_disable()
|
||||||
var tab = initPtrTable()
|
var tab = initPtrTable()
|
||||||
genericDeepCopyAux(dest, src, mt, tab)
|
genericDeepCopyAux(dest, src, mt, tab)
|
||||||
deinit tab
|
deinit tab
|
||||||
GC_enable()
|
GC_enable()
|
||||||
|
|
||||||
proc genericSeqDeepCopy(dest, src: pointer, mt: PNimType) {.compilerProc.} =
|
proc genericSeqDeepCopy(dest, src: pointer, mt: PNimType) {.compilerproc.} =
|
||||||
# also invoked for 'string'
|
# also invoked for 'string'
|
||||||
var src = src
|
var src = src
|
||||||
genericDeepCopy(dest, addr(src), mt)
|
genericDeepCopy(dest, addr(src), mt)
|
||||||
|
|
|
||||||
|
|
@ -149,7 +149,7 @@ when not defined(nimNoArrayToString):
|
||||||
## Generic ``$`` operator for arrays that is lifted from the components.
|
## Generic ``$`` operator for arrays that is lifted from the components.
|
||||||
collectionToString(x, "[", ", ", "]")
|
collectionToString(x, "[", ", ", "]")
|
||||||
|
|
||||||
proc `$`*[T](x: openarray[T]): string =
|
proc `$`*[T](x: openArray[T]): string =
|
||||||
## Generic ``$`` operator for openarrays that is lifted from the components
|
## Generic ``$`` operator for openarrays that is lifted from the components
|
||||||
## of `x`. Example:
|
## of `x`. Example:
|
||||||
##
|
##
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ elif defined(nimQuirky) and not defined(nimscript):
|
||||||
|
|
||||||
proc name(t: typedesc): string {.magic: "TypeTrait".}
|
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)
|
var buf = newStringOfCap(200)
|
||||||
add(buf, "Error: unhandled exception: ")
|
add(buf, "Error: unhandled exception: ")
|
||||||
add(buf, message)
|
add(buf, message)
|
||||||
|
|
@ -25,11 +25,11 @@ elif defined(nimQuirky) and not defined(nimscript):
|
||||||
cstderr.rawWrite buf
|
cstderr.rawWrite buf
|
||||||
quit 1
|
quit 1
|
||||||
|
|
||||||
proc sysFatal(exceptn: typedesc, message: string) {.inline, noReturn.} =
|
proc sysFatal(exceptn: typedesc, message: string) {.inline, noreturn.} =
|
||||||
sysFatal(exceptn, message, "")
|
sysFatal(exceptn, message, "")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
proc sysFatal(exceptn: typedesc, message: string) {.inline, noReturn.} =
|
proc sysFatal(exceptn: typedesc, message: string) {.inline, noreturn.} =
|
||||||
when declared(owned):
|
when declared(owned):
|
||||||
var e: owned(ref exceptn)
|
var e: owned(ref exceptn)
|
||||||
else:
|
else:
|
||||||
|
|
@ -38,7 +38,7 @@ else:
|
||||||
e.msg = message
|
e.msg = message
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noReturn.} =
|
proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noreturn.} =
|
||||||
when declared(owned):
|
when declared(owned):
|
||||||
var e: owned(ref exceptn)
|
var e: owned(ref exceptn)
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -184,7 +184,7 @@ proc incRef(c: PCell) {.inline.} =
|
||||||
# and not colorMask
|
# and not colorMask
|
||||||
logCell("incRef", c)
|
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:
|
# we keep it from being collected by pretending it's not even allocated:
|
||||||
let c = usrToCell(p)
|
let c = usrToCell(p)
|
||||||
add(gch.additionalRoots, c)
|
add(gch.additionalRoots, c)
|
||||||
|
|
@ -202,7 +202,7 @@ proc decRef(c: PCell) {.inline.} =
|
||||||
rtlAddZCT(c)
|
rtlAddZCT(c)
|
||||||
logCell("decRef", c)
|
logCell("decRef", c)
|
||||||
|
|
||||||
proc nimGCunref(p: pointer) {.compilerProc.} =
|
proc nimGCunref(p: pointer) {.compilerproc.} =
|
||||||
let cell = usrToCell(p)
|
let cell = usrToCell(p)
|
||||||
var L = gch.additionalRoots.len-1
|
var L = gch.additionalRoots.len-1
|
||||||
var i = L
|
var i = L
|
||||||
|
|
@ -223,15 +223,15 @@ template beforeDealloc(gch: var GcHeap; c: PCell; msg: typed) =
|
||||||
if gch.decStack.d[i] == c:
|
if gch.decStack.d[i] == c:
|
||||||
sysAssert(false, msg)
|
sysAssert(false, msg)
|
||||||
|
|
||||||
proc nimGCunrefNoCycle(p: pointer) {.compilerProc, inline.} =
|
proc nimGCunrefNoCycle(p: pointer) {.compilerproc, inline.} =
|
||||||
sysAssert(allocInv(gch.region), "begin nimGCunrefNoCycle")
|
sysAssert(allocInv(gch.region), "begin nimGCunrefNoCycle")
|
||||||
decRef(usrToCell(p))
|
decRef(usrToCell(p))
|
||||||
sysAssert(allocInv(gch.region), "end nimGCunrefNoCycle 5")
|
sysAssert(allocInv(gch.region), "end nimGCunrefNoCycle 5")
|
||||||
|
|
||||||
proc nimGCunrefRC1(p: pointer) {.compilerProc, inline.} =
|
proc nimGCunrefRC1(p: pointer) {.compilerproc, inline.} =
|
||||||
decRef(usrToCell(p))
|
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!
|
# the code generator calls this proc!
|
||||||
gcAssert(not isOnStack(dest), "asgnRef")
|
gcAssert(not isOnStack(dest), "asgnRef")
|
||||||
# BUGFIX: first incRef then decRef!
|
# 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,
|
proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline,
|
||||||
deprecated: "old compiler compat".} = asgnRef(dest, src)
|
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
|
# 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
|
# 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).
|
# reference is in the stack or not (this can happen for var parameters).
|
||||||
|
|
|
||||||
|
|
@ -193,12 +193,12 @@ proc doOperation(p: pointer, op: WalkOp) {.benign.}
|
||||||
proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) {.benign.}
|
proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) {.benign.}
|
||||||
# we need the prototype here for debugging purposes
|
# we need the prototype here for debugging purposes
|
||||||
|
|
||||||
proc nimGCref(p: pointer) {.compilerProc.} =
|
proc nimGCref(p: pointer) {.compilerproc.} =
|
||||||
let cell = usrToCell(p)
|
let cell = usrToCell(p)
|
||||||
markAsEscaped(cell)
|
markAsEscaped(cell)
|
||||||
add(gch.additionalRoots, cell)
|
add(gch.additionalRoots, cell)
|
||||||
|
|
||||||
proc nimGCunref(p: pointer) {.compilerProc.} =
|
proc nimGCunref(p: pointer) {.compilerproc.} =
|
||||||
let cell = usrToCell(p)
|
let cell = usrToCell(p)
|
||||||
var L = gch.additionalRoots.len-1
|
var L = gch.additionalRoots.len-1
|
||||||
var i = L
|
var i = L
|
||||||
|
|
@ -210,10 +210,10 @@ proc nimGCunref(p: pointer) {.compilerProc.} =
|
||||||
break
|
break
|
||||||
dec(i)
|
dec(i)
|
||||||
|
|
||||||
proc nimGCunrefNoCycle(p: pointer) {.compilerProc, inline.} =
|
proc nimGCunrefNoCycle(p: pointer) {.compilerproc, inline.} =
|
||||||
discard "can we do some freeing here?"
|
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?"
|
discard "can we do some freeing here?"
|
||||||
|
|
||||||
template markGrey(x: PCell) =
|
template markGrey(x: PCell) =
|
||||||
|
|
@ -225,7 +225,7 @@ template markGrey(x: PCell) =
|
||||||
x.setColor(rcGrey)
|
x.setColor(rcGrey)
|
||||||
add(gch.greyStack, x)
|
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!
|
# the code generator calls this proc!
|
||||||
gcAssert(not isOnStack(dest), "asgnRef")
|
gcAssert(not isOnStack(dest), "asgnRef")
|
||||||
# BUGFIX: first incRef then decRef!
|
# 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,
|
proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline,
|
||||||
deprecated: "old compiler compat".} = asgnRef(dest, src)
|
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
|
# 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
|
# 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).
|
# reference is in the stack or not (this can happen for var parameters).
|
||||||
|
|
|
||||||
|
|
@ -456,7 +456,7 @@ var
|
||||||
threadLocalMarkers {.exportc.}: array[0..3499, GlobalMarkerProc]
|
threadLocalMarkers {.exportc.}: array[0..3499, GlobalMarkerProc]
|
||||||
gHeapidGenerator: int
|
gHeapidGenerator: int
|
||||||
|
|
||||||
proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerProc.} =
|
proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerproc.} =
|
||||||
if globalMarkersLen <= high(globalMarkers):
|
if globalMarkersLen <= high(globalMarkers):
|
||||||
globalMarkers[globalMarkersLen] = markerProc
|
globalMarkers[globalMarkersLen] = markerProc
|
||||||
inc globalMarkersLen
|
inc globalMarkersLen
|
||||||
|
|
@ -464,7 +464,7 @@ proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerProc.} =
|
||||||
cstderr.rawWrite("[GC] cannot register global variable; too many global variables")
|
cstderr.rawWrite("[GC] cannot register global variable; too many global variables")
|
||||||
quit 1
|
quit 1
|
||||||
|
|
||||||
proc nimRegisterThreadLocalMarker(markerProc: GlobalMarkerProc) {.compilerProc.} =
|
proc nimRegisterThreadLocalMarker(markerProc: GlobalMarkerProc) {.compilerproc.} =
|
||||||
if threadLocalMarkersLen <= high(threadLocalMarkers):
|
if threadLocalMarkersLen <= high(threadLocalMarkers):
|
||||||
threadLocalMarkers[threadLocalMarkersLen] = markerProc
|
threadLocalMarkers[threadLocalMarkersLen] = markerProc
|
||||||
inc threadLocalMarkersLen
|
inc threadLocalMarkersLen
|
||||||
|
|
|
||||||
|
|
@ -162,7 +162,7 @@ when defined(nimGcRefLeak):
|
||||||
|
|
||||||
var ax: array[10_000, GcStackTrace]
|
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:
|
# we keep it from being collected by pretending it's not even allocated:
|
||||||
when false:
|
when false:
|
||||||
when withBitvectors: excl(gch.allocated, usrToCell(p))
|
when withBitvectors: excl(gch.allocated, usrToCell(p))
|
||||||
|
|
@ -171,7 +171,7 @@ proc nimGCref(p: pointer) {.compilerProc.} =
|
||||||
captureStackTrace(framePtr, ax[gch.additionalRoots.len])
|
captureStackTrace(framePtr, ax[gch.additionalRoots.len])
|
||||||
add(gch.additionalRoots, usrToCell(p))
|
add(gch.additionalRoots, usrToCell(p))
|
||||||
|
|
||||||
proc nimGCunref(p: pointer) {.compilerProc.} =
|
proc nimGCunref(p: pointer) {.compilerproc.} =
|
||||||
let cell = usrToCell(p)
|
let cell = usrToCell(p)
|
||||||
var L = gch.additionalRoots.len-1
|
var L = gch.additionalRoots.len-1
|
||||||
var i = L
|
var i = L
|
||||||
|
|
@ -372,14 +372,14 @@ proc mark(gch: var GcHeap, c: PCell) =
|
||||||
c, c.typ.name)
|
c, c.typ.name)
|
||||||
inc gch.indentation, 2
|
inc gch.indentation, 2
|
||||||
|
|
||||||
c.refCount = rcBlack
|
c.refcount = rcBlack
|
||||||
gcAssert gch.tempStack.len == 0, "stack not empty!"
|
gcAssert gch.tempStack.len == 0, "stack not empty!"
|
||||||
forAllChildren(c, waMarkPrecise)
|
forAllChildren(c, waMarkPrecise)
|
||||||
while gch.tempStack.len > 0:
|
while gch.tempStack.len > 0:
|
||||||
dec gch.tempStack.len
|
dec gch.tempStack.len
|
||||||
var d = gch.tempStack.d[gch.tempStack.len]
|
var d = gch.tempStack.d[gch.tempStack.len]
|
||||||
if d.refcount == rcWhite:
|
if d.refcount == rcWhite:
|
||||||
d.refCount = rcBlack
|
d.refcount = rcBlack
|
||||||
forAllChildren(d, waMarkPrecise)
|
forAllChildren(d, waMarkPrecise)
|
||||||
|
|
||||||
when defined(nimTracing):
|
when defined(nimTracing):
|
||||||
|
|
|
||||||
|
|
@ -73,7 +73,7 @@ type
|
||||||
tyVoidHidden
|
tyVoidHidden
|
||||||
|
|
||||||
TNimNodeKind = enum nkNone, nkSlot, nkList, nkCase
|
TNimNodeKind = enum nkNone, nkSlot, nkList, nkCase
|
||||||
TNimNode {.compilerProc.} = object
|
TNimNode {.compilerproc.} = object
|
||||||
kind: TNimNodeKind
|
kind: TNimNodeKind
|
||||||
offset: int
|
offset: int
|
||||||
typ: ptr TNimType
|
typ: ptr TNimType
|
||||||
|
|
@ -86,7 +86,7 @@ type
|
||||||
ntfAcyclic = 1, # type cannot form a cycle
|
ntfAcyclic = 1, # type cannot form a cycle
|
||||||
ntfEnumHole = 2 # enum has holes and thus `$` for them needs the slow
|
ntfEnumHole = 2 # enum has holes and thus `$` for them needs the slow
|
||||||
# version
|
# version
|
||||||
TNimType {.compilerProc.} = object
|
TNimType {.compilerproc.} = object
|
||||||
size: int
|
size: int
|
||||||
kind: TNimKind
|
kind: TNimKind
|
||||||
flags: set[TNimTypeFlag]
|
flags: set[TNimTypeFlag]
|
||||||
|
|
@ -105,7 +105,7 @@ type
|
||||||
when defined(nimTypeNames):
|
when defined(nimTypeNames):
|
||||||
# Declare this variable only once in system.nim
|
# Declare this variable only once in system.nim
|
||||||
when declared(ThisIsSystem):
|
when declared(ThisIsSystem):
|
||||||
var nimTypeRoot {.compilerProc.}: PNimType
|
var nimTypeRoot {.compilerproc.}: PNimType
|
||||||
else:
|
else:
|
||||||
var nimTypeRoot {.importc.}: PNimType
|
var nimTypeRoot {.importc.}: PNimType
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ include inclrtl
|
||||||
# ----------------- IO Part ------------------------------------------------
|
# ----------------- IO Part ------------------------------------------------
|
||||||
type
|
type
|
||||||
CFile {.importc: "FILE", header: "<stdio.h>",
|
CFile {.importc: "FILE", header: "<stdio.h>",
|
||||||
incompletestruct.} = object
|
incompleteStruct.} = object
|
||||||
File* = ptr CFile ## The type representing a file handle.
|
File* = ptr CFile ## The type representing a file handle.
|
||||||
|
|
||||||
FileMode* = enum ## The file mode when opening a file.
|
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)
|
result = wfreopen(f, m, stream)
|
||||||
|
|
||||||
else:
|
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 {.
|
proc freopen(filename, mode: cstring, stream: File): File {.
|
||||||
importc: "freopen", nodecl.}
|
importc: "freopen", nodecl.}
|
||||||
|
|
||||||
|
|
@ -442,7 +442,7 @@ when defined(posix) and not defined(nimscript):
|
||||||
st_mode: Mode ## Mode of file
|
st_mode: Mode ## Mode of file
|
||||||
filler_2: array[144 - 24 - 4, char]
|
filler_2: array[144 - 24 - 4, char]
|
||||||
|
|
||||||
proc S_ISDIR(m: Mode): bool =
|
proc modeIsDir(m: Mode): bool =
|
||||||
## Test for a directory.
|
## Test for a directory.
|
||||||
(m and 0o170000) == 0o40000
|
(m and 0o170000) == 0o40000
|
||||||
|
|
||||||
|
|
@ -454,7 +454,7 @@ when defined(posix) and not defined(nimscript):
|
||||||
header: "<sys/stat.h>", final, pure.} = object ## struct stat
|
header: "<sys/stat.h>", final, pure.} = object ## struct stat
|
||||||
st_mode: Mode ## Mode of file
|
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.
|
## Test for a directory.
|
||||||
|
|
||||||
proc c_fstat(a1: cint, a2: var Stat): cint {.
|
proc c_fstat(a1: cint, a2: var Stat): cint {.
|
||||||
|
|
@ -476,7 +476,7 @@ proc open*(f: var File, filename: string,
|
||||||
# be opened.
|
# be opened.
|
||||||
var f2 = cast[File](p)
|
var f2 = cast[File](p)
|
||||||
var res: Stat
|
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)
|
close(f2)
|
||||||
return false
|
return false
|
||||||
result = true
|
result = true
|
||||||
|
|
@ -550,11 +550,11 @@ when declared(stdout):
|
||||||
var echoLock: SysLock
|
var echoLock: SysLock
|
||||||
initSysLock echoLock
|
initSysLock echoLock
|
||||||
|
|
||||||
proc echoBinSafe(args: openArray[string]) {.compilerProc.} =
|
proc echoBinSafe(args: openArray[string]) {.compilerproc.} =
|
||||||
# flockfile deadlocks some versions of Android 5.x.x
|
# flockfile deadlocks some versions of Android 5.x.x
|
||||||
when not defined(windows) and not defined(android) and not defined(nintendoswitch):
|
when not defined(windows) and not defined(android) and not defined(nintendoswitch):
|
||||||
proc flockfile(f: File) {.importc, noDecl.}
|
proc flockfile(f: File) {.importc, nodecl.}
|
||||||
proc funlockfile(f: File) {.importc, noDecl.}
|
proc funlockfile(f: File) {.importc, nodecl.}
|
||||||
flockfile(stdout)
|
flockfile(stdout)
|
||||||
when defined(windows) and compileOption("threads"):
|
when defined(windows) and compileOption("threads"):
|
||||||
acquireSys echoLock
|
acquireSys echoLock
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@
|
||||||
|
|
||||||
# Compilerprocs for strings that do not depend on the string implementation.
|
# 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 alen = a.len
|
||||||
let blen = b.len
|
let blen = b.len
|
||||||
let minlen = min(alen, blen)
|
let minlen = min(alen, blen)
|
||||||
|
|
@ -20,7 +20,7 @@ proc cmpStrings(a, b: string): int {.inline, compilerProc.} =
|
||||||
else:
|
else:
|
||||||
result = alen - blen
|
result = alen - blen
|
||||||
|
|
||||||
proc eqStrings(a, b: string): bool {.inline, compilerProc.} =
|
proc eqStrings(a, b: string): bool {.inline, compilerproc.} =
|
||||||
let alen = a.len
|
let alen = a.len
|
||||||
let blen = b.len
|
let blen = b.len
|
||||||
if alen == blen:
|
if alen == blen:
|
||||||
|
|
@ -135,7 +135,7 @@ const
|
||||||
1e20, 1e21, 1e22]
|
1e20, 1e21, 1e22]
|
||||||
|
|
||||||
proc nimParseBiggestFloat(s: string, number: var BiggestFloat,
|
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.
|
# This routine attempt to parse float that can parsed quickly.
|
||||||
# ie whose integer part can fit inside a 53bits integer.
|
# ie whose integer part can fit inside a 53bits integer.
|
||||||
# their real exponent must also be <= 22. If the float doesn't follow
|
# their real exponent must also be <= 22. If the float doesn't follow
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ else:
|
||||||
template allocStrNoInit(size: untyped): untyped =
|
template allocStrNoInit(size: untyped): untyped =
|
||||||
cast[NimString](newObjNoInit(addr(strDesc), size))
|
cast[NimString](newObjNoInit(addr(strDesc), size))
|
||||||
|
|
||||||
proc rawNewStringNoInit(space: int): NimString {.compilerProc.} =
|
proc rawNewStringNoInit(space: int): NimString {.compilerproc.} =
|
||||||
var s = space
|
var s = space
|
||||||
if s < 7: s = 7
|
if s < 7: s = 7
|
||||||
result = allocStrNoInit(sizeof(TGenericSeq) + s + 1)
|
result = allocStrNoInit(sizeof(TGenericSeq) + s + 1)
|
||||||
|
|
@ -49,7 +49,7 @@ proc rawNewStringNoInit(space: int): NimString {.compilerProc.} =
|
||||||
when defined(gogc):
|
when defined(gogc):
|
||||||
result.elemSize = 1
|
result.elemSize = 1
|
||||||
|
|
||||||
proc rawNewString(space: int): NimString {.compilerProc.} =
|
proc rawNewString(space: int): NimString {.compilerproc.} =
|
||||||
var s = space
|
var s = space
|
||||||
if s < 7: s = 7
|
if s < 7: s = 7
|
||||||
result = allocStr(sizeof(TGenericSeq) + s + 1)
|
result = allocStr(sizeof(TGenericSeq) + s + 1)
|
||||||
|
|
@ -58,11 +58,11 @@ proc rawNewString(space: int): NimString {.compilerProc.} =
|
||||||
when defined(gogc):
|
when defined(gogc):
|
||||||
result.elemSize = 1
|
result.elemSize = 1
|
||||||
|
|
||||||
proc mnewString(len: int): NimString {.compilerProc.} =
|
proc mnewString(len: int): NimString {.compilerproc.} =
|
||||||
result = rawNewString(len)
|
result = rawNewString(len)
|
||||||
result.len = 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
|
# This is not used by most recent versions of the compiler anymore, but
|
||||||
# required for bootstrapping purposes.
|
# required for bootstrapping purposes.
|
||||||
let start = max(start, 0)
|
let start = max(start, 0)
|
||||||
|
|
@ -76,17 +76,17 @@ proc copyStrLast(s: NimString, start, last: int): NimString {.compilerProc.} =
|
||||||
else:
|
else:
|
||||||
result = rawNewString(len)
|
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
|
# This is not used by most recent versions of the compiler anymore, but
|
||||||
# required for bootstrapping purposes.
|
# required for bootstrapping purposes.
|
||||||
if s == nil: return nil
|
if s == nil: return nil
|
||||||
result = copyStrLast(s, start, s.len-1)
|
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""
|
if s == nil or s.len == 0: result = cstring""
|
||||||
else: result = cstring(addr s.data)
|
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 = rawNewStringNoInit(len)
|
||||||
result.len = len
|
result.len = len
|
||||||
copyMem(addr(result.data), str, len + 1)
|
copyMem(addr(result.data), str, len + 1)
|
||||||
|
|
@ -245,7 +245,7 @@ proc setLengthStr(s: NimString, newLen: int): NimString {.compilerRtl.} =
|
||||||
|
|
||||||
# ----------------- sequences ----------------------------------------------
|
# ----------------- sequences ----------------------------------------------
|
||||||
|
|
||||||
proc incrSeq(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
|
proc incrSeq(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerproc.} =
|
||||||
# increments the length by one:
|
# increments the length by one:
|
||||||
# this is needed for supporting ``add``;
|
# this is needed for supporting ``add``;
|
||||||
#
|
#
|
||||||
|
|
@ -260,7 +260,7 @@ proc incrSeq(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
|
||||||
result.reserved = r
|
result.reserved = r
|
||||||
inc(result.len)
|
inc(result.len)
|
||||||
|
|
||||||
proc incrSeqV2(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
|
proc incrSeqV2(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerproc.} =
|
||||||
# incrSeq version 2
|
# incrSeq version 2
|
||||||
result = seq
|
result = seq
|
||||||
if result.len >= result.space:
|
if result.len >= result.space:
|
||||||
|
|
@ -272,7 +272,7 @@ proc incrSeqV2(seq: PGenericSeq, elemSize: int): PGenericSeq {.compilerProc.} =
|
||||||
template `+!`(p: pointer, s: int): pointer =
|
template `+!`(p: pointer, s: int): pointer =
|
||||||
cast[pointer](cast[int](p) +% s)
|
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:
|
if s == nil:
|
||||||
result = cast[PGenericSeq](newSeq(typ, 1))
|
result = cast[PGenericSeq](newSeq(typ, 1))
|
||||||
result.len = 0
|
result.len = 0
|
||||||
|
|
|
||||||
|
|
@ -14,8 +14,10 @@
|
||||||
|
|
||||||
import dynlib
|
import dynlib
|
||||||
|
|
||||||
|
when defined(nimHasStyleChecks):
|
||||||
|
{.push styleChecks: off.}
|
||||||
|
|
||||||
{.passC: "-DWIN32_LEAN_AND_MEAN".}
|
{.passc: "-DWIN32_LEAN_AND_MEAN".}
|
||||||
|
|
||||||
const
|
const
|
||||||
useWinUnicode* = not defined(useWinAnsi)
|
useWinUnicode* = not defined(useWinAnsi)
|
||||||
|
|
@ -136,11 +138,11 @@ proc getVersion*(): DWORD {.stdcall, dynlib: "kernel32", importc: "GetVersion".}
|
||||||
proc closeHandle*(hObject: Handle): WINBOOL {.stdcall, dynlib: "kernel32",
|
proc closeHandle*(hObject: Handle): WINBOOL {.stdcall, dynlib: "kernel32",
|
||||||
importc: "CloseHandle".}
|
importc: "CloseHandle".}
|
||||||
|
|
||||||
proc readFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToRead: int32,
|
proc readFile*(hFile: Handle, buffer: pointer, nNumberOfBytesToRead: int32,
|
||||||
lpNumberOfBytesRead: ptr int32, lpOverlapped: pointer): WINBOOL{.
|
lpNumberOfBytesRead: ptr int32, lpOverlapped: pointer): WINBOOL{.
|
||||||
stdcall, dynlib: "kernel32", importc: "ReadFile".}
|
stdcall, dynlib: "kernel32", importc: "ReadFile".}
|
||||||
|
|
||||||
proc writeFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToWrite: int32,
|
proc writeFile*(hFile: Handle, buffer: pointer, nNumberOfBytesToWrite: int32,
|
||||||
lpNumberOfBytesWritten: ptr int32,
|
lpNumberOfBytesWritten: ptr int32,
|
||||||
lpOverlapped: pointer): WINBOOL{.
|
lpOverlapped: pointer): WINBOOL{.
|
||||||
stdcall, dynlib: "kernel32", importc: "WriteFile".}
|
stdcall, dynlib: "kernel32", importc: "WriteFile".}
|
||||||
|
|
@ -215,13 +217,13 @@ when useWinUnicode:
|
||||||
proc formatMessageW*(dwFlags: int32, lpSource: pointer,
|
proc formatMessageW*(dwFlags: int32, lpSource: pointer,
|
||||||
dwMessageId, dwLanguageId: int32,
|
dwMessageId, dwLanguageId: int32,
|
||||||
lpBuffer: pointer, nSize: int32,
|
lpBuffer: pointer, nSize: int32,
|
||||||
Arguments: pointer): int32 {.
|
arguments: pointer): int32 {.
|
||||||
importc: "FormatMessageW", stdcall, dynlib: "kernel32".}
|
importc: "FormatMessageW", stdcall, dynlib: "kernel32".}
|
||||||
else:
|
else:
|
||||||
proc formatMessageA*(dwFlags: int32, lpSource: pointer,
|
proc formatMessageA*(dwFlags: int32, lpSource: pointer,
|
||||||
dwMessageId, dwLanguageId: int32,
|
dwMessageId, dwLanguageId: int32,
|
||||||
lpBuffer: pointer, nSize: int32,
|
lpBuffer: pointer, nSize: int32,
|
||||||
Arguments: pointer): int32 {.
|
arguments: pointer): int32 {.
|
||||||
importc: "FormatMessageA", stdcall, dynlib: "kernel32".}
|
importc: "FormatMessageA", stdcall, dynlib: "kernel32".}
|
||||||
|
|
||||||
proc localFree*(p: pointer) {.
|
proc localFree*(p: pointer) {.
|
||||||
|
|
@ -414,13 +416,13 @@ proc sleep*(dwMilliseconds: int32){.stdcall, dynlib: "kernel32",
|
||||||
importc: "Sleep".}
|
importc: "Sleep".}
|
||||||
|
|
||||||
when useWinUnicode:
|
when useWinUnicode:
|
||||||
proc shellExecuteW*(HWND: Handle, lpOperation, lpFile,
|
proc shellExecuteW*(hwnd: Handle, lpOperation, lpFile,
|
||||||
lpParameters, lpDirectory: WideCString,
|
lpParameters, lpDirectory: WideCString,
|
||||||
nShowCmd: int32): Handle{.
|
nShowCmd: int32): Handle{.
|
||||||
stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW".}
|
stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW".}
|
||||||
|
|
||||||
else:
|
else:
|
||||||
proc shellExecuteA*(HWND: Handle, lpOperation, lpFile,
|
proc shellExecuteA*(hwnd: Handle, lpOperation, lpFile,
|
||||||
lpParameters, lpDirectory: cstring,
|
lpParameters, lpDirectory: cstring,
|
||||||
nShowCmd: int32): Handle{.
|
nShowCmd: int32): Handle{.
|
||||||
stdcall, dynlib: "shell32.dll", importc: "ShellExecuteA".}
|
stdcall, dynlib: "shell32.dll", importc: "ShellExecuteA".}
|
||||||
|
|
@ -482,12 +484,6 @@ type
|
||||||
sin6_addr*: In6_addr
|
sin6_addr*: In6_addr
|
||||||
sin6_scope_id*: int32 # unsigned
|
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",
|
Sockaddr_storage* {.importc: "SOCKADDR_STORAGE",
|
||||||
header: "winsock2.h".} = object
|
header: "winsock2.h".} = object
|
||||||
ss_family*: uint16
|
ss_family*: uint16
|
||||||
|
|
@ -707,18 +703,18 @@ const
|
||||||
ERROR_HANDLE_EOF* = 38
|
ERROR_HANDLE_EOF* = 38
|
||||||
ERROR_BAD_ARGUMENTS* = 165
|
ERROR_BAD_ARGUMENTS* = 165
|
||||||
|
|
||||||
proc duplicateHandle*(hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE,
|
proc duplicateHandle*(hSourceProcessHandle: Handle, hSourceHandle: Handle,
|
||||||
hTargetProcessHandle: HANDLE,
|
hTargetProcessHandle: Handle,
|
||||||
lpTargetHandle: ptr HANDLE,
|
lpTargetHandle: ptr Handle,
|
||||||
dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
|
dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
|
||||||
dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32",
|
dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32",
|
||||||
importc: "DuplicateHandle".}
|
importc: "DuplicateHandle".}
|
||||||
|
|
||||||
proc setHandleInformation*(hObject: HANDLE, dwMask: DWORD,
|
proc setHandleInformation*(hObject: Handle, dwMask: DWORD,
|
||||||
dwFlags: DWORD): WINBOOL {.stdcall,
|
dwFlags: DWORD): WINBOOL {.stdcall,
|
||||||
dynlib: "kernel32", importc: "SetHandleInformation".}
|
dynlib: "kernel32", importc: "SetHandleInformation".}
|
||||||
|
|
||||||
proc getCurrentProcess*(): HANDLE{.stdcall, dynlib: "kernel32",
|
proc getCurrentProcess*(): Handle{.stdcall, dynlib: "kernel32",
|
||||||
importc: "GetCurrentProcess".}
|
importc: "GetCurrentProcess".}
|
||||||
|
|
||||||
when useWinUnicode:
|
when useWinUnicode:
|
||||||
|
|
@ -1004,7 +1000,7 @@ const
|
||||||
type
|
type
|
||||||
WAITORTIMERCALLBACK* = proc(para1: pointer, para2: int32): void {.stdcall.}
|
WAITORTIMERCALLBACK* = proc(para1: pointer, para2: int32): void {.stdcall.}
|
||||||
|
|
||||||
proc postQueuedCompletionStatus*(CompletionPort: HANDLE,
|
proc postQueuedCompletionStatus*(CompletionPort: Handle,
|
||||||
dwNumberOfBytesTransferred: DWORD,
|
dwNumberOfBytesTransferred: DWORD,
|
||||||
dwCompletionKey: ULONG_PTR,
|
dwCompletionKey: ULONG_PTR,
|
||||||
lpOverlapped: pointer): bool
|
lpOverlapped: pointer): bool
|
||||||
|
|
@ -1017,7 +1013,7 @@ proc registerWaitForSingleObject*(phNewWaitObject: ptr Handle, hObject: Handle,
|
||||||
dwFlags: ULONG): bool
|
dwFlags: ULONG): bool
|
||||||
{.stdcall, dynlib: "kernel32", importc: "RegisterWaitForSingleObject".}
|
{.stdcall, dynlib: "kernel32", importc: "RegisterWaitForSingleObject".}
|
||||||
|
|
||||||
proc unregisterWait*(WaitHandle: HANDLE): DWORD
|
proc unregisterWait*(WaitHandle: Handle): DWORD
|
||||||
{.stdcall, dynlib: "kernel32", importc: "UnregisterWait".}
|
{.stdcall, dynlib: "kernel32", importc: "UnregisterWait".}
|
||||||
|
|
||||||
proc openProcess*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
|
proc openProcess*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
|
||||||
|
|
@ -1104,6 +1100,9 @@ proc toFILETIME*(t: int64): FILETIME =
|
||||||
type
|
type
|
||||||
LPFILETIME* = ptr FILETIME
|
LPFILETIME* = ptr FILETIME
|
||||||
|
|
||||||
proc setFileTime*(hFile: HANDLE, lpCreationTime: LPFILETIME,
|
proc setFileTime*(hFile: Handle, lpCreationTime: LPFILETIME,
|
||||||
lpLastAccessTime: LPFILETIME, lpLastWriteTime: LPFILETIME): WINBOOL
|
lpLastAccessTime: LPFILETIME, lpLastWriteTime: LPFILETIME): WINBOOL
|
||||||
{.stdcall, dynlib: "kernel32", importc: "SetFileTime".}
|
{.stdcall, dynlib: "kernel32", importc: "SetFileTime".}
|
||||||
|
|
||||||
|
when defined(nimHasStyleChecks):
|
||||||
|
{.pop.} # {.push styleChecks: off.}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue