there is only one style -- my style

This commit is contained in:
Araq 2019-07-10 19:17:06 +02:00
commit 87a2ced1ba
16 changed files with 232 additions and 213 deletions

View file

@ -1474,20 +1474,20 @@ proc registerModuleToMain(g: BModuleList; m: BModule) =
datInit = m.getDatInitName datInit = m.getDatInitName
if m.hcrOn: if m.hcrOn:
var hcr_module_meta = "$nN_LIB_PRIVATE const char* hcr_module_list[] = {$n" % [] var hcrModuleMeta = "$nN_LIB_PRIVATE const char* hcr_module_list[] = {$n" % []
let systemModulePath = getModuleDllPath(m, g.modules[g.graph.config.m.systemFileIdx.int].module) let systemModulePath = getModuleDllPath(m, g.modules[g.graph.config.m.systemFileIdx.int].module)
let mainModulePath = getModuleDllPath(m, m.module) let mainModulePath = getModuleDllPath(m, m.module)
if sfMainModule in m.module.flags: if sfMainModule in m.module.flags:
addf(hcr_module_meta, "\t$1,$n", [systemModulePath]) addf(hcrModuleMeta, "\t$1,$n", [systemModulePath])
g.graph.importDeps.withValue(FileIndex(m.module.position), deps): g.graph.importDeps.withValue(FileIndex(m.module.position), deps):
for curr in deps[]: for curr in deps[]:
addf(hcr_module_meta, "\t$1,$n", [getModuleDllPath(m, g.modules[curr.int].module)]) addf(hcrModuleMeta, "\t$1,$n", [getModuleDllPath(m, g.modules[curr.int].module)])
addf(hcr_module_meta, "\t\"\"};$n", []) addf(hcrModuleMeta, "\t\"\"};$n", [])
addf(hcr_module_meta, "$nN_LIB_EXPORT N_NIMCALL(void**, HcrGetImportedModules)() { return (void**)hcr_module_list; }$n", []) addf(hcrModuleMeta, "$nN_LIB_EXPORT N_NIMCALL(void**, HcrGetImportedModules)() { return (void**)hcr_module_list; }$n", [])
addf(hcr_module_meta, "$nN_LIB_EXPORT N_NIMCALL(char*, HcrGetSigHash)() { return \"$1\"; }$n$n", addf(hcrModuleMeta, "$nN_LIB_EXPORT N_NIMCALL(char*, HcrGetSigHash)() { return \"$1\"; }$n$n",
[($sigHash(m.module)).rope]) [($sigHash(m.module)).rope])
if sfMainModule in m.module.flags: if sfMainModule in m.module.flags:
add(g.mainModProcs, hcr_module_meta) add(g.mainModProcs, hcrModuleMeta)
addf(g.mainModProcs, "static void* hcr_handle;$N", []) addf(g.mainModProcs, "static void* hcr_handle;$N", [])
addf(g.mainModProcs, "N_LIB_EXPORT N_NIMCALL(void, $1)(void);$N", [init]) addf(g.mainModProcs, "N_LIB_EXPORT N_NIMCALL(void, $1)(void);$N", [init])
addf(g.mainModProcs, "N_LIB_EXPORT N_NIMCALL(void, $1)(void);$N", [datInit]) addf(g.mainModProcs, "N_LIB_EXPORT N_NIMCALL(void, $1)(void);$N", [datInit])
@ -1511,7 +1511,7 @@ proc registerModuleToMain(g: BModuleList; m: BModule) =
add(g.mainDatInit, "\t*cmd_count = cmdCount;\n") add(g.mainDatInit, "\t*cmd_count = cmdCount;\n")
add(g.mainDatInit, "\t*cmd_line = cmdLine;\n") add(g.mainDatInit, "\t*cmd_line = cmdLine;\n")
else: else:
add(m.s[cfsInitProc], hcr_module_meta) add(m.s[cfsInitProc], hcrModuleMeta)
return return
if m.s[cfsDatInitProc].len > 0: if m.s[cfsDatInitProc].len > 0:
@ -1876,11 +1876,11 @@ proc myProcess(b: PPassContext, n: PNode): PNode =
m.initProc.options = initProcOptions(m) m.initProc.options = initProcOptions(m)
#softRnl = if optLineDir in m.config.options: noRnl else: rnl #softRnl = if optLineDir in m.config.options: noRnl else: rnl
# XXX replicate this logic! # XXX replicate this logic!
let transformed_n = transformStmt(m.g.graph, m.module, n) let transformedN = transformStmt(m.g.graph, m.module, n)
if m.hcrOn: if m.hcrOn:
addHcrInitGuards(m.initProc, transformed_n, m.inHcrInitGuard) addHcrInitGuards(m.initProc, transformedN, m.inHcrInitGuard)
else: else:
genStmts(m.initProc, transformed_n) genStmts(m.initProc, transformedN)
proc shouldRecompile(m: BModule; code: Rope, cfile: Cfile): bool = proc shouldRecompile(m: BModule; code: Rope, cfile: Cfile): bool =
result = true result = true
@ -2020,7 +2020,7 @@ proc myClose(graph: ModuleGraph; b: PPassContext, n: PNode): PNode =
let disp = generateMethodDispatchers(graph) let disp = generateMethodDispatchers(graph)
for x in disp: genProcAux(m, x.sym) for x in disp: genProcAux(m, x.sym)
m.g.modules_closed.add m m.g.modulesClosed.add m
proc genForwardedProcs(g: BModuleList) = proc genForwardedProcs(g: BModuleList) =
# Forward declared proc:s lack bodies when first encountered, so they're given # Forward declared proc:s lack bodies when first encountered, so they're given

View file

@ -114,7 +114,7 @@ type
mainModProcs*, mainModInit*, otherModsInit*, mainDatInit*: Rope mainModProcs*, mainModInit*, otherModsInit*, mainDatInit*: Rope
mapping*: Rope # the generated mapping file (if requested) mapping*: Rope # the generated mapping file (if requested)
modules*: seq[BModule] # list of all compiled modules modules*: seq[BModule] # list of all compiled modules
modules_closed*: seq[BModule] # list of the same compiled modules, but in the order they were closed modulesClosed*: seq[BModule] # list of the same compiled modules, but in the order they were closed
forwardedProcs*: seq[PSym] # proc:s that did not yet have a body forwardedProcs*: seq[PSym] # proc:s that did not yet have a body
generatedHeader*: BModule generatedHeader*: BModule
breakPointId*: int breakPointId*: int
@ -196,6 +196,6 @@ proc newModuleList*(g: ModuleGraph): BModuleList =
config: g.config, graph: g, nimtvDeclared: initIntSet()) config: g.config, graph: g, nimtvDeclared: initIntSet())
iterator cgenModules*(g: BModuleList): BModule = iterator cgenModules*(g: BModuleList): BModule =
for m in g.modules_closed: for m in g.modulesClosed:
# iterate modules in the order they were closed # iterate modules in the order they were closed
yield m yield m

View file

@ -119,10 +119,10 @@ use(x)
Generates: Generates:
L0: fork L1 L0: fork lab1
join L0 # patched. join L0 # patched.
goto Louter goto Louter
L1: lab1:
def x def x
join L0 join L0
Louter: Louter:
@ -354,24 +354,24 @@ when true:
else: else:
proc genWhile(c: var Con; n: PNode) = proc genWhile(c: var Con; n: PNode) =
# L1: # lab1:
# cond, tmp # cond, tmp
# fork tmp, L2 # fork tmp, lab2
# body # body
# jmp L1 # jmp lab1
# L2: # lab2:
let oldForksLen = c.forks.len let oldForksLen = c.forks.len
let L1 = c.genLabel let lab1 = c.genLabel
withBlock(nil): withBlock(nil):
if isTrue(n.sons[0]): if isTrue(n.sons[0]):
c.gen(n.sons[1]) c.gen(n.sons[1])
c.jmpBack(n, L1) c.jmpBack(n, lab1)
else: else:
c.gen(n.sons[0]) c.gen(n.sons[0])
let L2 = c.forkI(n) let lab2 = c.forkI(n)
c.gen(n.sons[1]) c.gen(n.sons[1])
c.jmpBack(n, L1) c.jmpBack(n, lab1)
c.patch(L2) c.patch(lab2)
setLen(c.forks, oldForksLen) setLen(c.forks, oldForksLen)
proc genBlock(c: var Con; n: PNode) = proc genBlock(c: var Con; n: PNode) =
@ -383,23 +383,23 @@ proc genJoins(c: var Con; n: PNode) =
proc genBreak(c: var Con; n: PNode) = proc genBreak(c: var Con; n: PNode) =
genJoins(c, n) genJoins(c, n)
let L1 = c.gotoI(n) let lab1 = c.gotoI(n)
if n.sons[0].kind == nkSym: if n.sons[0].kind == nkSym:
#echo cast[int](n.sons[0].sym) #echo cast[int](n.sons[0].sym)
for i in countdown(c.blocks.len-1, 0): for i in countdown(c.blocks.len-1, 0):
if c.blocks[i].label == n.sons[0].sym: if c.blocks[i].label == n.sons[0].sym:
c.blocks[i].fixups.add L1 c.blocks[i].fixups.add lab1
return return
#globalError(n.info, "VM problem: cannot find 'break' target") #globalError(n.info, "VM problem: cannot find 'break' target")
else: else:
c.blocks[c.blocks.high].fixups.add L1 c.blocks[c.blocks.high].fixups.add lab1
template forkT(n, body) = template forkT(n, body) =
let oldLen = c.forks.len let oldLen = c.forks.len
let L1 = c.forkI(n) let lab1 = c.forkI(n)
body body
c.patch(L1) c.patch(lab1)
c.joinI(L1, n) c.joinI(lab1, n)
setLen(c.forks, oldLen) setLen(c.forks, oldLen)
proc genIf(c: var Con, n: PNode) = proc genIf(c: var Con, n: PNode) =
@ -415,15 +415,15 @@ proc genIf(c: var Con, n: PNode) =
D D
cond cond
fork L1 fork lab1
A A
goto Lend goto Lend
L1: lab1:
condB condB
fork L2 fork lab2
B B
goto Lend2 goto Lend2
L2: lab2:
condC condC
fork L3 fork L3
C C
@ -457,23 +457,23 @@ proc genIf(c: var Con, n: PNode) =
proc genAndOr(c: var Con; n: PNode) = proc genAndOr(c: var Con; n: PNode) =
# asgn dest, a # asgn dest, a
# fork L1 # fork lab1
# asgn dest, b # asgn dest, b
# L1: # lab1:
# join F1 # join F1
c.gen(n.sons[1]) c.gen(n.sons[1])
forkT(n): forkT(n):
c.gen(n.sons[2]) c.gen(n.sons[2])
proc genCase(c: var Con; n: PNode) = proc genCase(c: var Con; n: PNode) =
# if (!expr1) goto L1; # if (!expr1) goto lab1;
# thenPart # thenPart
# goto LEnd # goto LEnd
# L1: # lab1:
# if (!expr2) goto L2; # if (!expr2) goto lab2;
# thenPart2 # thenPart2
# goto LEnd # goto LEnd
# L2: # lab2:
# elsePart # elsePart
# Lend: # Lend:
let isExhaustive = skipTypes(n.sons[0].typ, let isExhaustive = skipTypes(n.sons[0].typ,
@ -714,9 +714,9 @@ proc genCall(c: var Con; n: PNode) =
# every call can potentially raise: # every call can potentially raise:
if c.inTryStmt > 0 and canRaise(n[0]): if c.inTryStmt > 0 and canRaise(n[0]):
# we generate the instruction sequence: # we generate the instruction sequence:
# fork L1 # fork lab1
# goto exceptionHandler (except or finally) # goto exceptionHandler (except or finally)
# L1: # lab1:
# join F1 # join F1
let endGoto = c.forkI(n) let endGoto = c.forkI(n)
c.tryStmtFixups.add c.gotoI(n) c.tryStmtFixups.add c.gotoI(n)

View file

@ -2260,8 +2260,8 @@ proc genProc(oldProc: PProc, prc: PSym): Rope =
else: else:
returnStmt = "return $#;$n" % [a.res] returnStmt = "return $#;$n" % [a.res]
let transformed_body = transformBody(oldProc.module.graph, prc, cache = false) let transformedBody = transformBody(oldProc.module.graph, prc, cache = false)
p.nested: genStmt(p, transformed_body) p.nested: genStmt(p, transformedBody)
var def: Rope var def: Rope
if not prc.constraint.isNil: if not prc.constraint.isNil:
@ -2541,7 +2541,7 @@ proc genModule(p: PProc, n: PNode) =
add(p.body, frameCreate(p, add(p.body, frameCreate(p,
makeJSString("module " & p.module.module.name.s), makeJSString("module " & p.module.module.name.s),
makeJSString(toFilename(p.config, p.module.module.info)))) makeJSString(toFilename(p.config, p.module.module.info))))
let n_transformed = transformStmt(p.module.graph, p.module.module, n) let transformedN = transformStmt(p.module.graph, p.module.module, n)
if p.config.hcrOn and n.kind == nkStmtList: if p.config.hcrOn and n.kind == nkStmtList:
let moduleSym = p.module.module let moduleSym = p.module.module
var moduleLoadedVar = rope(moduleSym.name.s) & "_loaded" & var moduleLoadedVar = rope(moduleSym.name.s) & "_loaded" &
@ -2549,7 +2549,7 @@ proc genModule(p: PProc, n: PNode) =
lineF(p, "var $1;$n", [moduleLoadedVar]) lineF(p, "var $1;$n", [moduleLoadedVar])
var inGuardedBlock = false var inGuardedBlock = false
addHcrInitGuards(p, n_transformed, moduleLoadedVar, inGuardedBlock) addHcrInitGuards(p, transformedN, moduleLoadedVar, inGuardedBlock)
if inGuardedBlock: if inGuardedBlock:
dec p.extraIndent dec p.extraIndent
@ -2557,7 +2557,7 @@ proc genModule(p: PProc, n: PNode) =
lineF(p, "$1 = true;$n", [moduleLoadedVar]) lineF(p, "$1 = true;$n", [moduleLoadedVar])
else: else:
genStmt(p, n_transformed) genStmt(p, transformedN)
if optStackTrace in p.options: if optStackTrace in p.options:
add(p.body, frameDestroy(p)) add(p.body, frameDestroy(p))

View file

@ -897,10 +897,10 @@ proc accentedName(g: var TSrcGen, n: PNode) =
proc infixArgument(g: var TSrcGen, n: PNode, i: int) = proc infixArgument(g: var TSrcGen, n: PNode, i: int) =
if i < 1 and i > 2: return if i < 1 and i > 2: return
var needsParenthesis = false var needsParenthesis = false
let n_next = n[i].skipHiddenNodes let nNext = n[i].skipHiddenNodes
if n_next.kind == nkInfix: if nNext.kind == nkInfix:
if n_next[0].kind in {nkSym, nkIdent} and n[0].kind in {nkSym, nkIdent}: if nNext[0].kind in {nkSym, nkIdent} and n[0].kind in {nkSym, nkIdent}:
let nextId = if n_next[0].kind == nkSym: n_next[0].sym.name else: n_next[0].ident let nextId = if nNext[0].kind == nkSym: nNext[0].sym.name else: nNext[0].ident
let nnId = if n[0].kind == nkSym: n[0].sym.name else: n[0].ident let nnId = if n[0].kind == nkSym: n[0].sym.name else: n[0].ident
if i == 1: if i == 1:
if getPrecedence(nextId) < getPrecedence(nnId): if getPrecedence(nextId) < getPrecedence(nnId):
@ -1144,10 +1144,10 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext) =
elif n[0].kind == nkSym: n[0].sym.name elif n[0].kind == nkSym: n[0].sym.name
elif n[0].kind in {nkOpenSymChoice, nkClosedSymChoice}: n[0][0].sym.name elif n[0].kind in {nkOpenSymChoice, nkClosedSymChoice}: n[0][0].sym.name
else: nil else: nil
let n_next = skipHiddenNodes(n[1]) let nNext = skipHiddenNodes(n[1])
if n_next.kind == nkPrefix or (opr != nil and renderer.isKeyword(opr)): if nNext.kind == nkPrefix or (opr != nil and renderer.isKeyword(opr)):
put(g, tkSpaces, Space) put(g, tkSpaces, Space)
if n_next.kind == nkInfix: if nNext.kind == nkInfix:
put(g, tkParLe, "(") put(g, tkParLe, "(")
gsub(g, n.sons[1]) gsub(g, n.sons[1])
put(g, tkParRi, ")") put(g, tkParRi, ")")

View file

@ -189,16 +189,16 @@ proc semTry(c: PContext, n: PNode; flags: TExprFlags): PNode =
template semExceptBranchType(typeNode: PNode): bool = template semExceptBranchType(typeNode: PNode): bool =
# returns true if exception type is imported type # returns true if exception type is imported type
let typ = semTypeNode(c, typeNode, nil).toObject() let typ = semTypeNode(c, typeNode, nil).toObject()
var is_imported = false var isImported = false
if isImportedException(typ, c.config): if isImportedException(typ, c.config):
is_imported = true isImported = true
elif not isException(typ): elif not isException(typ):
localError(c.config, typeNode.info, errExprCannotBeRaised) localError(c.config, typeNode.info, errExprCannotBeRaised)
if containsOrIncl(check, typ.id): if containsOrIncl(check, typ.id):
localError(c.config, typeNode.info, errExceptionAlreadyHandled) localError(c.config, typeNode.info, errExceptionAlreadyHandled)
typeNode = newNodeIT(nkType, typeNode.info, typ) typeNode = newNodeIT(nkType, typeNode.info, typ)
is_imported isImported
result = n result = n
inc c.p.inTryStmt inc c.p.inTryStmt
@ -223,9 +223,9 @@ proc semTry(c: PContext, n: PNode; flags: TExprFlags): PNode =
if a.len == 2 and a[0].isInfixAs(): if a.len == 2 and a[0].isInfixAs():
# support ``except Exception as ex: body`` # support ``except Exception as ex: body``
let is_imported = semExceptBranchType(a[0][1]) let isImported = semExceptBranchType(a[0][1])
let symbol = newSymG(skLet, a[0][2], c) let symbol = newSymG(skLet, a[0][2], c)
symbol.typ = if is_imported: a[0][1].typ symbol.typ = if isImported: a[0][1].typ
else: a[0][1].typ.toRef() else: a[0][1].typ.toRef()
addDecl(c, symbol) addDecl(c, symbol)
# Overwrite symbol in AST with the symbol in the symbol table. # Overwrite symbol in AST with the symbol in the symbol table.
@ -241,13 +241,13 @@ proc semTry(c: PContext, n: PNode; flags: TExprFlags): PNode =
# if ``except: body`` already encountered, # if ``except: body`` already encountered,
# cannot be followed by a ``except KeyError, ... : body`` block # cannot be followed by a ``except KeyError, ... : body`` block
inc catchAllExcepts inc catchAllExcepts
var is_native, is_imported: bool var isNative, isImported: bool
for j in 0..a.len-2: for j in 0..a.len-2:
let tmp = semExceptBranchType(a[j]) let tmp = semExceptBranchType(a[j])
if tmp: is_imported = true if tmp: isImported = true
else: is_native = true else: isNative = true
if is_native and is_imported: if isNative and isImported:
localError(c.config, a[0].info, "Mix of imported and native exception types is not allowed in one except branch") localError(c.config, a[0].info, "Mix of imported and native exception types is not allowed in one except branch")
elif a.kind == nkFinally: elif a.kind == nkFinally:

View file

@ -143,17 +143,17 @@ proc computeObjectOffsetsFoldFunction(conf: ConfigRef; n: PNode,
result.align = 1 # maximum of all member alignments result.align = 1 # maximum of all member alignments
var offset = initialOffset var offset = initialOffset
for i, child in n.sons: for i, child in n.sons:
let (new_offset, align) = computeObjectOffsetsFoldFunction(conf, child, offset) let (newOffset, align) = computeObjectOffsetsFoldFunction(conf, child, offset)
if new_offset == szIllegalRecursion: if newOffset == szIllegalRecursion:
result.offset = szIllegalRecursion result.offset = szIllegalRecursion
result.align = szIllegalRecursion result.align = szIllegalRecursion
return return
elif new_offset == szUnknownSize or offset == szUnknownSize: elif newOffset == szUnknownSize or offset == szUnknownSize:
# if anything is unknown, the rest becomes unknown as well # if anything is unknown, the rest becomes unknown as well
offset = szUnknownSize offset = szUnknownSize
result.align = szUnknownSize result.align = szUnknownSize
else: else:
offset = new_offset offset = newOffset
result.align = max(result.align, align) result.align = max(result.align, align)
# final alignment # final alignment
if offset == szUnknownSize: if offset == szUnknownSize:

View file

@ -304,31 +304,31 @@ proc isTrue(n: PNode): bool =
n.kind == nkIntLit and n.intVal != 0 n.kind == nkIntLit and n.intVal != 0
proc genWhile(c: PCtx; n: PNode) = proc genWhile(c: PCtx; n: PNode) =
# L1: # lab1:
# cond, tmp # cond, tmp
# fjmp tmp, L2 # fjmp tmp, lab2
# body # body
# jmp L1 # jmp lab1
# L2: # lab2:
let L1 = c.genLabel let lab1 = c.genLabel
withBlock(nil): withBlock(nil):
if isTrue(n.sons[0]): if isTrue(n.sons[0]):
c.gen(n.sons[1]) c.gen(n.sons[1])
c.jmpBack(n, L1) c.jmpBack(n, lab1)
elif isNotOpr(n.sons[0]): elif isNotOpr(n.sons[0]):
var tmp = c.genx(n.sons[0].sons[1]) var tmp = c.genx(n.sons[0].sons[1])
let L2 = c.xjmp(n, opcTJmp, tmp) let lab2 = c.xjmp(n, opcTJmp, tmp)
c.freeTemp(tmp) c.freeTemp(tmp)
c.gen(n.sons[1]) c.gen(n.sons[1])
c.jmpBack(n, L1) c.jmpBack(n, lab1)
c.patch(L2) c.patch(lab2)
else: else:
var tmp = c.genx(n.sons[0]) var tmp = c.genx(n.sons[0])
let L2 = c.xjmp(n, opcFJmp, tmp) let lab2 = c.xjmp(n, opcFJmp, tmp)
c.freeTemp(tmp) c.freeTemp(tmp)
c.gen(n.sons[1]) c.gen(n.sons[1])
c.jmpBack(n, L1) c.jmpBack(n, lab1)
c.patch(L2) c.patch(lab2)
proc genBlock(c: PCtx; n: PNode; dest: var TDest) = proc genBlock(c: PCtx; n: PNode; dest: var TDest) =
let oldRegisterCount = c.prc.maxSlots let oldRegisterCount = c.prc.maxSlots
@ -342,26 +342,26 @@ proc genBlock(c: PCtx; n: PNode; dest: var TDest) =
c.clearDest(n, dest) c.clearDest(n, dest)
proc genBreak(c: PCtx; n: PNode) = proc genBreak(c: PCtx; n: PNode) =
let L1 = c.xjmp(n, opcJmp) let lab1 = c.xjmp(n, opcJmp)
if n.sons[0].kind == nkSym: if n.sons[0].kind == nkSym:
#echo cast[int](n.sons[0].sym) #echo cast[int](n.sons[0].sym)
for i in countdown(c.prc.blocks.len-1, 0): for i in countdown(c.prc.blocks.len-1, 0):
if c.prc.blocks[i].label == n.sons[0].sym: if c.prc.blocks[i].label == n.sons[0].sym:
c.prc.blocks[i].fixups.add L1 c.prc.blocks[i].fixups.add lab1
return return
globalError(c.config, n.info, "VM problem: cannot find 'break' target") globalError(c.config, n.info, "VM problem: cannot find 'break' target")
else: else:
c.prc.blocks[c.prc.blocks.high].fixups.add L1 c.prc.blocks[c.prc.blocks.high].fixups.add lab1
proc genIf(c: PCtx, n: PNode; dest: var TDest) = proc genIf(c: PCtx, n: PNode; dest: var TDest) =
# if (!expr1) goto L1; # if (!expr1) goto lab1;
# thenPart # thenPart
# goto LEnd # goto LEnd
# L1: # lab1:
# if (!expr2) goto L2; # if (!expr2) goto lab2;
# thenPart2 # thenPart2
# goto LEnd # goto LEnd
# L2: # lab2:
# elsePart # elsePart
# Lend: # Lend:
if dest < 0 and not isEmptyType(n.typ): dest = getTemp(c, n.typ) if dest < 0 and not isEmptyType(n.typ): dest = getTemp(c, n.typ)
@ -393,18 +393,18 @@ proc isTemp(c: PCtx; dest: TDest): bool =
proc genAndOr(c: PCtx; n: PNode; opc: TOpcode; dest: var TDest) = proc genAndOr(c: PCtx; n: PNode; opc: TOpcode; dest: var TDest) =
# asgn dest, a # asgn dest, a
# tjmp|fjmp L1 # tjmp|fjmp lab1
# asgn dest, b # asgn dest, b
# L1: # lab1:
let copyBack = dest < 0 or not isTemp(c, dest) let copyBack = dest < 0 or not isTemp(c, dest)
let tmp = if copyBack: let tmp = if copyBack:
getTemp(c, n.typ) getTemp(c, n.typ)
else: else:
TRegister dest TRegister dest
c.gen(n.sons[1], tmp) c.gen(n.sons[1], tmp)
let L1 = c.xjmp(n, opc, tmp) let lab1 = c.xjmp(n, opc, tmp)
c.gen(n.sons[2], tmp) c.gen(n.sons[2], tmp)
c.patch(L1) c.patch(lab1)
if dest < 0: if dest < 0:
dest = tmp dest = tmp
elif copyBack: elif copyBack:
@ -452,14 +452,14 @@ proc unused(c: PCtx; n: PNode; x: TDest) {.inline.} =
globalError(c.config, n.info, "not unused") globalError(c.config, n.info, "not unused")
proc genCase(c: PCtx; n: PNode; dest: var TDest) = proc genCase(c: PCtx; n: PNode; dest: var TDest) =
# if (!expr1) goto L1; # if (!expr1) goto lab1;
# thenPart # thenPart
# goto LEnd # goto LEnd
# L1: # lab1:
# if (!expr2) goto L2; # if (!expr2) goto lab2;
# thenPart2 # thenPart2
# goto LEnd # goto LEnd
# L2: # lab2:
# elsePart # elsePart
# Lend: # Lend:
if not isEmptyType(n.typ): if not isEmptyType(n.typ):
@ -820,25 +820,25 @@ proc genCastIntFloat(c: PCtx; n: PNode; dest: var TDest) =
var unsignedIntegers = {tyUInt..tyUInt64, tyChar} var unsignedIntegers = {tyUInt..tyUInt64, tyChar}
let src = n.sons[1].typ.skipTypes(abstractRange)#.kind let src = n.sons[1].typ.skipTypes(abstractRange)#.kind
let dst = n.sons[0].typ.skipTypes(abstractRange)#.kind let dst = n.sons[0].typ.skipTypes(abstractRange)#.kind
let src_size = getSize(c.config, src) let srcSize = getSize(c.config, src)
let dst_size = getSize(c.config, dst) let dstSize = getSize(c.config, dst)
if src.kind in allowedIntegers and dst.kind in allowedIntegers: if src.kind in allowedIntegers and dst.kind in allowedIntegers:
let tmp = c.genx(n.sons[1]) let tmp = c.genx(n.sons[1])
if dest < 0: dest = c.getTemp(n[0].typ) if dest < 0: dest = c.getTemp(n[0].typ)
c.gABC(n, opcAsgnInt, dest, tmp) c.gABC(n, opcAsgnInt, dest, tmp)
if dst_size != sizeof(BiggestInt): # don't do anything on biggest int types if dstSize != sizeof(BiggestInt): # don't do anything on biggest int types
if dst.kind in signedIntegers: # we need to do sign extensions if dst.kind in signedIntegers: # we need to do sign extensions
if dst_size <= src_size: if dstSize <= srcSize:
# Sign extension can be omitted when the size increases. # Sign extension can be omitted when the size increases.
c.gABC(n, opcSignExtend, dest, TRegister(dst_size*8)) c.gABC(n, opcSignExtend, dest, TRegister(dstSize*8))
elif dst.kind in unsignedIntegers: elif dst.kind in unsignedIntegers:
if src.kind in signedIntegers or dst_size < src_size: if src.kind in signedIntegers or dstSize < srcSize:
# Cast from signed to unsigned always needs narrowing. Cast # Cast from signed to unsigned always needs narrowing. Cast
# from unsigned to unsigned only needs narrowing when target # from unsigned to unsigned only needs narrowing when target
# is smaller than source. # is smaller than source.
c.gABC(n, opcNarrowU, dest, TRegister(dst_size*8)) c.gABC(n, opcNarrowU, dest, TRegister(dstSize*8))
c.freeTemp(tmp) c.freeTemp(tmp)
elif src_size == dst_size and src.kind in allowedIntegers and elif srcSize == dstSize and src.kind in allowedIntegers and
dst.kind in {tyFloat, tyFloat32, tyFloat64}: dst.kind in {tyFloat, tyFloat32, tyFloat64}:
let tmp = c.genx(n[1]) let tmp = c.genx(n[1])
if dest < 0: dest = c.getTemp(n[0].typ) if dest < 0: dest = c.getTemp(n[0].typ)
@ -848,7 +848,7 @@ proc genCastIntFloat(c: PCtx; n: PNode; dest: var TDest) =
c.gABC(n, opcAsgnFloat64FromInt, dest, tmp) c.gABC(n, opcAsgnFloat64FromInt, dest, tmp)
c.freeTemp(tmp) c.freeTemp(tmp)
elif src_size == dst_size and src.kind in {tyFloat, tyFloat32, tyFloat64} and elif srcSize == dstSize and src.kind in {tyFloat, tyFloat32, tyFloat64} and
dst.kind in allowedIntegers: dst.kind in allowedIntegers:
let tmp = c.genx(n[1]) let tmp = c.genx(n[1])
if dest < 0: dest = c.getTemp(n[0].typ) if dest < 0: dest = c.getTemp(n[0].typ)
@ -1682,11 +1682,11 @@ proc genCheckedObjAccessAux(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags
c.gABC(n, opcContainsSet, rs, setLit, discVal) c.gABC(n, opcContainsSet, rs, setLit, discVal)
c.freeTemp(setLit) c.freeTemp(setLit)
# If the check fails let the user know # If the check fails let the user know
let L1 = c.xjmp(n, if negCheck: opcFJmp else: opcTJmp, rs) let lab1 = c.xjmp(n, if negCheck: opcFJmp else: opcTJmp, rs)
c.freeTemp(rs) c.freeTemp(rs)
# Not ideal but will do for the moment # Not ideal but will do for the moment
c.gABC(n, opcQuit) c.gABC(n, opcQuit)
c.patch(L1) c.patch(lab1)
proc genCheckedObjAccess(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) = proc genCheckedObjAccess(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) =
var objR: TDest = -1 var objR: TDest = -1

View file

@ -591,33 +591,33 @@ proc readIndexDir(dir: string):
var var
fileEntries: seq[IndexEntry] fileEntries: seq[IndexEntry]
title: IndexEntry title: IndexEntry
F = 0 f = 0
newSeq(fileEntries, 500) newSeq(fileEntries, 500)
setLen(fileEntries, 0) setLen(fileEntries, 0)
for line in lines(path): for line in lines(path):
let s = line.find('\t') let s = line.find('\t')
if s < 0: continue if s < 0: continue
setLen(fileEntries, F+1) setLen(fileEntries, f+1)
fileEntries[F].keyword = line.substr(0, s-1) fileEntries[f].keyword = line.substr(0, s-1)
fileEntries[F].link = line.substr(s+1) fileEntries[f].link = line.substr(s+1)
# See if we detect a title, a link without a `#foobar` trailing part. # See if we detect a title, a link without a `#foobar` trailing part.
if title.keyword.len == 0 and fileEntries[F].link.isDocumentationTitle: if title.keyword.len == 0 and fileEntries[f].link.isDocumentationTitle:
title.keyword = fileEntries[F].keyword title.keyword = fileEntries[f].keyword
title.link = fileEntries[F].link title.link = fileEntries[f].link
if fileEntries[F].link.find('\t') > 0: if fileEntries[f].link.find('\t') > 0:
let extraCols = fileEntries[F].link.split('\t') let extraCols = fileEntries[f].link.split('\t')
fileEntries[F].link = extraCols[0] fileEntries[f].link = extraCols[0]
assert extraCols.len == 3 assert extraCols.len == 3
fileEntries[F].linkTitle = extraCols[1].unquoteIndexColumn fileEntries[f].linkTitle = extraCols[1].unquoteIndexColumn
fileEntries[F].linkDesc = extraCols[2].unquoteIndexColumn fileEntries[f].linkDesc = extraCols[2].unquoteIndexColumn
else: else:
fileEntries[F].linkTitle = "" fileEntries[f].linkTitle = ""
fileEntries[F].linkDesc = "" fileEntries[f].linkDesc = ""
inc F inc f
# Depending on type add this to the list of symbols or table of APIs. # Depending on type add this to the list of symbols or table of APIs.
if title.keyword.len == 0: if title.keyword.len == 0:
for i in 0 ..< F: for i in 0 ..< f:
# Don't add to symbols TOC entries (they start with a whitespace). # Don't add to symbols TOC entries (they start with a whitespace).
let toc = fileEntries[i].linkTitle let toc = fileEntries[i].linkTitle
if toc.len > 0 and toc[0] == ' ': if toc.len > 0 and toc[0] == ' ':

View file

@ -241,8 +241,14 @@ proc tcFlow*(fd: cint; action: cint): cint {.importc: "tcflow",
# Window size ioctl. Should work on on any Unix that xterm has been ported to. # Window size ioctl. Should work on on any Unix that xterm has been ported to.
var TIOCGWINSZ*{.importc, header: "<sys/ioctl.h>".}: culong var TIOCGWINSZ*{.importc, header: "<sys/ioctl.h>".}: culong
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
type IOctl_WinSize* = object type IOctl_WinSize* = object
ws_row*, ws_col*, ws_xpixel*, ws_ypixel*: cushort ws_row*, ws_col*, ws_xpixel*, ws_ypixel*: cushort
when defined(nimHasStyleChecks):
{.pop.}
proc ioctl*(fd: cint, request: culong, reply: ptr IOctl_WinSize): int {. proc ioctl*(fd: cint, request: culong, reply: ptr IOctl_WinSize): int {.
importc: "ioctl", header: "<stdio.h>", varargs.} importc: "ioctl", header: "<stdio.h>", varargs.}

View file

@ -267,8 +267,8 @@ proc unregister*[T](s: Selector[T], ev: SelectEvent) =
proc registerTimer*[T](s: Selector[T], timeout: int, oneshot: bool, proc registerTimer*[T](s: Selector[T], timeout: int, oneshot: bool,
data: T): int {.discardable.} = data: T): int {.discardable.} =
var var
new_ts: Itimerspec newTs: Itimerspec
old_ts: Itimerspec oldTs: Itimerspec
let fdi = timerfd_create(CLOCK_MONOTONIC, 0).int let fdi = timerfd_create(CLOCK_MONOTONIC, 0).int
if fdi == -1: if fdi == -1:
raiseIOSelectorsError(osLastError()) raiseIOSelectorsError(osLastError())
@ -282,19 +282,19 @@ proc registerTimer*[T](s: Selector[T], timeout: int, oneshot: bool,
epv.data.u64 = fdi.uint epv.data.u64 = fdi.uint
if oneshot: if oneshot:
new_ts.it_interval.tv_sec = posix.Time(0) newTs.it_interval.tv_sec = posix.Time(0)
new_ts.it_interval.tv_nsec = 0 newTs.it_interval.tv_nsec = 0
new_ts.it_value.tv_sec = posix.Time(timeout div 1_000) newTs.it_value.tv_sec = posix.Time(timeout div 1_000)
new_ts.it_value.tv_nsec = (timeout %% 1_000) * 1_000_000 newTs.it_value.tv_nsec = (timeout %% 1_000) * 1_000_000
incl(events, Event.Oneshot) incl(events, Event.Oneshot)
epv.events = epv.events or EPOLLONESHOT epv.events = epv.events or EPOLLONESHOT
else: else:
new_ts.it_interval.tv_sec = posix.Time(timeout div 1000) newTs.it_interval.tv_sec = posix.Time(timeout div 1000)
new_ts.it_interval.tv_nsec = (timeout %% 1_000) * 1_000_000 newTs.it_interval.tv_nsec = (timeout %% 1_000) * 1_000_000
new_ts.it_value.tv_sec = new_ts.it_interval.tv_sec newTs.it_value.tv_sec = newTs.it_interval.tv_sec
new_ts.it_value.tv_nsec = new_ts.it_interval.tv_nsec newTs.it_value.tv_nsec = newTs.it_interval.tv_nsec
if timerfd_settime(fdi.cint, cint(0), new_ts, old_ts) != 0: if timerfd_settime(fdi.cint, cint(0), newTs, oldTs) != 0:
raiseIOSelectorsError(osLastError()) raiseIOSelectorsError(osLastError())
if epoll_ctl(s.epollFD, EPOLL_CTL_ADD, fdi.cint, addr epv) != 0: if epoll_ctl(s.epollFD, EPOLL_CTL_ADD, fdi.cint, addr epv) != 0:
raiseIOSelectorsError(osLastError()) raiseIOSelectorsError(osLastError())

View file

@ -253,8 +253,8 @@ proc getAddrInfo*(address: string, port: Port, domain: Domain = AF_INET,
when not defined(freebsd) and not defined(openbsd) and not defined(netbsd) and not defined(android) and not defined(haiku): when not defined(freebsd) and not defined(openbsd) and not defined(netbsd) and not defined(android) and not defined(haiku):
if domain == AF_INET6: if domain == AF_INET6:
hints.ai_flags = AI_V4MAPPED hints.ai_flags = AI_V4MAPPED
let socket_port = if sockType == SOCK_RAW: "" else: $port let socketPort = if sockType == SOCK_RAW: "" else: $port
var gaiResult = getaddrinfo(address, socket_port, addr(hints), result) var gaiResult = getaddrinfo(address, socketPort, addr(hints), result)
if gaiResult != 0'i32: if gaiResult != 0'i32:
when useWinVersion: when useWinVersion:
raiseOSError(osLastError()) raiseOSError(osLastError())
@ -357,8 +357,8 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} =
result.addrList = @[] result.addrList = @[]
var i = 0 var i = 0
while not isNil(s.h_addr_list[i]): while not isNil(s.h_addr_list[i]):
var inaddr_ptr = cast[ptr InAddr](s.h_addr_list[i]) var inaddrPtr = cast[ptr InAddr](s.h_addr_list[i])
result.addrList.add($inet_ntoa(inaddr_ptr[])) result.addrList.add($inet_ntoa(inaddrPtr[]))
inc(i) inc(i)
else: else:
result.addrList = cstringArrayToSeq(s.h_addr_list) result.addrList = cstringArrayToSeq(s.h_addr_list)
@ -386,8 +386,8 @@ proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} =
result.addrList = @[] result.addrList = @[]
var i = 0 var i = 0
while not isNil(s.h_addr_list[i]): while not isNil(s.h_addr_list[i]):
var inaddr_ptr = cast[ptr InAddr](s.h_addr_list[i]) var inaddrPtr = cast[ptr InAddr](s.h_addr_list[i])
result.addrList.add($inet_ntoa(inaddr_ptr[])) result.addrList.add($inet_ntoa(inaddrPtr[]))
inc(i) inc(i)
else: else:
result.addrList = cstringArrayToSeq(s.h_addr_list) result.addrList = cstringArrayToSeq(s.h_addr_list)

View file

@ -148,6 +148,9 @@ type
Peek, Peek,
SafeDisconn ## Ensures disconnection exceptions (ECONNRESET, EPIPE etc) are not thrown. SafeDisconn ## Ensures disconnection exceptions (ECONNRESET, EPIPE etc) are not thrown.
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
type type
IpAddressFamily* {.pure.} = enum ## Describes the type of an IP address IpAddressFamily* {.pure.} = enum ## Describes the type of an IP address
IPv6, ## IPv6 address IPv6, ## IPv6 address
@ -161,6 +164,8 @@ type
of IpAddressFamily.IPv4: of IpAddressFamily.IPv4:
address_v4*: array[0..3, uint8] ## Contains the IP address in bytes in address_v4*: array[0..3, uint8] ## Contains the IP address in bytes in
## case of IPv4 ## case of IPv4
when defined(nimHasStyleChecks):
{.pop.}
proc socketError*(socket: Socket, err: int = -1, async = false, proc socketError*(socket: Socket, err: int = -1, async = false,
lastError = (-1).OSErrorCode): void {.gcsafe.} lastError = (-1).OSErrorCode): void {.gcsafe.}

View file

@ -71,14 +71,14 @@ when defined(windows):
type type
SHORT = int16 SHORT = int16
COORD = object COORD = object
X: SHORT x: SHORT
Y: SHORT y: SHORT
SMALL_RECT = object SMALL_RECT = object
Left: SHORT left: SHORT
Top: SHORT top: SHORT
Right: SHORT right: SHORT
Bottom: SHORT bottom: SHORT
CONSOLE_SCREEN_BUFFER_INFO = object CONSOLE_SCREEN_BUFFER_INFO = object
dwSize: COORD dwSize: COORD
@ -114,14 +114,14 @@ when defined(windows):
var csbi: CONSOLE_SCREEN_BUFFER_INFO var csbi: CONSOLE_SCREEN_BUFFER_INFO
for h in handles: for h in handles:
if getConsoleScreenBufferInfo(h, addr csbi) != 0: if getConsoleScreenBufferInfo(h, addr csbi) != 0:
return int(csbi.srWindow.Right - csbi.srWindow.Left + 1) return int(csbi.srWindow.right - csbi.srWindow.left + 1)
return 0 return 0
proc terminalHeightIoctl*(handles: openArray[Handle]): int = proc terminalHeightIoctl*(handles: openArray[Handle]): int =
var csbi: CONSOLE_SCREEN_BUFFER_INFO var csbi: CONSOLE_SCREEN_BUFFER_INFO
for h in handles: for h in handles:
if getConsoleScreenBufferInfo(h, addr csbi) != 0: if getConsoleScreenBufferInfo(h, addr csbi) != 0:
return int(csbi.srWindow.Bottom - csbi.srWindow.Top + 1) return int(csbi.srWindow.bottom - csbi.srWindow.top + 1)
return 0 return 0
proc terminalWidth*(): int = proc terminalWidth*(): int =
@ -168,12 +168,12 @@ when defined(windows):
var c: CONSOLE_SCREEN_BUFFER_INFO 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))
proc setCursorPos(h: Handle, x, y: int) = proc setCursorPos(h: Handle, x, y: int) =
var c: COORD var c: COORD
c.X = int16(x) c.x = int16(x)
c.Y = int16(y) c.y = int16(y)
if setConsoleCursorPosition(h, c) == 0: if setConsoleCursorPosition(h, c) == 0:
raiseOSError(osLastError()) raiseOSError(osLastError())
@ -319,7 +319,7 @@ proc setCursorXPos*(f: File, x: int) =
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0: if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError()) raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition var origin = scrbuf.dwCursorPosition
origin.X = int16(x) origin.x = int16(x)
if setConsoleCursorPosition(h, origin) == 0: if setConsoleCursorPosition(h, origin) == 0:
raiseOSError(osLastError()) raiseOSError(osLastError())
else: else:
@ -336,7 +336,7 @@ when defined(windows):
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0: if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError()) raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition var origin = scrbuf.dwCursorPosition
origin.Y = int16(y) origin.y = int16(y)
if setConsoleCursorPosition(h, origin) == 0: if setConsoleCursorPosition(h, origin) == 0:
raiseOSError(osLastError()) raiseOSError(osLastError())
else: else:
@ -422,10 +422,10 @@ proc eraseLine*(f: File) =
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0: if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError()) raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition var origin = scrbuf.dwCursorPosition
origin.X = 0'i16 origin.x = 0'i16
if setConsoleCursorPosition(h, origin) == 0: if setConsoleCursorPosition(h, origin) == 0:
raiseOSError(osLastError()) raiseOSError(osLastError())
var wt: DWORD = scrbuf.dwSize.X - origin.X var wt: DWORD = scrbuf.dwSize.x - origin.x
if fillConsoleOutputCharacter(h, ' ', wt, if fillConsoleOutputCharacter(h, ' ', wt,
origin, addr(numwrote)) == 0: origin, addr(numwrote)) == 0:
raiseOSError(osLastError()) raiseOSError(osLastError())
@ -446,7 +446,7 @@ proc eraseScreen*(f: File) =
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0: if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError()) raiseOSError(osLastError())
let numChars = int32(scrbuf.dwSize.X)*int32(scrbuf.dwSize.Y) let numChars = int32(scrbuf.dwSize.x)*int32(scrbuf.dwSize.y)
if fillConsoleOutputCharacter(h, ' ', numChars, if fillConsoleOutputCharacter(h, ' ', numChars,
origin, addr(numwrote)) == 0: origin, addr(numwrote)) == 0:

View file

@ -283,12 +283,20 @@ type
dSat = "Saturday" dSat = "Saturday"
dSun = "Sunday" dSun = "Sunday"
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
type
DateTimeLocale* = object DateTimeLocale* = object
MMM*: array[mJan..mDec, string] MMM*: array[mJan..mDec, string]
MMMM*: array[mJan..mDec, string] MMMM*: array[mJan..mDec, string]
ddd*: array[dMon..dSun, string] ddd*: array[dMon..dSun, string]
dddd*: array[dMon..dSun, string] dddd*: array[dMon..dSun, string]
when defined(nimHasStyleChecks):
{.pop.}
type
MonthdayRange* = range[1..31] MonthdayRange* = range[1..31]
HourRange* = range[0..23] HourRange* = range[0..23]
MinuteRange* = range[0..59] MinuteRange* = range[0..59]

View file

@ -65,85 +65,85 @@ template ror2 (val: uint32): uint32 = (val shr 2) or (val shl 30)
template ror31(val: uint32): uint32 = (val shr 31) or (val shl 1) template ror31(val: uint32): uint32 = (val shr 31) or (val shl 1)
proc transform(ctx: var Sha1State) = proc transform(ctx: var Sha1State) =
var W: array[80, uint32] var w: array[80, uint32]
var A, B, C, D, E: uint32 var a, b, c, d, e: uint32
var t = 0 var t = 0
A = ctx.state[0] a = ctx.state[0]
B = ctx.state[1] b = ctx.state[1]
C = ctx.state[2] c = ctx.state[2]
D = ctx.state[3] d = ctx.state[3]
E = ctx.state[4] e = ctx.state[4]
template SHA_F1(A, B, C, D, E, t: untyped) = template shaF1(a, b, c, d, e, t: untyped) =
bigEndian32(addr W[t], addr ctx.buf[t * 4]) bigEndian32(addr w[t], addr ctx.buf[t * 4])
E += ror27(A) + W[t] + (D xor (B and (C xor D))) + 0x5A827999'u32 e += ror27(a) + w[t] + (d xor (b and (c xor d))) + 0x5A827999'u32
B = ror2(B) b = ror2(b)
while t < 15: while t < 15:
SHA_F1(A, B, C, D, E, t + 0) shaF1(a, b, c, d, e, t + 0)
SHA_F1(E, A, B, C, D, t + 1) shaF1(e, a, b, c, d, t + 1)
SHA_F1(D, E, A, B, C, t + 2) shaF1(d, e, a, b, c, t + 2)
SHA_F1(C, D, E, A, B, t + 3) shaF1(c, d, e, a, b, t + 3)
SHA_F1(B, C, D, E, A, t + 4) shaF1(b, c, d, e, a, t + 4)
t += 5 t += 5
SHA_F1(A, B, C, D, E, t + 0) # 16th one, t == 15 shaF1(a, b, c, d, e, t + 0) # 16th one, t == 15
template SHA_F11(A, B, C, D, E, t: untyped) = template shaF11(a, b, c, d, e, t: untyped) =
W[t] = ror31(W[t-3] xor W[t-8] xor W[t-14] xor W[t-16]) w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16])
E += ror27(A) + W[t] + (D xor (B and (C xor D))) + 0x5A827999'u32 e += ror27(a) + w[t] + (d xor (b and (c xor d))) + 0x5A827999'u32
B = ror2(B) b = ror2(b)
SHA_F11(E, A, B, C, D, t + 1) shaF11(e, a, b, c, d, t + 1)
SHA_F11(D, E, A, B, C, t + 2) shaF11(d, e, a, b, c, t + 2)
SHA_F11(C, D, E, A, B, t + 3) shaF11(c, d, e, a, b, t + 3)
SHA_F11(B, C, D, E, A, t + 4) shaF11(b, c, d, e, a, t + 4)
template SHA_F2(A, B, C, D, E, t: untyped) = template shaF2(a, b, c, d, e, t: untyped) =
W[t] = ror31(W[t-3] xor W[t-8] xor W[t-14] xor W[t-16]) w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16])
E += ror27(A) + W[t] + (B xor C xor D) + 0x6ED9EBA1'u32 e += ror27(a) + w[t] + (b xor c xor d) + 0x6ED9EBA1'u32
B = ror2(B) b = ror2(b)
t = 20 t = 20
while t < 40: while t < 40:
SHA_F2(A, B, C, D, E, t + 0) shaF2(a, b, c, d, e, t + 0)
SHA_F2(E, A, B, C, D, t + 1) shaF2(e, a, b, c, d, t + 1)
SHA_F2(D, E, A, B, C, t + 2) shaF2(d, e, a, b, c, t + 2)
SHA_F2(C, D, E, A, B, t + 3) shaF2(c, d, e, a, b, t + 3)
SHA_F2(B, C, D, E, A, t + 4) shaF2(b, c, d, e, a, t + 4)
t += 5 t += 5
template SHA_F3(A, B, C, D, E, t: untyped) = template shaF3(a, b, c, d, e, t: untyped) =
W[t] = ror31(W[t-3] xor W[t-8] xor W[t-14] xor W[t-16]) w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16])
E += ror27(A) + W[t] + ((B and C) or (D and (B or C))) + 0x8F1BBCDC'u32 e += ror27(a) + w[t] + ((b and c) or (d and (b or c))) + 0x8F1BBCDC'u32
B = ror2(B) b = ror2(b)
while t < 60: while t < 60:
SHA_F3(A, B, C, D, E, t + 0) shaF3(a, b, c, d, e, t + 0)
SHA_F3(E, A, B, C, D, t + 1) shaF3(e, a, b, c, d, t + 1)
SHA_F3(D, E, A, B, C, t + 2) shaF3(d, e, a, b, c, t + 2)
SHA_F3(C, D, E, A, B, t + 3) shaF3(c, d, e, a, b, t + 3)
SHA_F3(B, C, D, E, A, t + 4) shaF3(b, c, d, e, a, t + 4)
t += 5 t += 5
template SHA_F4(A, B, C, D, E, t: untyped) = template shaF4(a, b, c, d, e, t: untyped) =
W[t] = ror31(W[t-3] xor W[t-8] xor W[t-14] xor W[t-16]) w[t] = ror31(w[t-3] xor w[t-8] xor w[t-14] xor w[t-16])
E += ror27(A) + W[t] + (B xor C xor D) + 0xCA62C1D6'u32 e += ror27(a) + w[t] + (b xor c xor d) + 0xCA62C1D6'u32
B = ror2(B) b = ror2(b)
while t < 80: while t < 80:
SHA_F4(A, B, C, D, E, t + 0) shaF4(a, b, c, d, e, t + 0)
SHA_F4(E, A, B, C, D, t + 1) shaF4(e, a, b, c, d, t + 1)
SHA_F4(D, E, A, B, C, t + 2) shaF4(d, e, a, b, c, t + 2)
SHA_F4(C, D, E, A, B, t + 3) shaF4(c, d, e, a, b, t + 3)
SHA_F4(B, C, D, E, A, t + 4) shaF4(b, c, d, e, a, t + 4)
t += 5 t += 5
ctx.state[0] += A ctx.state[0] += a
ctx.state[1] += B ctx.state[1] += b
ctx.state[2] += C ctx.state[2] += c
ctx.state[3] += D ctx.state[3] += d
ctx.state[4] += E ctx.state[4] += e
proc update*(ctx: var Sha1State, data: openArray[char]) = proc update*(ctx: var Sha1State, data: openArray[char]) =
var i = ctx.count mod 64 var i = ctx.count mod 64
@ -178,7 +178,7 @@ proc update*(ctx: var Sha1State, data: openArray[char]) =
proc finalize*(ctx: var Sha1State): Sha1Digest = proc finalize*(ctx: var Sha1State): Sha1Digest =
var cnt = uint64(ctx.count * 8) var cnt = uint64(ctx.count * 8)
# A 1 bit # a 1 bit
update(ctx, "\x80") update(ctx, "\x80")
# Add padding until we reach a complexive size of 64 - 8 bytes # Add padding until we reach a complexive size of 64 - 8 bytes
while (ctx.count mod 64) != (64 - 8): while (ctx.count mod 64) != (64 - 8):