mirror of
https://github.com/nim-lang/Nim.git
synced 2026-09-01 11:23:40 +00:00
Compare commits
259 Commits
v2.2.2
...
pr_table_s
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86688cbcb0 | ||
|
|
c08f9311bf | ||
|
|
1f8da3835f | ||
|
|
1af88a2d20 | ||
|
|
91e8e605d0 | ||
|
|
f0b5bf359e | ||
|
|
1f07fdd2dc | ||
|
|
ebeef1067f | ||
|
|
510ac84518 | ||
|
|
b7d8896d00 | ||
|
|
a5cc33c1d3 | ||
|
|
b211ada273 | ||
|
|
1a7bc6d878 | ||
|
|
e6f6c369ff | ||
|
|
485b414fce | ||
|
|
7695d51fc4 | ||
|
|
e2bed72b72 | ||
|
|
0861dabfa7 | ||
|
|
647c6687f1 | ||
|
|
af5fd3fea3 | ||
|
|
cab3342a2d | ||
|
|
8c3e62e6de | ||
|
|
95b1dda1db | ||
|
|
1f9cac1f5c | ||
|
|
67f9bc2f4b | ||
|
|
d6d28a9c79 | ||
|
|
6d59680217 | ||
|
|
2f402fcb82 | ||
|
|
793baf34ff | ||
|
|
6481482e0e | ||
|
|
2af9ddc286 | ||
|
|
70d057fcc6 | ||
|
|
8d0e853e0a | ||
|
|
d83ff81695 | ||
|
|
41c447b5f4 | ||
|
|
26ed469996 | ||
|
|
4aff12408c | ||
|
|
8ed0a63973 | ||
|
|
aeeccee50a | ||
|
|
e8bf6af0da | ||
|
|
78835562b1 | ||
|
|
3dda60a8ce | ||
|
|
dcc4e07e54 | ||
|
|
0df351bf50 | ||
|
|
d3b6dba616 | ||
|
|
e1be29942e | ||
|
|
cd220fe3e1 | ||
|
|
86d6f71f5a | ||
|
|
5b9ff963c5 | ||
|
|
65b26401bc | ||
|
|
2f127bf99f | ||
|
|
3c4246dd24 | ||
|
|
fc806710cb | ||
|
|
e2a306355c | ||
|
|
5c71fbab30 | ||
|
|
6bc52737b3 | ||
|
|
f29234b40f | ||
|
|
63c884038d | ||
|
|
986ca7dcd4 | ||
|
|
50ed43df42 | ||
|
|
ce4304ce97 | ||
|
|
f80ce139d5 | ||
|
|
d5c7abe3d2 | ||
|
|
8ce58fab26 | ||
|
|
70b3232d3a | ||
|
|
81d8c0fc17 | ||
|
|
91d1933ea2 | ||
|
|
b9c593404c | ||
|
|
556f217b4c | ||
|
|
d31cce557b | ||
|
|
be4d19e562 | ||
|
|
e0197a8380 | ||
|
|
d2d810585c | ||
|
|
80af252025 | ||
|
|
f485973459 | ||
|
|
f7a461a30c | ||
|
|
f796c01e3c | ||
|
|
9bb7e53e7f | ||
|
|
da9f7f671b | ||
|
|
69e0cdb6c0 | ||
|
|
b529f69518 | ||
|
|
aeb3fe9505 | ||
|
|
d408b94063 | ||
|
|
801733f286 | ||
|
|
6f4106bf5d | ||
|
|
c0861142f8 | ||
|
|
d0288d3b57 | ||
|
|
02fb0476ce | ||
|
|
2e9e7f13ee | ||
|
|
bbf6a62c90 | ||
|
|
6bbf9c3117 | ||
|
|
8f4bfda5f4 | ||
|
|
c3120b6121 | ||
|
|
2529f33760 | ||
|
|
464dc99376 | ||
|
|
3bee04d9f3 | ||
|
|
33dc2367e7 | ||
|
|
ddf5a9f6c5 | ||
|
|
05bba15623 | ||
|
|
5340005869 | ||
|
|
8881017c80 | ||
|
|
dcd0793f2b | ||
|
|
e479151473 | ||
|
|
e7f48cdd5c | ||
|
|
1a901bd94e | ||
|
|
4aaabbb5b8 | ||
|
|
6112c51e78 | ||
|
|
2df633180a | ||
|
|
555191a3f0 | ||
|
|
96043bdbb7 | ||
|
|
af3181e75b | ||
|
|
652edb229a | ||
|
|
08c2a1741d | ||
|
|
33e455c986 | ||
|
|
9fcc3b0599 | ||
|
|
a788bae318 | ||
|
|
3eddb64909 | ||
|
|
b7b1003e6a | ||
|
|
e28d2f42e9 | ||
|
|
a610f23060 | ||
|
|
d8391a5c49 | ||
|
|
a2031ec6cf | ||
|
|
712f5be7eb | ||
|
|
f053767132 | ||
|
|
05c74d6844 | ||
|
|
75b512bc6a | ||
|
|
e239968b80 | ||
|
|
cd9ce377f8 | ||
|
|
371f50f66d | ||
|
|
cc696f18c0 | ||
|
|
726195d784 | ||
|
|
21420d8b09 | ||
|
|
1863f6447f | ||
|
|
ccb72c784d | ||
|
|
511ab72342 | ||
|
|
45e21ce8f1 | ||
|
|
76c5f16ac5 | ||
|
|
9d61f2cdd1 | ||
|
|
1fddb61b3b | ||
|
|
3e47725c08 | ||
|
|
8091d76306 | ||
|
|
b3c1fbaf13 | ||
|
|
45b8434c7d | ||
|
|
67ad1ae159 | ||
|
|
cfd8f8b857 | ||
|
|
c71de10608 | ||
|
|
f4b9fcc8ac | ||
|
|
0bc3f5c74c | ||
|
|
f98964d99f | ||
|
|
f5d80ede80 | ||
|
|
5f056f87b2 | ||
|
|
46bb47a444 | ||
|
|
08b82c90f5 | ||
|
|
8b88b5fdd8 | ||
|
|
7b47987341 | ||
|
|
c8072b1eb2 | ||
|
|
0e3330ee96 | ||
|
|
d55cd40642 | ||
|
|
658c9da33e | ||
|
|
5e56f0a356 | ||
|
|
74df699ff1 | ||
|
|
1576563775 | ||
|
|
4091576ab7 | ||
|
|
d61897459d | ||
|
|
815bbf0e73 | ||
|
|
3fc87259bd | ||
|
|
15271dba2f | ||
|
|
2e9422df57 | ||
|
|
24aa92c14f | ||
|
|
031ad957ba | ||
|
|
506c8a5ce8 | ||
|
|
40fc2d0e76 | ||
|
|
efd603eb28 | ||
|
|
79ce3fe6b7 | ||
|
|
aa90d00caf | ||
|
|
2af602a5c8 | ||
|
|
d303c289fa | ||
|
|
9d08f6cee3 | ||
|
|
294b1566e7 | ||
|
|
820e2bee9c | ||
|
|
2864830941 | ||
|
|
dd3a4b2aba | ||
|
|
b534f34e95 | ||
|
|
3aaaed1acf | ||
|
|
40b37c96d2 | ||
|
|
baf3695c76 | ||
|
|
2c56872b5c | ||
|
|
ca5df9ab25 | ||
|
|
67442471ae | ||
|
|
e69eb99a15 | ||
|
|
041098e882 | ||
|
|
93c24fe1c5 | ||
|
|
ae9287c4f3 | ||
|
|
0a058a6b8f | ||
|
|
0806fb0b6f | ||
|
|
68b2e9eb6a | ||
|
|
fce86e5937 | ||
|
|
5fa96ef270 | ||
|
|
b8f6088ac0 | ||
|
|
52cf7dfde0 | ||
|
|
0347536ff2 | ||
|
|
d0b6b9346e | ||
|
|
8be82c36c9 | ||
|
|
4a056b1849 | ||
|
|
a3aea224c9 | ||
|
|
53460f312c | ||
|
|
922f7dfd71 | ||
|
|
3e8f44b232 | ||
|
|
8b39b2df7d | ||
|
|
6df050d6d2 | ||
|
|
34c87de984 | ||
|
|
d4b9c147ab | ||
|
|
07628b0dec | ||
|
|
80e6b35721 | ||
|
|
71515bf278 | ||
|
|
a0d78d259b | ||
|
|
1dbf614858 | ||
|
|
2f7586c066 | ||
|
|
720d0aee5c | ||
|
|
def1fea43a | ||
|
|
25c068c070 | ||
|
|
1bebc236bd | ||
|
|
449106a5a4 | ||
|
|
bb0006598d | ||
|
|
f5cb39289b | ||
|
|
af23bc2941 | ||
|
|
aaf6c408c6 | ||
|
|
706985997e | ||
|
|
9c85f4fd07 | ||
|
|
274762638f | ||
|
|
e9a4d096ab | ||
|
|
2f904535d0 | ||
|
|
96d6eee9bc | ||
|
|
67ea754b7f | ||
|
|
95a7695810 | ||
|
|
f73e03b132 | ||
|
|
d72b848d17 | ||
|
|
d6633ae1da | ||
|
|
4515b2dae2 | ||
|
|
30e552e3d3 | ||
|
|
c73eedfe6e | ||
|
|
911cef1621 | ||
|
|
ea9811a4d2 | ||
|
|
7f2e6a1359 | ||
|
|
a2ee709199 | ||
|
|
a65501325c | ||
|
|
cad8726907 | ||
|
|
aa605da92a | ||
|
|
09043f409f | ||
|
|
9e30b39412 | ||
|
|
4a63186cda | ||
|
|
782b75cc08 | ||
|
|
f420a5a273 | ||
|
|
7dfadb8b4e | ||
|
|
4eed341ba5 | ||
|
|
d98ef312f0 | ||
|
|
89978b48ba | ||
|
|
d6a71a1067 | ||
|
|
f7cb0322c2 |
@@ -1,121 +0,0 @@
|
||||
type
|
||||
Snippet = string
|
||||
Builder = string
|
||||
|
||||
template newBuilder(s: string): Builder =
|
||||
s
|
||||
|
||||
proc addField(obj: var Builder; name, typ: Snippet) =
|
||||
obj.add('\t')
|
||||
obj.add(typ)
|
||||
obj.add(" ")
|
||||
obj.add(name)
|
||||
obj.add(";\n")
|
||||
|
||||
proc addField(obj: var Builder; field: PSym; name, typ: Snippet; isFlexArray: bool; initializer: Snippet) =
|
||||
obj.add('\t')
|
||||
if field.alignment > 0:
|
||||
obj.add("NIM_ALIGN(")
|
||||
obj.addInt(field.alignment)
|
||||
obj.add(") ")
|
||||
obj.add(typ)
|
||||
if sfNoalias in field.flags:
|
||||
obj.add(" NIM_NOALIAS")
|
||||
obj.add(" ")
|
||||
obj.add(name)
|
||||
if isFlexArray:
|
||||
obj.add("[SEQ_DECL_SIZE]")
|
||||
if field.bitsize != 0:
|
||||
obj.add(":")
|
||||
obj.addInt(field.bitsize)
|
||||
if initializer.len != 0:
|
||||
obj.add(initializer)
|
||||
obj.add(";\n")
|
||||
|
||||
proc structOrUnion(t: PType): Snippet =
|
||||
let t = t.skipTypes({tyAlias, tySink})
|
||||
if tfUnion in t.flags: "union"
|
||||
else: "struct"
|
||||
|
||||
proc ptrType(t: Snippet): Snippet =
|
||||
t & "*"
|
||||
|
||||
template addStruct(obj: var Builder; m: BModule; typ: PType; name: string; baseType: string; body: typed) =
|
||||
if tfPacked in typ.flags:
|
||||
if hasAttribute in CC[m.config.cCompiler].props:
|
||||
obj.add(structOrUnion(typ))
|
||||
obj.add(" __attribute__((__packed__))")
|
||||
else:
|
||||
obj.add("#pragma pack(push, 1)\n")
|
||||
obj.add(structOrUnion(typ))
|
||||
else:
|
||||
obj.add(structOrUnion(typ))
|
||||
obj.add(" ")
|
||||
obj.add(name)
|
||||
type BaseClassKind = enum
|
||||
bcNone, bcCppInherit, bcSupField, bcNoneRtti, bcNoneTinyRtti
|
||||
var baseKind = bcNone
|
||||
if typ.kind == tyObject:
|
||||
if typ.baseClass == nil:
|
||||
if lacksMTypeField(typ):
|
||||
baseKind = bcNone
|
||||
elif optTinyRtti in m.config.globalOptions:
|
||||
baseKind = bcNoneTinyRtti
|
||||
else:
|
||||
baseKind = bcNoneRtti
|
||||
elif m.compileToCpp:
|
||||
baseKind = bcCppInherit
|
||||
else:
|
||||
baseKind = bcSupField
|
||||
if baseKind == bcCppInherit:
|
||||
obj.add(" : public ")
|
||||
obj.add(baseType)
|
||||
obj.add(" ")
|
||||
obj.add("{\n")
|
||||
let currLen = obj.len
|
||||
case baseKind
|
||||
of bcNone:
|
||||
# rest of the options add a field or don't need it due to inheritance,
|
||||
# we need to add the dummy field for uncheckedarray ahead of time
|
||||
# so that it remains trailing
|
||||
if typ.itemId notin m.g.graph.memberProcsPerType and
|
||||
typ.n != nil and typ.n.len == 1 and typ.n[0].kind == nkSym and
|
||||
typ.n[0].sym.typ.skipTypes(abstractInst).kind == tyUncheckedArray:
|
||||
# only consists of flexible array field, add *initial* dummy field
|
||||
obj.addField(name = "dummy", typ = "char")
|
||||
of bcCppInherit: discard
|
||||
of bcNoneRtti:
|
||||
obj.addField(name = "m_type", typ = ptrType(cgsymValue(m, "TNimType")))
|
||||
of bcNoneTinyRtti:
|
||||
obj.addField(name = "m_type", typ = ptrType(cgsymValue(m, "TNimTypeV2")))
|
||||
of bcSupField:
|
||||
obj.addField(name = "Sup", typ = baseType)
|
||||
body
|
||||
if baseKind == bcNone and currLen == obj.len and typ.itemId notin m.g.graph.memberProcsPerType:
|
||||
# no fields were added, add dummy field
|
||||
obj.addField(name = "dummy", typ = "char")
|
||||
obj.add("};\n")
|
||||
if tfPacked in typ.flags and hasAttribute notin CC[m.config.cCompiler].props:
|
||||
result.add("#pragma pack(pop)\n")
|
||||
|
||||
template addFieldWithStructType(obj: var Builder; m: BModule; parentTyp: PType; fieldName: string, body: typed) =
|
||||
## adds a field with a `struct { ... }` type, building it according to `body`
|
||||
obj.add('\t')
|
||||
if tfPacked in parentTyp.flags:
|
||||
if hasAttribute in CC[m.config.cCompiler].props:
|
||||
obj.add("struct __attribute__((__packed__)) {\n")
|
||||
else:
|
||||
obj.add("#pragma pack(push, 1)\nstruct {")
|
||||
else:
|
||||
obj.add("struct {\n")
|
||||
body
|
||||
obj.add("} ")
|
||||
obj.add(fieldName)
|
||||
obj.add(";\n")
|
||||
if tfPacked in parentTyp.flags and hasAttribute notin CC[m.config.cCompiler].props:
|
||||
result.add("#pragma pack(pop)\n")
|
||||
|
||||
template addAnonUnion(obj: var Builder; body: typed) =
|
||||
obj.add "union{\n"
|
||||
body
|
||||
obj.add("};\n")
|
||||
164
compiler/cbuilderbase.nim
Normal file
164
compiler/cbuilderbase.nim
Normal file
@@ -0,0 +1,164 @@
|
||||
import ropes, int128
|
||||
|
||||
type
|
||||
Snippet* = string
|
||||
Builder* = object
|
||||
buf*: string
|
||||
indents*: int
|
||||
|
||||
template newBuilder*(s: string): Builder =
|
||||
Builder(buf: s)
|
||||
|
||||
proc extract*(builder: Builder): Snippet =
|
||||
builder.buf
|
||||
|
||||
proc add*(builder: var Builder, s: string) =
|
||||
builder.buf.add(s)
|
||||
|
||||
proc add*(builder: var Builder, s: char) =
|
||||
builder.buf.add(s)
|
||||
|
||||
proc addNewline*(builder: var Builder) =
|
||||
builder.add('\n')
|
||||
for i in 0 ..< builder.indents:
|
||||
builder.add('\t')
|
||||
|
||||
proc addLineEnd*(builder: var Builder, s: string) =
|
||||
builder.add(s)
|
||||
builder.addNewline()
|
||||
|
||||
proc addLineEndIndent*(builder: var Builder, s: string) =
|
||||
inc builder.indents
|
||||
builder.add(s)
|
||||
builder.addNewline()
|
||||
|
||||
proc addDedent*(builder: var Builder, s: string) =
|
||||
if builder.buf.len > 0 and builder.buf[^1] == '\t':
|
||||
builder.buf.setLen(builder.buf.len - 1)
|
||||
builder.add(s)
|
||||
dec builder.indents
|
||||
|
||||
proc addLineEndDedent*(builder: var Builder, s: string) =
|
||||
builder.addDedent(s)
|
||||
builder.addNewline()
|
||||
|
||||
proc addLineComment*(builder: var Builder, comment: string) =
|
||||
# probably no-op on nifc
|
||||
builder.add("// ")
|
||||
builder.add(comment)
|
||||
builder.addNewline()
|
||||
|
||||
proc addIntValue*(builder: var Builder, val: int) =
|
||||
builder.buf.addInt(val)
|
||||
|
||||
proc addIntValue*(builder: var Builder, val: int64) =
|
||||
builder.buf.addInt(val)
|
||||
|
||||
proc addIntValue*(builder: var Builder, val: uint64) =
|
||||
builder.buf.addInt(val)
|
||||
|
||||
proc addIntValue*(builder: var Builder, val: Int128) =
|
||||
builder.buf.addInt128(val)
|
||||
|
||||
template cIntValue*(val: int): Snippet = $val
|
||||
template cIntValue*(val: int64): Snippet = $val
|
||||
template cIntValue*(val: uint64): Snippet = $val
|
||||
template cIntValue*(val: Int128): Snippet = $val
|
||||
|
||||
template cUintValue*(val: uint): Snippet = $val & "U"
|
||||
|
||||
import std/formatfloat
|
||||
|
||||
proc addFloatValue*(builder: var Builder, val: float) =
|
||||
builder.buf.addFloat(val)
|
||||
|
||||
template cFloatValue*(val: float): Snippet = $val
|
||||
|
||||
proc addInt64Literal*(result: var Builder; i: BiggestInt) =
|
||||
if i > low(int64):
|
||||
result.add "IL64($1)" % [rope(i)]
|
||||
else:
|
||||
result.add "(IL64(-9223372036854775807) - IL64(1))"
|
||||
|
||||
proc addUint64Literal*(result: var Builder; i: uint64) =
|
||||
result.add rope($i & "ULL")
|
||||
|
||||
proc addIntLiteral*(result: var Builder; i: BiggestInt) =
|
||||
if i > low(int32) and i <= high(int32):
|
||||
result.addIntValue(i)
|
||||
elif i == low(int32):
|
||||
# Nim has the same bug for the same reasons :-)
|
||||
result.add "(-2147483647 -1)"
|
||||
elif i > low(int64):
|
||||
result.add "IL64($1)" % [rope(i)]
|
||||
else:
|
||||
result.add "(IL64(-9223372036854775807) - IL64(1))"
|
||||
|
||||
proc addIntLiteral*(result: var Builder; i: Int128) =
|
||||
addIntLiteral(result, toInt64(i))
|
||||
|
||||
proc cInt64Literal*(i: BiggestInt): Snippet =
|
||||
if i > low(int64):
|
||||
result = "IL64($1)" % [rope(i)]
|
||||
else:
|
||||
result = "(IL64(-9223372036854775807) - IL64(1))"
|
||||
|
||||
proc cUint64Literal*(i: uint64): Snippet =
|
||||
result = $i & "ULL"
|
||||
|
||||
proc cIntLiteral*(i: BiggestInt): Snippet =
|
||||
if i > low(int32) and i <= high(int32):
|
||||
result = rope(i)
|
||||
elif i == low(int32):
|
||||
# Nim has the same bug for the same reasons :-)
|
||||
result = "(-2147483647 -1)"
|
||||
elif i > low(int64):
|
||||
result = "IL64($1)" % [rope(i)]
|
||||
else:
|
||||
result = "(IL64(-9223372036854775807) - IL64(1))"
|
||||
|
||||
proc cIntLiteral*(i: Int128): Snippet =
|
||||
result = cIntLiteral(toInt64(i))
|
||||
|
||||
const
|
||||
NimInt* = "NI"
|
||||
NimInt8* = "NI8"
|
||||
NimInt16* = "NI16"
|
||||
NimInt32* = "NI32"
|
||||
NimInt64* = "NI64"
|
||||
CInt* = "int"
|
||||
NimUint* = "NU"
|
||||
NimUint8* = "NU8"
|
||||
NimUint16* = "NU16"
|
||||
NimUint32* = "NU32"
|
||||
NimUint64* = "NU64"
|
||||
NimFloat* = "NF"
|
||||
NimFloat32* = "NF32"
|
||||
NimFloat64* = "NF64"
|
||||
NimFloat128* = "NF128" # not actually defined
|
||||
NimNan* = "NAN"
|
||||
NimInf* = "INF"
|
||||
NimBool* = "NIM_BOOL"
|
||||
NimTrue* = "NIM_TRUE"
|
||||
NimFalse* = "NIM_FALSE"
|
||||
NimChar* = "NIM_CHAR"
|
||||
CChar* = "char"
|
||||
NimCstring* = "NCSTRING"
|
||||
NimNil* = "NIM_NIL"
|
||||
CNil* = "NULL"
|
||||
NimStrlitFlag* = "NIM_STRLIT_FLAG"
|
||||
CVoid* = "void"
|
||||
CPointer* = "void*"
|
||||
CConstPointer* = "NIM_CONST void*"
|
||||
|
||||
proc cIntType*(bits: BiggestInt): Snippet =
|
||||
"NI" & $bits
|
||||
|
||||
proc cUintType*(bits: BiggestInt): Snippet =
|
||||
"NU" & $bits
|
||||
|
||||
type
|
||||
IfBuilderState* = enum
|
||||
WaitingIf, WaitingElseIf, InBlock
|
||||
IfBuilder* = object
|
||||
state*: IfBuilderState
|
||||
668
compiler/cbuilderdecls.nim
Normal file
668
compiler/cbuilderdecls.nim
Normal file
@@ -0,0 +1,668 @@
|
||||
type VarKind = enum
|
||||
Local
|
||||
Global
|
||||
Threadvar
|
||||
Const
|
||||
AlwaysConst ## const even on C++
|
||||
|
||||
proc addVarHeader(builder: var Builder, kind: VarKind) =
|
||||
## adds modifiers for given var kind:
|
||||
## Local has no modifier
|
||||
## Global has `static` modifier
|
||||
## Const has `static NIM_CONST` modifier
|
||||
## AlwaysConst has `static const` modifier (NIM_CONST is no-op on C++)
|
||||
## Threadvar is unimplemented
|
||||
case kind
|
||||
of Local: discard
|
||||
of Global:
|
||||
builder.add("static ")
|
||||
of Const:
|
||||
builder.add("static NIM_CONST ")
|
||||
of AlwaysConst:
|
||||
builder.add("static const ")
|
||||
of Threadvar:
|
||||
doAssert false, "unimplemented"
|
||||
|
||||
proc addVar(builder: var Builder, kind: VarKind = Local, name: string, typ: Snippet, initializer: Snippet = "") =
|
||||
## adds a variable declaration to the builder
|
||||
builder.addVarHeader(kind)
|
||||
builder.add(typ)
|
||||
builder.add(" ")
|
||||
builder.add(name)
|
||||
if initializer.len != 0:
|
||||
builder.add(" = ")
|
||||
builder.add(initializer)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
template addVarWithType(builder: var Builder, kind: VarKind = Local, name: string, body: typed) =
|
||||
## adds a variable declaration to the builder, with the `body` building the type
|
||||
builder.addVarHeader(kind)
|
||||
body
|
||||
builder.add(" ")
|
||||
builder.add(name)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
template addVarWithInitializer(builder: var Builder, kind: VarKind = Local, name: string,
|
||||
typ: Snippet, initializerBody: typed) =
|
||||
## adds a variable declaration to the builder, with
|
||||
## `initializerBody` building the initializer. initializer must be provided
|
||||
builder.addVarHeader(kind)
|
||||
builder.add(typ)
|
||||
builder.add(" ")
|
||||
builder.add(name)
|
||||
builder.add(" = ")
|
||||
initializerBody
|
||||
builder.addLineEnd(";")
|
||||
|
||||
template addVarWithTypeAndInitializer(builder: var Builder, kind: VarKind = Local, name: string,
|
||||
typeBody, initializerBody: typed) =
|
||||
## adds a variable declaration to the builder, with `typeBody` building the type, and
|
||||
## `initializerBody` building the initializer. initializer must be provided
|
||||
builder.addVarHeader(kind)
|
||||
typeBody
|
||||
builder.add(" ")
|
||||
builder.add(name)
|
||||
builder.add(" = ")
|
||||
initializerBody
|
||||
builder.addLineEnd(";")
|
||||
|
||||
proc addArrayVar(builder: var Builder, kind: VarKind = Local, name: string, elementType: Snippet, len: int, initializer: Snippet = "") =
|
||||
## adds an array variable declaration to the builder
|
||||
builder.addVarHeader(kind)
|
||||
builder.add(elementType)
|
||||
builder.add(" ")
|
||||
builder.add(name)
|
||||
builder.add("[")
|
||||
builder.addIntValue(len)
|
||||
builder.add("]")
|
||||
if initializer.len != 0:
|
||||
builder.add(" = ")
|
||||
builder.add(initializer)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
template addArrayVarWithInitializer(builder: var Builder, kind: VarKind = Local, name: string, elementType: Snippet, len: int, body: typed) =
|
||||
## adds an array variable declaration to the builder with the initializer built according to `body`
|
||||
builder.addVarHeader(kind)
|
||||
builder.add(elementType)
|
||||
builder.add(" ")
|
||||
builder.add(name)
|
||||
builder.add("[")
|
||||
builder.addIntValue(len)
|
||||
builder.add("] = ")
|
||||
body
|
||||
builder.addLineEnd(";")
|
||||
|
||||
template addTypedef(builder: var Builder, name: string, typeBody: typed) =
|
||||
## adds a typedef declaration to the builder with name `name` and type as
|
||||
## built in `typeBody`
|
||||
builder.add("typedef ")
|
||||
typeBody
|
||||
builder.add(" ")
|
||||
builder.add(name)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
proc addProcTypedef(builder: var Builder, callConv: TCallingConvention, name: string, rettype, params: Snippet) =
|
||||
builder.add("typedef ")
|
||||
builder.add(CallingConvToStr[callConv])
|
||||
builder.add("_PTR(")
|
||||
builder.add(rettype)
|
||||
builder.add(", ")
|
||||
builder.add(name)
|
||||
builder.add(")")
|
||||
builder.add(params)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
template addArrayTypedef(builder: var Builder, name: string, len: BiggestInt, typeBody: typed) =
|
||||
## adds an array typedef declaration to the builder with name `name`,
|
||||
## length `len`, and element type as built in `typeBody`
|
||||
builder.add("typedef ")
|
||||
typeBody
|
||||
builder.add(" ")
|
||||
builder.add(name)
|
||||
builder.add("[")
|
||||
builder.addIntValue(len)
|
||||
builder.addLineEnd("];")
|
||||
|
||||
type
|
||||
StructInitializerKind = enum
|
||||
siOrderedStruct ## struct constructor, but without named fields on C
|
||||
siNamedStruct ## struct constructor, with named fields i.e. C99 designated initializer
|
||||
siArray ## array constructor
|
||||
siWrapper ## wrapper for a single field, generates it verbatim
|
||||
|
||||
StructInitializer = object
|
||||
## context for building struct initializers, i.e. `{ field1, field2 }`
|
||||
kind: StructInitializerKind
|
||||
## if true, fields will not be named, instead values are placed in order
|
||||
needsComma: bool
|
||||
|
||||
proc initStructInitializer(builder: var Builder, kind: StructInitializerKind): StructInitializer =
|
||||
## starts building a struct initializer, i.e. braced initializer list
|
||||
result = StructInitializer(kind: kind, needsComma: false)
|
||||
if kind != siWrapper:
|
||||
builder.add("{")
|
||||
|
||||
template addField(builder: var Builder, constr: var StructInitializer, name: string, valueBody: typed) =
|
||||
## adds a field to a struct initializer, with the value built in `valueBody`
|
||||
if constr.needsComma:
|
||||
assert constr.kind != siWrapper, "wrapper constructor cannot have multiple fields"
|
||||
builder.add(", ")
|
||||
else:
|
||||
constr.needsComma = true
|
||||
case constr.kind
|
||||
of siArray, siWrapper:
|
||||
# no name, can just add value
|
||||
valueBody
|
||||
of siOrderedStruct:
|
||||
# no name, can just add value on C
|
||||
assert name.len != 0, "name has to be given for struct initializer field"
|
||||
valueBody
|
||||
of siNamedStruct:
|
||||
assert name.len != 0, "name has to be given for struct initializer field"
|
||||
builder.add(".")
|
||||
builder.add(name)
|
||||
builder.add(" = ")
|
||||
valueBody
|
||||
|
||||
proc finishStructInitializer(builder: var Builder, constr: StructInitializer) =
|
||||
## finishes building a struct initializer
|
||||
if constr.kind != siWrapper:
|
||||
builder.add("}")
|
||||
|
||||
template addStructInitializer(builder: var Builder, constr: out StructInitializer, kind: StructInitializerKind, body: typed) =
|
||||
## builds a struct initializer, i.e. `{ field1, field2 }`
|
||||
## a `var StructInitializer` must be declared and passed as a parameter so
|
||||
## that it can be used with `addField`
|
||||
constr = builder.initStructInitializer(kind)
|
||||
body
|
||||
builder.finishStructInitializer(constr)
|
||||
|
||||
proc addField(obj: var Builder; name, typ: Snippet; isFlexArray: bool = false; initializer: Snippet = "") =
|
||||
## adds a field inside a struct/union type
|
||||
obj.add('\t')
|
||||
obj.add(typ)
|
||||
obj.add(" ")
|
||||
obj.add(name)
|
||||
if isFlexArray:
|
||||
obj.add("[SEQ_DECL_SIZE]")
|
||||
if initializer.len != 0:
|
||||
obj.add(initializer)
|
||||
obj.add(";\n")
|
||||
|
||||
proc addArrayField(obj: var Builder; name, elementType: Snippet; len: int; initializer: Snippet = "") =
|
||||
## adds an array field inside a struct/union type
|
||||
obj.add('\t')
|
||||
obj.add(elementType)
|
||||
obj.add(" ")
|
||||
obj.add(name)
|
||||
obj.add("[")
|
||||
obj.addIntValue(len)
|
||||
obj.add("]")
|
||||
if initializer.len != 0:
|
||||
obj.add(initializer)
|
||||
obj.add(";\n")
|
||||
|
||||
proc addField(obj: var Builder; field: PSym; name, typ: Snippet; isFlexArray: bool = false; initializer: Snippet = "") =
|
||||
## adds an field inside a struct/union type, based on an `skField` symbol
|
||||
obj.add('\t')
|
||||
if field.alignment > 0:
|
||||
obj.add("NIM_ALIGN(")
|
||||
obj.addIntValue(field.alignment)
|
||||
obj.add(") ")
|
||||
obj.add(typ)
|
||||
if sfNoalias in field.flags:
|
||||
obj.add(" NIM_NOALIAS")
|
||||
obj.add(" ")
|
||||
obj.add(name)
|
||||
if isFlexArray:
|
||||
obj.add("[SEQ_DECL_SIZE]")
|
||||
if field.bitsize != 0:
|
||||
obj.add(":")
|
||||
obj.addIntValue(field.bitsize)
|
||||
if initializer.len != 0:
|
||||
obj.add(initializer)
|
||||
obj.add(";\n")
|
||||
|
||||
proc addProcField(obj: var Builder, callConv: TCallingConvention, name: string, rettype, params: Snippet) =
|
||||
obj.add(CallingConvToStr[callConv])
|
||||
obj.add("_PTR(")
|
||||
obj.add(rettype)
|
||||
obj.add(", ")
|
||||
obj.add(name)
|
||||
obj.add(")")
|
||||
obj.add(params)
|
||||
obj.add(";\n")
|
||||
|
||||
type
|
||||
BaseClassKind = enum
|
||||
## denotes how and whether or not the base class/RTTI should be stored
|
||||
bcNone, bcCppInherit, bcSupField, bcNoneRtti, bcNoneTinyRtti
|
||||
StructBuilderInfo = object
|
||||
## context for building `struct` types
|
||||
baseKind: BaseClassKind
|
||||
named: bool
|
||||
preFieldsLen: int
|
||||
|
||||
proc structOrUnion(t: PType): Snippet =
|
||||
let t = t.skipTypes({tyAlias, tySink})
|
||||
if tfUnion in t.flags: "union"
|
||||
else: "struct"
|
||||
|
||||
proc startSimpleStruct(obj: var Builder; m: BModule; name: string; baseType: Snippet): StructBuilderInfo =
|
||||
result = StructBuilderInfo(baseKind: bcNone, named: name.len != 0)
|
||||
obj.add("struct")
|
||||
if result.named:
|
||||
obj.add(" ")
|
||||
obj.add(name)
|
||||
if baseType.len != 0:
|
||||
if m.compileToCpp:
|
||||
result.baseKind = bcCppInherit
|
||||
else:
|
||||
result.baseKind = bcSupField
|
||||
if result.baseKind == bcCppInherit:
|
||||
obj.add(" : public ")
|
||||
obj.add(baseType)
|
||||
obj.add(" ")
|
||||
obj.add("{\n")
|
||||
result.preFieldsLen = obj.buf.len
|
||||
if result.baseKind == bcSupField:
|
||||
obj.addField(name = "Sup", typ = baseType)
|
||||
|
||||
proc finishSimpleStruct(obj: var Builder; m: BModule; info: StructBuilderInfo) =
|
||||
if info.baseKind == bcNone and info.preFieldsLen == obj.buf.len:
|
||||
# no fields were added, add dummy field
|
||||
obj.addField(name = "dummy", typ = CChar)
|
||||
if info.named:
|
||||
obj.add("};\n")
|
||||
else:
|
||||
obj.add("}")
|
||||
|
||||
template addSimpleStruct(obj: var Builder; m: BModule; name: string; baseType: Snippet; body: typed) =
|
||||
## builds a struct type not based on a Nim type with fields according to `body`,
|
||||
## `name` can be empty to build as a type expression and not a statement
|
||||
let info = startSimpleStruct(obj, m, name, baseType)
|
||||
body
|
||||
finishSimpleStruct(obj, m, info)
|
||||
|
||||
proc startStruct(obj: var Builder; m: BModule; t: PType; name: string; baseType: Snippet): StructBuilderInfo =
|
||||
result = StructBuilderInfo(baseKind: bcNone, named: name.len != 0)
|
||||
if tfPacked in t.flags:
|
||||
if hasAttribute in CC[m.config.cCompiler].props:
|
||||
obj.add(structOrUnion(t))
|
||||
obj.add(" __attribute__((__packed__))")
|
||||
else:
|
||||
obj.add("#pragma pack(push, 1)\n")
|
||||
obj.add(structOrUnion(t))
|
||||
else:
|
||||
obj.add(structOrUnion(t))
|
||||
if result.named:
|
||||
obj.add(" ")
|
||||
obj.add(name)
|
||||
if t.kind == tyObject:
|
||||
if t.baseClass == nil:
|
||||
if lacksMTypeField(t):
|
||||
result.baseKind = bcNone
|
||||
elif optTinyRtti in m.config.globalOptions:
|
||||
result.baseKind = bcNoneTinyRtti
|
||||
else:
|
||||
result.baseKind = bcNoneRtti
|
||||
elif m.compileToCpp:
|
||||
result.baseKind = bcCppInherit
|
||||
else:
|
||||
result.baseKind = bcSupField
|
||||
elif baseType.len != 0:
|
||||
if m.compileToCpp:
|
||||
result.baseKind = bcCppInherit
|
||||
else:
|
||||
result.baseKind = bcSupField
|
||||
if result.baseKind == bcCppInherit:
|
||||
obj.add(" : public ")
|
||||
obj.add(baseType)
|
||||
obj.add(" ")
|
||||
obj.add("{\n")
|
||||
result.preFieldsLen = obj.buf.len
|
||||
case result.baseKind
|
||||
of bcNone:
|
||||
# rest of the options add a field or don't need it due to inheritance,
|
||||
# we need to add the dummy field for uncheckedarray ahead of time
|
||||
# so that it remains trailing
|
||||
if t.itemId notin m.g.graph.memberProcsPerType and
|
||||
t.n != nil and t.n.len == 1 and t.n[0].kind == nkSym and
|
||||
t.n[0].sym.typ.skipTypes(abstractInst).kind == tyUncheckedArray:
|
||||
# only consists of flexible array field, add *initial* dummy field
|
||||
obj.addField(name = "dummy", typ = CChar)
|
||||
of bcCppInherit: discard
|
||||
of bcNoneRtti:
|
||||
obj.addField(name = "m_type", typ = ptrType(cgsymValue(m, "TNimType")))
|
||||
of bcNoneTinyRtti:
|
||||
obj.addField(name = "m_type", typ = ptrType(cgsymValue(m, "TNimTypeV2")))
|
||||
of bcSupField:
|
||||
obj.addField(name = "Sup", typ = baseType)
|
||||
|
||||
proc finishStruct(obj: var Builder; m: BModule; t: PType; info: StructBuilderInfo) =
|
||||
if info.baseKind == bcNone and info.preFieldsLen == obj.buf.len and
|
||||
t.itemId notin m.g.graph.memberProcsPerType:
|
||||
# no fields were added, add dummy field
|
||||
obj.addField(name = "dummy", typ = CChar)
|
||||
if info.named:
|
||||
obj.add("};\n")
|
||||
else:
|
||||
obj.add("}")
|
||||
if tfPacked in t.flags and hasAttribute notin CC[m.config.cCompiler].props:
|
||||
obj.add("#pragma pack(pop)\n")
|
||||
|
||||
template addStruct(obj: var Builder; m: BModule; typ: PType; name: string; baseType: Snippet; body: typed) =
|
||||
## builds a struct type directly based on `typ` with fields according to `body`,
|
||||
## `name` can be empty to build as a type expression and not a statement
|
||||
let info = startStruct(obj, m, typ, name, baseType)
|
||||
body
|
||||
finishStruct(obj, m, typ, info)
|
||||
|
||||
template addFieldWithStructType(obj: var Builder; m: BModule; parentTyp: PType; fieldName: string, body: typed) =
|
||||
## adds a field with a `struct { ... }` type, building the fields according to `body`
|
||||
obj.add('\t')
|
||||
if tfPacked in parentTyp.flags:
|
||||
if hasAttribute in CC[m.config.cCompiler].props:
|
||||
obj.add("struct __attribute__((__packed__)) {\n")
|
||||
else:
|
||||
obj.add("#pragma pack(push, 1)\nstruct {")
|
||||
else:
|
||||
obj.add("struct {\n")
|
||||
body
|
||||
obj.add("} ")
|
||||
obj.add(fieldName)
|
||||
obj.add(";\n")
|
||||
if tfPacked in parentTyp.flags and hasAttribute notin CC[m.config.cCompiler].props:
|
||||
obj.add("#pragma pack(pop)\n")
|
||||
|
||||
template addAnonUnion(obj: var Builder; body: typed) =
|
||||
## adds an anonymous union i.e. `union { ... };` with fields according to `body`
|
||||
obj.add "union{\n"
|
||||
body
|
||||
obj.add("};\n")
|
||||
|
||||
template addUnionType(obj: var Builder; body: typed) =
|
||||
## adds a union type i.e. `union { ... }` with fields according to `body`
|
||||
obj.add "union{\n"
|
||||
body
|
||||
obj.add("}")
|
||||
|
||||
type DeclVisibility = enum
|
||||
None
|
||||
Extern
|
||||
ExternC
|
||||
ImportLib
|
||||
ExportLib
|
||||
ExportLibVar
|
||||
Private
|
||||
StaticProc
|
||||
|
||||
proc addVisibilityPrefix(builder: var Builder, visibility: DeclVisibility) =
|
||||
# internal proc
|
||||
case visibility
|
||||
of None: discard
|
||||
of Extern:
|
||||
builder.add("extern ")
|
||||
of ExternC:
|
||||
builder.add("NIM_EXTERNC ")
|
||||
of ImportLib:
|
||||
builder.add("N_LIB_IMPORT ")
|
||||
of ExportLib:
|
||||
builder.add("N_LIB_EXPORT ")
|
||||
of ExportLibVar:
|
||||
builder.add("N_LIB_EXPORT_VAR ")
|
||||
of Private:
|
||||
builder.add("N_LIB_PRIVATE ")
|
||||
of StaticProc:
|
||||
builder.add("static ")
|
||||
|
||||
template addDeclWithVisibility(builder: var Builder, visibility: DeclVisibility, declBody: typed) =
|
||||
## adds a declaration as in `declBody` with the given visibility
|
||||
builder.addVisibilityPrefix(visibility)
|
||||
declBody
|
||||
|
||||
type ProcParamBuilder = object
|
||||
needsComma: bool
|
||||
|
||||
proc initProcParamBuilder(builder: var Builder): ProcParamBuilder =
|
||||
result = ProcParamBuilder(needsComma: false)
|
||||
builder.add("(")
|
||||
|
||||
proc finishProcParamBuilder(builder: var Builder, params: ProcParamBuilder) =
|
||||
if params.needsComma:
|
||||
builder.add(")")
|
||||
else:
|
||||
builder.add("void)")
|
||||
|
||||
template cgDeclFrmt*(s: PSym): string =
|
||||
s.constraint.strVal
|
||||
|
||||
proc addParam(builder: var Builder, params: var ProcParamBuilder, name: string, typ: Snippet) =
|
||||
if params.needsComma:
|
||||
builder.add(", ")
|
||||
else:
|
||||
params.needsComma = true
|
||||
builder.add(typ)
|
||||
builder.add(" ")
|
||||
builder.add(name)
|
||||
|
||||
proc addParam(builder: var Builder, params: var ProcParamBuilder, param: PSym, typ: Snippet) =
|
||||
if params.needsComma:
|
||||
builder.add(", ")
|
||||
else:
|
||||
params.needsComma = true
|
||||
var modifiedTyp = typ
|
||||
if sfNoalias in param.flags:
|
||||
modifiedTyp.add(" NIM_NOALIAS")
|
||||
if sfCodegenDecl notin param.flags:
|
||||
builder.add(modifiedTyp)
|
||||
builder.add(" ")
|
||||
builder.add(param.loc.snippet)
|
||||
else:
|
||||
builder.add runtimeFormat(param.cgDeclFrmt, [modifiedTyp, param.loc.snippet])
|
||||
|
||||
proc addUnnamedParam(builder: var Builder, params: var ProcParamBuilder, typ: Snippet) =
|
||||
if params.needsComma:
|
||||
builder.add(", ")
|
||||
else:
|
||||
params.needsComma = true
|
||||
builder.add(typ)
|
||||
|
||||
proc addProcTypedParam(builder: var Builder, paramBuilder: var ProcParamBuilder, callConv: TCallingConvention, name: string, rettype, params: Snippet) =
|
||||
if paramBuilder.needsComma:
|
||||
builder.add(", ")
|
||||
else:
|
||||
paramBuilder.needsComma = true
|
||||
builder.add(CallingConvToStr[callConv])
|
||||
builder.add("_PTR(")
|
||||
builder.add(rettype)
|
||||
builder.add(", ")
|
||||
builder.add(name)
|
||||
builder.add(")")
|
||||
builder.add(params)
|
||||
|
||||
proc addVarargsParam(builder: var Builder, params: var ProcParamBuilder) =
|
||||
# does not exist in NIFC, needs to be proc pragma
|
||||
if params.needsComma:
|
||||
builder.add(", ")
|
||||
else:
|
||||
params.needsComma = true
|
||||
builder.add("...")
|
||||
|
||||
template addProcParams(builder: var Builder, params: out ProcParamBuilder, body: typed) =
|
||||
params = initProcParamBuilder(builder)
|
||||
body
|
||||
finishProcParamBuilder(builder, params)
|
||||
|
||||
type SimpleProcParam = tuple
|
||||
name, typ: string
|
||||
|
||||
proc cProcParams(params: varargs[SimpleProcParam]): Snippet =
|
||||
if params.len == 0: return "(void)"
|
||||
result = "("
|
||||
for i in 0 ..< params.len:
|
||||
if i != 0: result.add(", ")
|
||||
result.add(params[i].typ)
|
||||
if params[i].name.len != 0:
|
||||
result.add(" ")
|
||||
result.add(params[i].name)
|
||||
result.add(")")
|
||||
|
||||
template addProcHeaderWithParams(builder: var Builder, callConv: TCallingConvention,
|
||||
name: string, rettype: Snippet, paramBuilder: typed) =
|
||||
# on nifc should build something like (proc name params type pragmas
|
||||
# with no body given
|
||||
# or enforce this with secondary builder object
|
||||
builder.add(CallingConvToStr[callConv])
|
||||
builder.add("(")
|
||||
builder.add(rettype)
|
||||
builder.add(", ")
|
||||
builder.add(name)
|
||||
builder.add(")")
|
||||
paramBuilder
|
||||
|
||||
proc addProcHeader(builder: var Builder, callConv: TCallingConvention,
|
||||
name: string, rettype, params: Snippet) =
|
||||
# on nifc should build something like (proc name params type pragmas
|
||||
# with no body given
|
||||
# or enforce this with secondary builder object
|
||||
addProcHeaderWithParams(builder, callConv, name, rettype):
|
||||
builder.add(params)
|
||||
|
||||
proc addProcHeader(builder: var Builder, name: string, rettype, params: Snippet, isConstructor = false) =
|
||||
# no callconv
|
||||
builder.add(rettype)
|
||||
builder.add(" ")
|
||||
if isConstructor:
|
||||
builder.add("__attribute__((constructor)) ")
|
||||
builder.add(name)
|
||||
builder.add(params)
|
||||
|
||||
proc addProcHeader(builder: var Builder, m: BModule, prc: PSym, name: string, params, rettype: Snippet, addAttributes: bool) =
|
||||
# on nifc should build something like (proc name params type pragmas
|
||||
# with no body given
|
||||
# or enforce this with secondary builder object
|
||||
let noreturn = isNoReturn(m, prc)
|
||||
if sfPure in prc.flags and hasDeclspec in extccomp.CC[m.config.cCompiler].props:
|
||||
builder.add("__declspec(naked) ")
|
||||
if noreturn and hasDeclspec in extccomp.CC[m.config.cCompiler].props:
|
||||
builder.add("__declspec(noreturn) ")
|
||||
builder.add(CallingConvToStr[prc.typ.callConv])
|
||||
builder.add("(")
|
||||
builder.add(rettype)
|
||||
builder.add(", ")
|
||||
builder.add(name)
|
||||
builder.add(")")
|
||||
builder.add(params)
|
||||
if addAttributes:
|
||||
if sfPure in prc.flags and hasAttribute in extccomp.CC[m.config.cCompiler].props:
|
||||
builder.add(" __attribute__((naked))")
|
||||
if noreturn and hasAttribute in extccomp.CC[m.config.cCompiler].props:
|
||||
builder.add(" __attribute__((noreturn))")
|
||||
|
||||
proc finishProcHeaderAsProto(builder: var Builder) =
|
||||
builder.addLineEnd(";")
|
||||
|
||||
template finishProcHeaderWithBody(builder: var Builder, body: typed) =
|
||||
builder.addLineEndIndent(" {")
|
||||
body
|
||||
builder.addLineEndDedent("}")
|
||||
builder.addNewline
|
||||
|
||||
proc addProcVar(builder: var Builder, m: BModule, prc: PSym, name: string, params, rettype: Snippet,
|
||||
isStatic = false, ignoreAttributes = false) =
|
||||
# on nifc, builds full variable
|
||||
if isStatic:
|
||||
builder.add("static ")
|
||||
let noreturn = isNoReturn(m, prc)
|
||||
if not ignoreAttributes:
|
||||
if sfPure in prc.flags and hasDeclspec in extccomp.CC[m.config.cCompiler].props:
|
||||
builder.add("__declspec(naked) ")
|
||||
if noreturn and hasDeclspec in extccomp.CC[m.config.cCompiler].props:
|
||||
builder.add("__declspec(noreturn) ")
|
||||
builder.add(CallingConvToStr[prc.typ.callConv])
|
||||
builder.add("_PTR(")
|
||||
builder.add(rettype)
|
||||
builder.add(", ")
|
||||
builder.add(name)
|
||||
builder.add(")")
|
||||
builder.add(params)
|
||||
if not ignoreAttributes:
|
||||
if sfPure in prc.flags and hasAttribute in extccomp.CC[m.config.cCompiler].props:
|
||||
builder.add(" __attribute__((naked))")
|
||||
if noreturn and hasAttribute in extccomp.CC[m.config.cCompiler].props:
|
||||
builder.add(" __attribute__((noreturn))")
|
||||
# ensure we are just adding a variable:
|
||||
builder.addLineEnd(";")
|
||||
|
||||
proc addProcVar(builder: var Builder, callConv: TCallingConvention,
|
||||
name: string, params, rettype: Snippet,
|
||||
isStatic = false, isVolatile = false) =
|
||||
# on nifc, builds full variable
|
||||
if isStatic:
|
||||
builder.add("static ")
|
||||
builder.add(CallingConvToStr[callConv])
|
||||
builder.add("_PTR(")
|
||||
builder.add(rettype)
|
||||
builder.add(", ")
|
||||
if isVolatile:
|
||||
builder.add("volatile ")
|
||||
builder.add(name)
|
||||
builder.add(")")
|
||||
builder.add(params)
|
||||
# ensure we are just adding a variable:
|
||||
builder.addLineEnd(";")
|
||||
|
||||
proc addProcVar(builder: var Builder,
|
||||
name: string, params, rettype: Snippet,
|
||||
isStatic = false, isVolatile = false) =
|
||||
# no callconv
|
||||
if isStatic:
|
||||
builder.add("static ")
|
||||
builder.add(rettype)
|
||||
builder.add(" (*")
|
||||
if isVolatile:
|
||||
builder.add("volatile ")
|
||||
builder.add(name)
|
||||
builder.add(")")
|
||||
builder.add(params)
|
||||
# ensure we are just adding a variable:
|
||||
builder.addLineEnd(";")
|
||||
|
||||
type VarInitializerKind = enum
|
||||
Assignment, CppConstructor
|
||||
|
||||
proc addVar(builder: var Builder, m: BModule, s: PSym, name: string, typ: Snippet, kind = Local, visibility: DeclVisibility = None, initializer: Snippet = "", initializerKind: VarInitializerKind = Assignment) =
|
||||
if sfCodegenDecl in s.flags:
|
||||
builder.add(runtimeFormat(s.cgDeclFrmt, [typ, name]))
|
||||
if initializer.len != 0:
|
||||
if initializerKind == Assignment:
|
||||
builder.add(" = ")
|
||||
builder.add(initializer)
|
||||
builder.addLineEnd(";")
|
||||
return
|
||||
if s.kind in {skLet, skVar, skField, skForVar} and s.alignment > 0:
|
||||
builder.add("NIM_ALIGN(" & $s.alignment & ") ")
|
||||
builder.addVisibilityPrefix(visibility)
|
||||
if kind == Threadvar:
|
||||
if optThreads in m.config.globalOptions:
|
||||
let sym = s.typ.sym
|
||||
if sym != nil and sfCppNonPod in sym.flags:
|
||||
builder.add("NIM_THREAD_LOCAL ")
|
||||
else: builder.add("NIM_THREADVAR ")
|
||||
else:
|
||||
builder.addVarHeader(kind)
|
||||
builder.add(typ)
|
||||
if sfRegister in s.flags: builder.add(" register")
|
||||
if sfVolatile in s.flags: builder.add(" volatile")
|
||||
if sfNoalias in s.flags: builder.add(" NIM_NOALIAS")
|
||||
builder.add(" ")
|
||||
builder.add(name)
|
||||
if initializer.len != 0:
|
||||
if initializerKind == Assignment:
|
||||
builder.add(" = ")
|
||||
builder.add(initializer)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
proc addInclude(builder: var Builder, value: Snippet) =
|
||||
builder.addLineEnd("#include " & value)
|
||||
259
compiler/cbuilderexprs.nim
Normal file
259
compiler/cbuilderexprs.nim
Normal file
@@ -0,0 +1,259 @@
|
||||
proc constType(t: Snippet): Snippet =
|
||||
# needs manipulation of `t` in nifc
|
||||
"NIM_CONST " & t
|
||||
|
||||
proc constPtrType(t: Snippet): Snippet =
|
||||
t & "* NIM_CONST"
|
||||
|
||||
proc ptrConstType(t: Snippet): Snippet =
|
||||
"NIM_CONST " & t & "*"
|
||||
|
||||
proc ptrType(t: Snippet): Snippet =
|
||||
t & "*"
|
||||
|
||||
proc cppRefType(t: Snippet): Snippet =
|
||||
t & "&"
|
||||
|
||||
const
|
||||
CallingConvToStr: array[TCallingConvention, string] = ["N_NIMCALL",
|
||||
"N_STDCALL", "N_CDECL", "N_SAFECALL",
|
||||
"N_SYSCALL", # this is probably not correct for all platforms,
|
||||
# but one can #define it to what one wants
|
||||
"N_INLINE", "N_NOINLINE", "N_FASTCALL", "N_THISCALL", "N_CLOSURE", "N_NOCONV",
|
||||
"N_NOCONV" #ccMember is N_NOCONV
|
||||
]
|
||||
|
||||
proc procPtrTypeUnnamed(rettype, params: Snippet): Snippet =
|
||||
rettype & "(*)" & params
|
||||
|
||||
proc procPtrTypeUnnamedNimCall(rettype, params: Snippet): Snippet =
|
||||
rettype & "(N_RAW_NIMCALL*)" & params
|
||||
|
||||
proc procPtrTypeUnnamed(callConv: TCallingConvention, rettype, params: Snippet): Snippet =
|
||||
CallingConvToStr[callConv] & "_PTR(" & rettype & ", )" & params
|
||||
|
||||
type CppCaptureKind = enum None, ByReference, ByCopy
|
||||
|
||||
template addCppLambda(builder: var Builder, captures: CppCaptureKind, params: Snippet, body: typed) =
|
||||
builder.add("[")
|
||||
case captures
|
||||
of None: discard
|
||||
of ByReference: builder.add("&")
|
||||
of ByCopy: builder.add("=")
|
||||
builder.add("] ")
|
||||
builder.add(params)
|
||||
builder.addLineEndIndent(" {")
|
||||
body
|
||||
builder.addLineEndDedent("}")
|
||||
|
||||
proc cCast(typ, value: Snippet): Snippet =
|
||||
"((" & typ & ") " & value & ")"
|
||||
|
||||
proc wrapPar(value: Snippet): Snippet =
|
||||
# used for expression group, no-op on sexp
|
||||
"(" & value & ")"
|
||||
|
||||
proc removeSinglePar(value: Snippet): Snippet =
|
||||
# removes a single paren layer expected to exist, to silence Wparentheses-equality
|
||||
assert value[0] == '(' and value[^1] == ')'
|
||||
value[1..^2]
|
||||
|
||||
template addCast(builder: var Builder, typ: Snippet, valueBody: typed) =
|
||||
## adds a cast to `typ` with value built by `valueBody`
|
||||
builder.add "(("
|
||||
builder.add typ
|
||||
builder.add ") "
|
||||
valueBody
|
||||
builder.add ")"
|
||||
|
||||
proc cAddr(value: Snippet): Snippet =
|
||||
"(&" & value & ")"
|
||||
|
||||
proc cLabelAddr(value: TLabel): Snippet =
|
||||
"&&" & value
|
||||
|
||||
proc cDeref(value: Snippet): Snippet =
|
||||
"(*" & value & ")"
|
||||
|
||||
proc subscript(a, b: Snippet): Snippet =
|
||||
a & "[" & b & "]"
|
||||
|
||||
proc dotField(a, b: Snippet): Snippet =
|
||||
a & "." & b
|
||||
|
||||
proc derefField(a, b: Snippet): Snippet =
|
||||
a & "->" & b
|
||||
|
||||
type CallBuilder = object
|
||||
needsComma: bool
|
||||
|
||||
proc initCallBuilder(builder: var Builder, callee: Snippet): CallBuilder =
|
||||
result = CallBuilder(needsComma: false)
|
||||
builder.add(callee)
|
||||
builder.add("(")
|
||||
|
||||
const cArgumentSeparator = ", "
|
||||
|
||||
proc addArgumentSeparator(builder: var Builder) =
|
||||
# no-op on NIFC
|
||||
# used by "single argument" builders
|
||||
builder.add(cArgumentSeparator)
|
||||
|
||||
template addArgument(builder: var Builder, call: var CallBuilder, valueBody: typed) =
|
||||
if call.needsComma:
|
||||
builder.addArgumentSeparator()
|
||||
else:
|
||||
call.needsComma = true
|
||||
valueBody
|
||||
|
||||
proc finishCallBuilder(builder: var Builder, call: CallBuilder) =
|
||||
builder.add(")")
|
||||
|
||||
template addCall(builder: var Builder, call: out CallBuilder, callee: Snippet, body: typed) =
|
||||
call = initCallBuilder(builder, callee)
|
||||
body
|
||||
finishCallBuilder(builder, call)
|
||||
|
||||
proc addCall(builder: var Builder, callee: Snippet, args: varargs[Snippet]) =
|
||||
builder.add(callee)
|
||||
builder.add("(")
|
||||
if args.len != 0:
|
||||
builder.add(args[0])
|
||||
for i in 1 ..< args.len:
|
||||
builder.add(", ")
|
||||
builder.add(args[i])
|
||||
builder.add(")")
|
||||
|
||||
proc cCall(callee: Snippet, args: varargs[Snippet]): Snippet =
|
||||
result = callee
|
||||
result.add("(")
|
||||
if args.len != 0:
|
||||
result.add(args[0])
|
||||
for i in 1 ..< args.len:
|
||||
result.add(", ")
|
||||
result.add(args[i])
|
||||
result.add(")")
|
||||
|
||||
proc addSizeof(builder: var Builder, val: Snippet) =
|
||||
builder.add("sizeof(")
|
||||
builder.add(val)
|
||||
builder.add(")")
|
||||
|
||||
proc addAlignof(builder: var Builder, val: Snippet) =
|
||||
builder.add("NIM_ALIGNOF(")
|
||||
builder.add(val)
|
||||
builder.add(")")
|
||||
|
||||
proc addOffsetof(builder: var Builder, val, member: Snippet) =
|
||||
builder.add("offsetof(")
|
||||
builder.add(val)
|
||||
builder.add(", ")
|
||||
builder.add(member)
|
||||
builder.add(")")
|
||||
|
||||
template cSizeof(val: Snippet): Snippet =
|
||||
"sizeof(" & val & ")"
|
||||
|
||||
template cAlignof(val: Snippet): Snippet =
|
||||
"NIM_ALIGNOF(" & val & ")"
|
||||
|
||||
template cOffsetof(val, member: Snippet): Snippet =
|
||||
"offsetof(" & val & ", " & member & ")"
|
||||
|
||||
type TypedBinaryOp = enum
|
||||
Add, Sub, Mul, Div, Mod
|
||||
Shr, Shl, BitAnd, BitOr, BitXor
|
||||
|
||||
const typedBinaryOperators: array[TypedBinaryOp, string] = [
|
||||
Add: "+",
|
||||
Sub: "-",
|
||||
Mul: "*",
|
||||
Div: "/",
|
||||
Mod: "%",
|
||||
Shr: ">>",
|
||||
Shl: "<<",
|
||||
BitAnd: "&",
|
||||
BitOr: "|",
|
||||
BitXor: "^"
|
||||
]
|
||||
|
||||
type TypedUnaryOp = enum
|
||||
Neg, BitNot
|
||||
|
||||
const typedUnaryOperators: array[TypedUnaryOp, string] = [
|
||||
Neg: "-",
|
||||
BitNot: "~",
|
||||
]
|
||||
|
||||
type UntypedBinaryOp = enum
|
||||
LessEqual, LessThan, GreaterEqual, GreaterThan, Equal, NotEqual
|
||||
And, Or
|
||||
|
||||
const untypedBinaryOperators: array[UntypedBinaryOp, string] = [
|
||||
LessEqual: "<=",
|
||||
LessThan: "<",
|
||||
GreaterEqual: ">=",
|
||||
GreaterThan: ">",
|
||||
Equal: "==",
|
||||
NotEqual: "!=",
|
||||
And: "&&",
|
||||
Or: "||"
|
||||
]
|
||||
|
||||
type UntypedUnaryOp = enum
|
||||
Not
|
||||
|
||||
const untypedUnaryOperators: array[UntypedUnaryOp, string] = [
|
||||
Not: "!"
|
||||
]
|
||||
|
||||
proc addOp(builder: var Builder, binOp: TypedBinaryOp, t: Snippet, a, b: Snippet) =
|
||||
builder.add('(')
|
||||
builder.add(a)
|
||||
builder.add(' ')
|
||||
builder.add(typedBinaryOperators[binOp])
|
||||
builder.add(' ')
|
||||
builder.add(b)
|
||||
builder.add(')')
|
||||
|
||||
proc addOp(builder: var Builder, unOp: TypedUnaryOp, t: Snippet, a: Snippet) =
|
||||
builder.add('(')
|
||||
builder.add(typedUnaryOperators[unOp])
|
||||
builder.add('(')
|
||||
builder.add(a)
|
||||
builder.add("))")
|
||||
|
||||
proc addOp(builder: var Builder, binOp: UntypedBinaryOp, a, b: Snippet) =
|
||||
builder.add('(')
|
||||
builder.add(a)
|
||||
builder.add(' ')
|
||||
builder.add(untypedBinaryOperators[binOp])
|
||||
builder.add(' ')
|
||||
builder.add(b)
|
||||
builder.add(')')
|
||||
|
||||
proc addOp(builder: var Builder, unOp: UntypedUnaryOp, a: Snippet) =
|
||||
builder.add('(')
|
||||
builder.add(untypedUnaryOperators[unOp])
|
||||
builder.add('(')
|
||||
builder.add(a)
|
||||
builder.add("))")
|
||||
|
||||
template cOp(binOp: TypedBinaryOp, t: Snippet, a, b: Snippet): Snippet =
|
||||
'(' & a & ' ' & typedBinaryOperators[binOp] & ' ' & b & ')'
|
||||
|
||||
template cOp(binOp: TypedUnaryOp, t: Snippet, a: Snippet): Snippet =
|
||||
'(' & typedUnaryOperators[binOp] & '(' & a & "))"
|
||||
|
||||
template cOp(binOp: UntypedBinaryOp, a, b: Snippet): Snippet =
|
||||
'(' & a & ' ' & untypedBinaryOperators[binOp] & ' ' & b & ')'
|
||||
|
||||
template cOp(binOp: UntypedUnaryOp, a: Snippet): Snippet =
|
||||
'(' & untypedUnaryOperators[binOp] & '(' & a & "))"
|
||||
|
||||
template cIfExpr(cond, a, b: Snippet): Snippet =
|
||||
# XXX used for `min` and `max`, maybe add nifc primitives for these
|
||||
"(" & cond & " ? " & a & " : " & b & ")"
|
||||
|
||||
template cUnlikely(val: Snippet): Snippet =
|
||||
"NIM_UNLIKELY(" & val & ")"
|
||||
329
compiler/cbuilderstmts.nim
Normal file
329
compiler/cbuilderstmts.nim
Normal file
@@ -0,0 +1,329 @@
|
||||
template addAssignmentWithValue(builder: var Builder, lhs: Snippet, valueBody: typed) =
|
||||
builder.add(lhs)
|
||||
builder.add(" = ")
|
||||
valueBody
|
||||
builder.addLineEnd(";")
|
||||
|
||||
template addFieldAssignmentWithValue(builder: var Builder, lhs: Snippet, name: string, valueBody: typed) =
|
||||
builder.add(lhs)
|
||||
builder.add("." & name & " = ")
|
||||
valueBody
|
||||
builder.addLineEnd(";")
|
||||
|
||||
template addAssignment(builder: var Builder, lhs, rhs: Snippet) =
|
||||
builder.addAssignmentWithValue(lhs):
|
||||
builder.add(rhs)
|
||||
|
||||
template addFieldAssignment(builder: var Builder, lhs: Snippet, name: string, rhs: Snippet) =
|
||||
builder.addFieldAssignmentWithValue(lhs, name):
|
||||
builder.add(rhs)
|
||||
|
||||
template addMutualFieldAssignment(builder: var Builder, lhs, rhs: Snippet, name: string) =
|
||||
builder.addFieldAssignmentWithValue(lhs, name):
|
||||
builder.add(rhs)
|
||||
builder.add("." & name)
|
||||
|
||||
template addAssignment(builder: var Builder, lhs: Snippet, rhs: int | int64 | uint64 | Int128) =
|
||||
builder.addAssignmentWithValue(lhs):
|
||||
builder.addIntValue(rhs)
|
||||
|
||||
template addFieldAssignment(builder: var Builder, lhs: Snippet, name: string, rhs: int | int64 | uint64 | Int128) =
|
||||
builder.addFieldAssignmentWithValue(lhs, name):
|
||||
builder.addIntValue(rhs)
|
||||
|
||||
template addDerefFieldAssignment(builder: var Builder, lhs: Snippet, name: string, rhs: Snippet) =
|
||||
builder.add(lhs)
|
||||
builder.add("->" & name & " = ")
|
||||
builder.add(rhs)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
template addSubscriptAssignment(builder: var Builder, lhs: Snippet, index: Snippet, rhs: Snippet) =
|
||||
builder.add(lhs)
|
||||
builder.add("[" & index & "] = ")
|
||||
builder.add(rhs)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
template addStmt(builder: var Builder, stmtBody: typed) =
|
||||
## makes an expression built by `stmtBody` into a statement
|
||||
stmtBody
|
||||
builder.addLineEnd(";")
|
||||
|
||||
proc addCallStmt(builder: var Builder, callee: Snippet, args: varargs[Snippet]) =
|
||||
builder.addStmt():
|
||||
builder.addCall(callee, args)
|
||||
|
||||
# XXX blocks need indent tracker in `Builder` object
|
||||
|
||||
template addSingleIfStmt(builder: var Builder, cond: Snippet, body: typed) =
|
||||
builder.add("if (")
|
||||
builder.add(cond)
|
||||
builder.addLineEndIndent(") {")
|
||||
body
|
||||
builder.addLineEndDedent("}")
|
||||
|
||||
template addSingleIfStmtWithCond(builder: var Builder, condBody: typed, body: typed) =
|
||||
builder.add("if (")
|
||||
condBody
|
||||
builder.addLineEndIndent(") {")
|
||||
body
|
||||
builder.addLineEndDedent("}")
|
||||
|
||||
proc initIfStmt(builder: var Builder): IfBuilder =
|
||||
IfBuilder(state: WaitingIf)
|
||||
|
||||
proc finishIfStmt(builder: var Builder, stmt: IfBuilder) =
|
||||
assert stmt.state != InBlock
|
||||
builder.addNewline()
|
||||
|
||||
template addIfStmt(builder: var Builder, stmt: out IfBuilder, body: typed) =
|
||||
stmt = initIfStmt(builder)
|
||||
body
|
||||
finishIfStmt(builder, stmt)
|
||||
|
||||
proc initElifBranch(builder: var Builder, stmt: var IfBuilder, cond: Snippet) =
|
||||
case stmt.state
|
||||
of WaitingIf:
|
||||
builder.add("if (")
|
||||
of WaitingElseIf:
|
||||
builder.add(" else if (")
|
||||
else: assert false, $stmt.state
|
||||
builder.add(cond)
|
||||
builder.addLineEndIndent(") {")
|
||||
stmt.state = InBlock
|
||||
|
||||
proc initElseBranch(builder: var Builder, stmt: var IfBuilder) =
|
||||
assert stmt.state == WaitingElseIf, $stmt.state
|
||||
builder.addLineEndIndent(" else {")
|
||||
stmt.state = InBlock
|
||||
|
||||
proc finishBranch(builder: var Builder, stmt: var IfBuilder) =
|
||||
builder.addDedent("}")
|
||||
stmt.state = WaitingElseIf
|
||||
|
||||
template addElifBranch(builder: var Builder, stmt: var IfBuilder, cond: Snippet, body: typed) =
|
||||
initElifBranch(builder, stmt, cond)
|
||||
body
|
||||
finishBranch(builder, stmt)
|
||||
|
||||
template addElseBranch(builder: var Builder, stmt: var IfBuilder, body: typed) =
|
||||
initElseBranch(builder, stmt)
|
||||
body
|
||||
finishBranch(builder, stmt)
|
||||
|
||||
proc initForRange(builder: var Builder, i, start, bound: Snippet, inclusive: bool = false) =
|
||||
builder.add("for (")
|
||||
builder.add(i)
|
||||
builder.add(" = ")
|
||||
builder.add(start)
|
||||
builder.add("; ")
|
||||
builder.add(i)
|
||||
if inclusive:
|
||||
builder.add(" <= ")
|
||||
else:
|
||||
builder.add(" < ")
|
||||
builder.add(bound)
|
||||
builder.add("; ")
|
||||
builder.add(i)
|
||||
builder.addLineEndIndent("++) {")
|
||||
|
||||
proc initForStep(builder: var Builder, i, start, bound, step: Snippet, inclusive: bool = false) =
|
||||
builder.add("for (")
|
||||
builder.add(i)
|
||||
builder.add(" = ")
|
||||
builder.add(start)
|
||||
builder.add("; ")
|
||||
builder.add(i)
|
||||
if inclusive:
|
||||
builder.add(" <= ")
|
||||
else:
|
||||
builder.add(" < ")
|
||||
builder.add(bound)
|
||||
builder.add("; ")
|
||||
builder.add(i)
|
||||
builder.add(" += ")
|
||||
builder.add(step)
|
||||
builder.addLineEndIndent(") {")
|
||||
|
||||
proc finishFor(builder: var Builder) {.inline.} =
|
||||
builder.addLineEndDedent("}")
|
||||
|
||||
template addForRangeExclusive(builder: var Builder, i, start, bound: Snippet, body: typed) =
|
||||
initForRange(builder, i, start, bound, false)
|
||||
body
|
||||
finishFor(builder)
|
||||
|
||||
template addForRangeInclusive(builder: var Builder, i, start, bound: Snippet, body: typed) =
|
||||
initForRange(builder, i, start, bound, true)
|
||||
body
|
||||
finishFor(builder)
|
||||
|
||||
template addSwitchStmt(builder: var Builder, val: Snippet, body: typed) =
|
||||
builder.add("switch (")
|
||||
builder.add(val)
|
||||
builder.addLineEnd(") {") # no indent
|
||||
body
|
||||
builder.addLineEnd("}")
|
||||
|
||||
template addSingleSwitchCase(builder: var Builder, val: Snippet, body: typed) =
|
||||
builder.add("case ")
|
||||
builder.add(val)
|
||||
builder.addLineEndIndent(":")
|
||||
body
|
||||
builder.addLineEndDedent("")
|
||||
|
||||
type
|
||||
SwitchCaseState = enum
|
||||
None, Of, Else, Finished
|
||||
SwitchCaseBuilder = object
|
||||
state: SwitchCaseState
|
||||
|
||||
proc addCase(builder: var Builder, info: var SwitchCaseBuilder, val: Snippet) =
|
||||
if info.state != Of:
|
||||
assert info.state == None
|
||||
info.state = Of
|
||||
builder.add("case ")
|
||||
builder.add(val)
|
||||
builder.addLineEndIndent(":")
|
||||
|
||||
proc addCaseRange(builder: var Builder, info: var SwitchCaseBuilder, first, last: Snippet) =
|
||||
if info.state != Of:
|
||||
assert info.state == None
|
||||
info.state = Of
|
||||
builder.add("case ")
|
||||
builder.add(first)
|
||||
builder.add(" ... ")
|
||||
builder.add(last)
|
||||
builder.addLineEndIndent(":")
|
||||
|
||||
proc addCaseElse(builder: var Builder, info: var SwitchCaseBuilder) =
|
||||
assert info.state == None
|
||||
info.state = Else
|
||||
builder.addLineEndIndent("default:")
|
||||
|
||||
template addSwitchCase(builder: var Builder, info: out SwitchCaseBuilder, caseBody, body: typed) =
|
||||
info = SwitchCaseBuilder(state: None)
|
||||
caseBody
|
||||
info.state = Finished
|
||||
body
|
||||
builder.addLineEndDedent("")
|
||||
|
||||
template addSwitchElse(builder: var Builder, body: typed) =
|
||||
builder.addLineEndIndent("default:")
|
||||
body
|
||||
builder.addLineEndDedent("")
|
||||
|
||||
proc addBreak(builder: var Builder) =
|
||||
builder.addLineEnd("break;")
|
||||
|
||||
type ScopeBuilder = object
|
||||
inside: bool
|
||||
|
||||
proc initScope(builder: var Builder): ScopeBuilder =
|
||||
builder.addLineEndIndent("{")
|
||||
result = ScopeBuilder(inside: true)
|
||||
|
||||
proc finishScope(builder: var Builder, scope: var ScopeBuilder) =
|
||||
assert scope.inside, "scope not inited"
|
||||
builder.addLineEndDedent("}")
|
||||
scope.inside = false
|
||||
|
||||
template addScope(builder: var Builder, body: typed) =
|
||||
builder.addLineEndIndent("{")
|
||||
body
|
||||
builder.addLineEndDedent("}")
|
||||
|
||||
type WhileBuilder = object
|
||||
inside: bool
|
||||
|
||||
proc initWhileStmt(builder: var Builder, cond: Snippet): WhileBuilder =
|
||||
builder.add("while (")
|
||||
builder.add(cond)
|
||||
builder.addLineEndIndent(") {")
|
||||
result = WhileBuilder(inside: true)
|
||||
|
||||
proc finishWhileStmt(builder: var Builder, stmt: var WhileBuilder) =
|
||||
assert stmt.inside, "while stmt not inited"
|
||||
builder.addLineEndDedent("}")
|
||||
stmt.inside = false
|
||||
|
||||
template addWhileStmt(builder: var Builder, cond: Snippet, body: typed) =
|
||||
builder.add("while (")
|
||||
builder.add(cond)
|
||||
builder.addLineEndIndent(") {")
|
||||
body
|
||||
builder.addLineEndDedent("}")
|
||||
|
||||
proc addLabel(builder: var Builder, name: TLabel) =
|
||||
builder.add(name)
|
||||
builder.addLineEnd(": ;")
|
||||
|
||||
proc addReturn(builder: var Builder) =
|
||||
builder.addLineEnd("return;")
|
||||
|
||||
proc addReturn(builder: var Builder, value: Snippet) =
|
||||
builder.add("return ")
|
||||
builder.add(value)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
proc addGoto(builder: var Builder, label: TLabel) =
|
||||
builder.add("goto ")
|
||||
builder.add(label)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
proc addComputedGoto(builder: var Builder, value: Snippet) =
|
||||
builder.add("goto *")
|
||||
builder.add(value)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
proc addIncr(builder: var Builder, val: Snippet) =
|
||||
builder.add(val)
|
||||
builder.addLineEnd("++;")
|
||||
|
||||
proc addDecr(builder: var Builder, val: Snippet) =
|
||||
builder.add(val)
|
||||
builder.addLineEnd("--;")
|
||||
|
||||
proc addInPlaceOp(builder: var Builder, binOp: TypedBinaryOp, t: Snippet, a, b: Snippet) =
|
||||
builder.add(a)
|
||||
builder.add(' ')
|
||||
builder.add(typedBinaryOperators[binOp])
|
||||
builder.add("= ")
|
||||
builder.add(b)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
proc addInPlaceOp(builder: var Builder, binOp: UntypedBinaryOp, a, b: Snippet) =
|
||||
builder.add(a)
|
||||
builder.add(' ')
|
||||
builder.add(untypedBinaryOperators[binOp])
|
||||
builder.add("= ")
|
||||
builder.add(b)
|
||||
builder.addLineEnd(";")
|
||||
|
||||
proc cInPlaceOp(binOp: TypedBinaryOp, t: Snippet, a, b: Snippet): Snippet =
|
||||
result = ""
|
||||
result.add(a)
|
||||
result.add(' ')
|
||||
result.add(typedBinaryOperators[binOp])
|
||||
result.add("= ")
|
||||
result.add(b)
|
||||
result.add(";\n")
|
||||
|
||||
proc cInPlaceOp(binOp: UntypedBinaryOp, a, b: Snippet): Snippet =
|
||||
result = ""
|
||||
result.add(a)
|
||||
result.add(' ')
|
||||
result.add(untypedBinaryOperators[binOp])
|
||||
result.add("= ")
|
||||
result.add(b)
|
||||
result.add(";\n")
|
||||
|
||||
template addCPragma(builder: var Builder, val: Snippet) =
|
||||
builder.addNewline()
|
||||
builder.add("#pragma ")
|
||||
builder.add(val)
|
||||
builder.addNewline()
|
||||
|
||||
proc addDiscard(builder: var Builder, val: Snippet) =
|
||||
builder.add("(void)")
|
||||
builder.add(val)
|
||||
builder.addLineEnd(";")
|
||||
@@ -84,20 +84,21 @@ proc cleanupTemp(p: BProc; returnType: PType, tmp: TLoc): bool =
|
||||
let dtor = getAttachedOp(p.module.g.graph, returnType, attachedDestructor)
|
||||
var op = initLocExpr(p, newSymNode(dtor))
|
||||
var callee = rdLoc(op)
|
||||
let destroy = if dtor.typ.firstParamType.kind == tyVar:
|
||||
callee & "(&" & rdLoc(tmp) & ")"
|
||||
let destroyArg =
|
||||
if dtor.typ.firstParamType.kind == tyVar:
|
||||
cAddr(rdLoc(tmp))
|
||||
else:
|
||||
callee & "(" & rdLoc(tmp) & ")"
|
||||
rdLoc(tmp)
|
||||
let destroy = cCall(callee, destroyArg)
|
||||
raiseExitCleanup(p, destroy)
|
||||
result = true
|
||||
else:
|
||||
result = false
|
||||
|
||||
proc fixupCall(p: BProc, le, ri: PNode, d: var TLoc,
|
||||
callee, params: Rope) =
|
||||
result: var Builder, call: var CallBuilder) =
|
||||
let canRaise = p.config.exc == excGoto and canRaiseDisp(p, ri[0])
|
||||
genLineDir(p, ri)
|
||||
var pl = callee & "(" & params
|
||||
# getUniqueType() is too expensive here:
|
||||
var typ = skipTypes(ri[0].typ, abstractInst)
|
||||
if typ.returnType != nil:
|
||||
@@ -106,7 +107,6 @@ proc fixupCall(p: BProc, le, ri: PNode, d: var TLoc,
|
||||
# perhaps generate no temp if the call doesn't have side effects
|
||||
flags.incl needTempForOpenArray
|
||||
if isInvalidReturnType(p.config, typ):
|
||||
if params.len != 0: pl.add(", ")
|
||||
# beware of 'result = p(result)'. We may need to allocate a temporary:
|
||||
if d.k in {locTemp, locNone} or not preventNrvo(p, d.lode, le, ri):
|
||||
# Great, we can use 'd':
|
||||
@@ -114,33 +114,39 @@ proc fixupCall(p: BProc, le, ri: PNode, d: var TLoc,
|
||||
elif d.k notin {locTemp} and not hasNoInit(ri):
|
||||
# reset before pass as 'result' var:
|
||||
discard "resetLoc(p, d)"
|
||||
pl.add(addrLoc(p.config, d))
|
||||
pl.add(");\n")
|
||||
line(p, cpsStmts, pl)
|
||||
let rad = addrLoc(p.config, d)
|
||||
result.addArgument(call):
|
||||
result.add(rad)
|
||||
result.finishCallBuilder(call)
|
||||
p.s(cpsStmts).addStmt():
|
||||
p.s(cpsStmts).add(extract(result))
|
||||
else:
|
||||
var tmp: TLoc = getTemp(p, typ.returnType, needsInit=true)
|
||||
pl.add(addrLoc(p.config, tmp))
|
||||
pl.add(");\n")
|
||||
line(p, cpsStmts, pl)
|
||||
let ratmp = addrLoc(p.config, tmp)
|
||||
result.addArgument(call):
|
||||
result.add(ratmp)
|
||||
result.finishCallBuilder(call)
|
||||
p.s(cpsStmts).addStmt():
|
||||
p.s(cpsStmts).add(extract(result))
|
||||
genAssignment(p, d, tmp, {}) # no need for deep copying
|
||||
if canRaise: raiseExit(p)
|
||||
else:
|
||||
pl.add(")")
|
||||
result.finishCallBuilder(call)
|
||||
if p.module.compileToCpp:
|
||||
if lfSingleUse in d.flags:
|
||||
# do not generate spurious temporaries for C++! For C we're better off
|
||||
# with them to prevent undefined behaviour and because the codegen
|
||||
# is free to emit expressions multiple times!
|
||||
d.k = locCall
|
||||
d.snippet = pl
|
||||
d.snippet = extract(result)
|
||||
excl d.flags, lfSingleUse
|
||||
else:
|
||||
if d.k == locNone and p.splitDecls == 0 and p.config.exc != excGoto:
|
||||
d = getTempCpp(p, typ.returnType, pl)
|
||||
d = getTempCpp(p, typ.returnType, extract(result))
|
||||
else:
|
||||
if d.k == locNone: d = getTemp(p, typ.returnType)
|
||||
var list = initLoc(locCall, d.lode, OnUnknown)
|
||||
list.snippet = pl
|
||||
list.snippet = extract(result)
|
||||
genAssignment(p, d, list, {needAssignCall}) # no need for deep copying
|
||||
if canRaise: raiseExit(p)
|
||||
|
||||
@@ -151,7 +157,7 @@ proc fixupCall(p: BProc, le, ri: PNode, d: var TLoc,
|
||||
d = getTemp(p, typ.returnType)
|
||||
assert(d.t != nil) # generate an assignment to d:
|
||||
var list = initLoc(locCall, d.lode, OnUnknown)
|
||||
list.snippet = pl
|
||||
list.snippet = extract(result)
|
||||
genAssignment(p, d, list, flags+{needAssignCall}) # no need for deep copying
|
||||
if canRaise:
|
||||
if not (useTemp and cleanupTemp(p, typ.returnType, d)):
|
||||
@@ -159,15 +165,16 @@ proc fixupCall(p: BProc, le, ri: PNode, d: var TLoc,
|
||||
else:
|
||||
var tmp: TLoc = getTemp(p, typ.returnType, needsInit=true)
|
||||
var list = initLoc(locCall, d.lode, OnUnknown)
|
||||
list.snippet = pl
|
||||
list.snippet = extract(result)
|
||||
genAssignment(p, tmp, list, flags+{needAssignCall}) # no need for deep copying
|
||||
if canRaise:
|
||||
if not cleanupTemp(p, typ.returnType, tmp):
|
||||
raiseExit(p)
|
||||
genAssignment(p, d, tmp, {})
|
||||
else:
|
||||
pl.add(");\n")
|
||||
line(p, cpsStmts, pl)
|
||||
finishCallBuilder(result, call)
|
||||
p.s(cpsStmts).addStmt():
|
||||
p.s(cpsStmts).add(extract(result))
|
||||
if canRaise: raiseExit(p)
|
||||
|
||||
proc genBoundsCheck(p: BProc; arr, a, b: TLoc; arrTyp: PType)
|
||||
@@ -199,49 +206,49 @@ proc genOpenArraySlice(p: BProc; q: PNode; formalType, destType: PType; prepareF
|
||||
if optBoundsCheck in p.options:
|
||||
genBoundsCheck(p, a, b, c, ty)
|
||||
if prepareForMutation:
|
||||
linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
|
||||
let bra = byRefLoc(p, a)
|
||||
p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimPrepareStrMutationV2"),
|
||||
bra)
|
||||
let dest = getTypeDesc(p.module, destType)
|
||||
let lengthExpr = "($1)-($2)+1" % [rdLoc(c), rdLoc(b)]
|
||||
let ra = rdLoc(a)
|
||||
let rb = rdLoc(b)
|
||||
let rc = rdLoc(c)
|
||||
let lengthExpr = cOp(Add, NimInt, cOp(Sub, NimInt, rc, rb), cIntValue(1))
|
||||
case ty.kind
|
||||
of tyArray:
|
||||
let first = toInt64(firstOrd(p.config, ty))
|
||||
if first == 0:
|
||||
result = ("($3*)(($1)+($2))" % [rdLoc(a), rdLoc(b), dest],
|
||||
lengthExpr)
|
||||
result = (cCast(ptrType(dest), cOp(Add, NimInt, ra, rb)), lengthExpr)
|
||||
else:
|
||||
var lit = newRopeAppender()
|
||||
intLiteral(first, lit)
|
||||
result = ("($4*)($1)+(($2)-($3))" %
|
||||
[rdLoc(a), rdLoc(b), lit, dest],
|
||||
lengthExpr)
|
||||
let lit = cIntLiteral(first)
|
||||
result = (cCast(ptrType(dest), cOp(Add, NimInt, ra, cOp(Sub, NimInt, rb, lit))), lengthExpr)
|
||||
of tyOpenArray, tyVarargs:
|
||||
if reifiedOpenArray(q[1]):
|
||||
result = ("($3*)($1.Field0)+($2)" % [rdLoc(a), rdLoc(b), dest],
|
||||
lengthExpr)
|
||||
else:
|
||||
result = ("($3*)($1)+($2)" % [rdLoc(a), rdLoc(b), dest],
|
||||
lengthExpr)
|
||||
let data = if reifiedOpenArray(q[1]): dotField(ra, "Field0") else: ra
|
||||
result = (cCast(ptrType(dest), cOp(Add, NimInt, data, rb)), lengthExpr)
|
||||
of tyUncheckedArray, tyCstring:
|
||||
result = ("($3*)($1)+($2)" % [rdLoc(a), rdLoc(b), dest],
|
||||
lengthExpr)
|
||||
result = (cCast(ptrType(dest), cOp(Add, NimInt, ra, rb)), lengthExpr)
|
||||
of tyString, tySequence:
|
||||
let atyp = skipTypes(a.t, abstractInst)
|
||||
if formalType.skipTypes(abstractInst).kind in {tyVar} and atyp.kind == tyString and
|
||||
optSeqDestructors in p.config.globalOptions:
|
||||
linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
|
||||
let bra = byRefLoc(p, a)
|
||||
p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimPrepareStrMutationV2"),
|
||||
bra)
|
||||
var val: Snippet
|
||||
if atyp.kind in {tyVar} and not compileToCpp(p.module):
|
||||
result = ("(($5) ? (($4*)(*$1)$3+($2)) : NIM_NIL)" %
|
||||
[rdLoc(a), rdLoc(b), dataField(p), dest, dataFieldAccessor(p, "*" & rdLoc(a))],
|
||||
lengthExpr)
|
||||
val = cDeref(ra)
|
||||
else:
|
||||
result = ("(($5) ? (($4*)$1$3+($2)) : NIM_NIL)" %
|
||||
[rdLoc(a), rdLoc(b), dataField(p), dest, dataFieldAccessor(p, rdLoc(a))],
|
||||
lengthExpr)
|
||||
val = ra
|
||||
result = (
|
||||
cIfExpr(dataFieldAccessor(p, val),
|
||||
cCast(ptrType(dest), cOp(Add, NimInt, dataField(p, val), rb)),
|
||||
NimNil),
|
||||
lengthExpr)
|
||||
else:
|
||||
result = ("", "")
|
||||
internalError(p.config, "openArrayLoc: " & typeToString(a.t))
|
||||
|
||||
proc openArrayLoc(p: BProc, formalType: PType, n: PNode; result: var Rope) =
|
||||
proc openArrayLoc(p: BProc, formalType: PType, n: PNode; result: var Builder) =
|
||||
var q = skipConv(n)
|
||||
var skipped = false
|
||||
while q.kind == nkStmtListExpr and q.len > 0:
|
||||
@@ -256,42 +263,66 @@ proc openArrayLoc(p: BProc, formalType: PType, n: PNode; result: var Rope) =
|
||||
genStmts(p, q[i])
|
||||
q = q.lastSon
|
||||
let (x, y) = genOpenArraySlice(p, q, formalType, n.typ.elementType)
|
||||
result.add x & ", " & y
|
||||
result.add(x)
|
||||
result.addArgumentSeparator()
|
||||
result.add(y)
|
||||
else:
|
||||
var a = initLocExpr(p, if n.kind == nkHiddenStdConv: n[1] else: n)
|
||||
case skipTypes(a.t, abstractVar+{tyStatic}).kind
|
||||
of tyOpenArray, tyVarargs:
|
||||
let ra = rdLoc(a)
|
||||
if reifiedOpenArray(n):
|
||||
if a.t.kind in {tyVar, tyLent}:
|
||||
result.add "$1->Field0, $1->Field1" % [rdLoc(a)]
|
||||
result.add(derefField(ra, "Field0"))
|
||||
result.addArgumentSeparator()
|
||||
result.add(derefField(ra, "Field1"))
|
||||
else:
|
||||
result.add "$1.Field0, $1.Field1" % [rdLoc(a)]
|
||||
result.add(dotField(ra, "Field0"))
|
||||
result.addArgumentSeparator()
|
||||
result.add(dotField(ra, "Field1"))
|
||||
else:
|
||||
result.add "$1, $1Len_0" % [rdLoc(a)]
|
||||
result.add(ra)
|
||||
result.addArgumentSeparator()
|
||||
result.add(ra & "Len_0")
|
||||
of tyString, tySequence:
|
||||
let ntyp = skipTypes(n.typ, abstractInst)
|
||||
if formalType.skipTypes(abstractInst).kind in {tyVar} and ntyp.kind == tyString and
|
||||
optSeqDestructors in p.config.globalOptions:
|
||||
linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
|
||||
let bra = byRefLoc(p, a)
|
||||
p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimPrepareStrMutationV2"),
|
||||
bra)
|
||||
if ntyp.kind in {tyVar} and not compileToCpp(p.module):
|
||||
var t = TLoc(snippet: "(*$1)" % [a.rdLoc])
|
||||
result.add "($4) ? ((*$1)$3) : NIM_NIL, $2" %
|
||||
[a.rdLoc, lenExpr(p, t), dataField(p),
|
||||
dataFieldAccessor(p, "*" & a.rdLoc)]
|
||||
let ra = a.rdLoc
|
||||
var t = TLoc(snippet: cDeref(ra))
|
||||
let lt = lenExpr(p, t)
|
||||
result.add(cIfExpr(dataFieldAccessor(p, t.snippet), dataField(p, t.snippet), NimNil))
|
||||
result.addArgumentSeparator()
|
||||
result.add(lt)
|
||||
else:
|
||||
result.add "($4) ? ($1$3) : NIM_NIL, $2" %
|
||||
[a.rdLoc, lenExpr(p, a), dataField(p), dataFieldAccessor(p, a.rdLoc)]
|
||||
let ra = a.rdLoc
|
||||
let la = lenExpr(p, a)
|
||||
result.add(cIfExpr(dataFieldAccessor(p, ra), dataField(p, ra), NimNil))
|
||||
result.addArgumentSeparator()
|
||||
result.add(la)
|
||||
of tyArray:
|
||||
result.add "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, a.t))]
|
||||
let ra = rdLoc(a)
|
||||
result.add(ra)
|
||||
result.addArgumentSeparator()
|
||||
result.addIntValue(lengthOrd(p.config, a.t))
|
||||
of tyPtr, tyRef:
|
||||
case elementType(a.t).kind
|
||||
of tyString, tySequence:
|
||||
var t = TLoc(snippet: "(*$1)" % [a.rdLoc])
|
||||
result.add "($4) ? ((*$1)$3) : NIM_NIL, $2" %
|
||||
[a.rdLoc, lenExpr(p, t), dataField(p),
|
||||
dataFieldAccessor(p, "*" & a.rdLoc)]
|
||||
let ra = a.rdLoc
|
||||
var t = TLoc(snippet: cDeref(ra))
|
||||
let lt = lenExpr(p, t)
|
||||
result.add(cIfExpr(dataFieldAccessor(p, t.snippet), dataField(p, t.snippet), NimNil))
|
||||
result.addArgumentSeparator()
|
||||
result.add(lt)
|
||||
of tyArray:
|
||||
result.add "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, elementType(a.t)))]
|
||||
let ra = rdLoc(a)
|
||||
result.add(ra)
|
||||
result.addArgumentSeparator()
|
||||
result.addIntValue(lengthOrd(p.config, elementType(a.t)))
|
||||
else:
|
||||
internalError(p.config, "openArrayLoc: " & typeToString(a.t))
|
||||
else: internalError(p.config, "openArrayLoc: " & typeToString(a.t))
|
||||
@@ -311,11 +342,12 @@ proc literalsNeedsTmp(p: BProc, a: TLoc): TLoc =
|
||||
result = getTemp(p, a.lode.typ, needsInit=false)
|
||||
genAssignment(p, result, a, {})
|
||||
|
||||
proc genArgStringToCString(p: BProc, n: PNode; result: var Rope; needsTmp: bool) {.inline.} =
|
||||
proc genArgStringToCString(p: BProc, n: PNode; result: var Builder; needsTmp: bool) {.inline.} =
|
||||
var a = initLocExpr(p, n[0])
|
||||
appcg(p.module, result, "#nimToCStringConv($1)", [withTmpIfNeeded(p, a, needsTmp).rdLoc])
|
||||
let ra = withTmpIfNeeded(p, a, needsTmp).rdLoc
|
||||
result.addCall(cgsymValue(p.module, "nimToCStringConv"), ra)
|
||||
|
||||
proc genArg(p: BProc, n: PNode, param: PSym; call: PNode; result: var Rope; needsTmp = false) =
|
||||
proc genArg(p: BProc, n: PNode, param: PSym; call: PNode; result: var Builder; needsTmp = false) =
|
||||
var a: TLoc
|
||||
if n.kind == nkStringToCString:
|
||||
genArgStringToCString(p, n, result, needsTmp)
|
||||
@@ -356,12 +388,11 @@ proc genArg(p: BProc, n: PNode, param: PSym; call: PNode; result: var Rope; need
|
||||
if param.typ.kind in {tyVar, tyPtr, tyRef, tySink}:
|
||||
let typ = skipTypes(param.typ, abstractPtrs)
|
||||
if not sameBackendTypePickyAliases(typ, n.typ.skipTypes(abstractPtrs)):
|
||||
a.snippet = "(($1) ($2))" %
|
||||
[getTypeDesc(p.module, param.typ), rdCharLoc(a)]
|
||||
a.snippet = cCast(getTypeDesc(p.module, param.typ), rdCharLoc(a))
|
||||
addRdLoc(withTmpIfNeeded(p, a, needsTmp), result)
|
||||
#assert result != nil
|
||||
|
||||
proc genArgNoParam(p: BProc, n: PNode; result: var Rope; needsTmp = false) =
|
||||
proc genArgNoParam(p: BProc, n: PNode; result: var Builder; needsTmp = false) =
|
||||
var a: TLoc
|
||||
if n.kind == nkStringToCString:
|
||||
genArgStringToCString(p, n, result, needsTmp)
|
||||
@@ -424,7 +455,7 @@ proc getPotentialReads(n: PNode; result: var seq[PNode]) =
|
||||
for s in n:
|
||||
getPotentialReads(s, result)
|
||||
|
||||
proc genParams(p: BProc, ri: PNode, typ: PType; result: var Rope) =
|
||||
proc genParams(p: BProc, ri: PNode, typ: PType; result: var Builder, argBuilder: var CallBuilder) =
|
||||
# We must generate temporaries in cases like #14396
|
||||
# to keep the strict Left-To-Right evaluation
|
||||
var needTmp = newSeq[bool](ri.len - 1)
|
||||
@@ -446,21 +477,22 @@ proc genParams(p: BProc, ri: PNode, typ: PType; result: var Rope) =
|
||||
# Optimization: don't use a temp, if we would only take the address anyway
|
||||
needTmp[i - 1] = false
|
||||
|
||||
var oldLen = result.len
|
||||
for i in 1..<ri.len:
|
||||
if i < typ.n.len:
|
||||
assert(typ.n[i].kind == nkSym)
|
||||
let paramType = typ.n[i]
|
||||
if not paramType.typ.isCompileTimeOnly:
|
||||
if oldLen != result.len:
|
||||
result.add(", ")
|
||||
oldLen = result.len
|
||||
genArg(p, ri[i], paramType.sym, ri, result, needTmp[i-1])
|
||||
var arg = newBuilder("")
|
||||
genArg(p, ri[i], paramType.sym, ri, arg, needTmp[i-1])
|
||||
if arg.buf.len != 0:
|
||||
result.addArgument(argBuilder):
|
||||
result.add(extract(arg))
|
||||
else:
|
||||
if oldLen != result.len:
|
||||
result.add(", ")
|
||||
oldLen = result.len
|
||||
genArgNoParam(p, ri[i], result, needTmp[i-1])
|
||||
var arg = newBuilder("")
|
||||
genArgNoParam(p, ri[i], arg, needTmp[i-1])
|
||||
if arg.buf.len != 0:
|
||||
result.addArgument(argBuilder):
|
||||
result.add(extract(arg))
|
||||
|
||||
proc addActualSuffixForHCR(res: var Rope, module: PSym, sym: PSym) =
|
||||
if sym.flags * {sfImportc, sfNonReloadable} == {} and sym.loc.k == locProc and
|
||||
@@ -474,21 +506,39 @@ proc genPrefixCall(p: BProc, le, ri: PNode, d: var TLoc) =
|
||||
var typ = skipTypes(ri[0].typ, abstractInstOwned)
|
||||
assert(typ.kind == tyProc)
|
||||
|
||||
var params = newRopeAppender()
|
||||
genParams(p, ri, typ, params)
|
||||
|
||||
var callee = rdLoc(op)
|
||||
if p.hcrOn and ri[0].kind == nkSym:
|
||||
callee.addActualSuffixForHCR(p.module.module, ri[0].sym)
|
||||
fixupCall(p, le, ri, d, callee, params)
|
||||
|
||||
var res = newBuilder("")
|
||||
var call = initCallBuilder(res, callee)
|
||||
genParams(p, ri, typ, res, call)
|
||||
fixupCall(p, le, ri, d, res, call)
|
||||
|
||||
proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
|
||||
|
||||
proc addComma(r: Rope): Rope =
|
||||
if r.len == 0: r else: r & ", "
|
||||
template callProc(rp, params, pTyp: Snippet): Snippet =
|
||||
let e = dotField(rp, "ClE_0")
|
||||
let p = dotField(rp, "ClP_0")
|
||||
let eCall =
|
||||
# note `params` here is actually multiple params
|
||||
if params.len == 0:
|
||||
cCall(p, e)
|
||||
else:
|
||||
cCall(p, params, e)
|
||||
cIfExpr(e,
|
||||
eCall,
|
||||
cCall(cCast(pTyp, p), params))
|
||||
|
||||
const PatProc = "$1.ClE_0? $1.ClP_0($3$1.ClE_0):(($4)($1.ClP_0))($2)"
|
||||
const PatIter = "$1.ClP_0($3$1.ClE_0)" # we know the env exists
|
||||
template callIter(rp, params: Snippet): Snippet =
|
||||
# we know the env exists
|
||||
let e = dotField(rp, "ClE_0")
|
||||
let p = dotField(rp, "ClP_0")
|
||||
# note `params` here is actually multiple params
|
||||
if params.len == 0:
|
||||
cCall(p, e)
|
||||
else:
|
||||
cCall(p, params, e)
|
||||
|
||||
var op = initLocExpr(p, ri[0])
|
||||
|
||||
@@ -496,20 +546,23 @@ proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
|
||||
var typ = skipTypes(ri[0].typ, abstractInstOwned)
|
||||
assert(typ.kind == tyProc)
|
||||
|
||||
var pl = newRopeAppender()
|
||||
genParams(p, ri, typ, pl)
|
||||
var params = newBuilder("")
|
||||
var argBuilder = default(CallBuilder) # not initCallBuilder, we just want the params
|
||||
genParams(p, ri, typ, params, argBuilder)
|
||||
|
||||
template genCallPattern {.dirty.} =
|
||||
if tfIterator in typ.flags:
|
||||
lineF(p, cpsStmts, PatIter & ";$n", [rdLoc(op), pl, pl.addComma, rawProc])
|
||||
else:
|
||||
lineF(p, cpsStmts, PatProc & ";$n", [rdLoc(op), pl, pl.addComma, rawProc])
|
||||
let rp = rdLoc(op)
|
||||
let pars = extract(params)
|
||||
p.s(cpsStmts).addStmt():
|
||||
if tfIterator in typ.flags:
|
||||
p.s(cpsStmts).add(callIter(rp, pars))
|
||||
else:
|
||||
p.s(cpsStmts).add(callProc(rp, pars, rawProc))
|
||||
|
||||
let rawProc = getClosureType(p.module, typ, clHalf)
|
||||
let canRaise = p.config.exc == excGoto and canRaiseDisp(p, ri[0])
|
||||
if typ.returnType != nil:
|
||||
if isInvalidReturnType(p.config, typ):
|
||||
if ri.len > 1: pl.add(", ")
|
||||
# beware of 'result = p(result)'. We may need to allocate a temporary:
|
||||
if d.k in {locTemp, locNone} or not preventNrvo(p, d.lode, le, ri):
|
||||
# Great, we can use 'd':
|
||||
@@ -518,12 +571,14 @@ proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
|
||||
elif d.k notin {locTemp} and not hasNoInit(ri):
|
||||
# reset before pass as 'result' var:
|
||||
discard "resetLoc(p, d)"
|
||||
pl.add(addrLoc(p.config, d))
|
||||
params.addArgument(argBuilder):
|
||||
params.add(addrLoc(p.config, d))
|
||||
genCallPattern()
|
||||
if canRaise: raiseExit(p)
|
||||
else:
|
||||
var tmp: TLoc = getTemp(p, typ.returnType, needsInit=true)
|
||||
pl.add(addrLoc(p.config, tmp))
|
||||
params.addArgument(argBuilder):
|
||||
params.add(addrLoc(p.config, tmp))
|
||||
genCallPattern()
|
||||
if canRaise: raiseExit(p)
|
||||
genAssignment(p, d, tmp, {}) # no need for deep copying
|
||||
@@ -531,20 +586,24 @@ proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
|
||||
if d.k == locNone: d = getTemp(p, typ.returnType)
|
||||
assert(d.t != nil) # generate an assignment to d:
|
||||
var list: TLoc = initLoc(locCall, d.lode, OnUnknown)
|
||||
let rp = rdLoc(op)
|
||||
let pars = extract(params)
|
||||
if tfIterator in typ.flags:
|
||||
list.snippet = PatIter % [rdLoc(op), pl, pl.addComma, rawProc]
|
||||
list.snippet = callIter(rp, pars)
|
||||
else:
|
||||
list.snippet = PatProc % [rdLoc(op), pl, pl.addComma, rawProc]
|
||||
list.snippet = callProc(rp, pars, rawProc)
|
||||
genAssignment(p, d, list, {}) # no need for deep copying
|
||||
if canRaise: raiseExit(p)
|
||||
else:
|
||||
var tmp: TLoc = getTemp(p, typ.returnType)
|
||||
assert(d.t != nil) # generate an assignment to d:
|
||||
var list: TLoc = initLoc(locCall, d.lode, OnUnknown)
|
||||
let rp = rdLoc(op)
|
||||
let pars = extract(params)
|
||||
if tfIterator in typ.flags:
|
||||
list.snippet = PatIter % [rdLoc(op), pl, pl.addComma, rawProc]
|
||||
list.snippet = callIter(rp, pars)
|
||||
else:
|
||||
list.snippet = PatProc % [rdLoc(op), pl, pl.addComma, rawProc]
|
||||
list.snippet = callProc(rp, pars, rawProc)
|
||||
genAssignment(p, tmp, list, {})
|
||||
if canRaise: raiseExit(p)
|
||||
genAssignment(p, d, tmp, {})
|
||||
@@ -552,8 +611,8 @@ proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
|
||||
genCallPattern()
|
||||
if canRaise: raiseExit(p)
|
||||
|
||||
proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Rope;
|
||||
argsCounter: var int) =
|
||||
proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Builder;
|
||||
argBuilder: var CallBuilder) =
|
||||
if i < typ.n.len:
|
||||
# 'var T' is 'T&' in C++. This means we ignore the request of
|
||||
# any nkHiddenAddr when it's a 'var T'.
|
||||
@@ -562,20 +621,17 @@ proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Rope;
|
||||
if paramType.typ.isCompileTimeOnly:
|
||||
discard
|
||||
elif paramType.typ.kind in {tyVar} and ri[i].kind == nkHiddenAddr:
|
||||
if argsCounter > 0: result.add ", "
|
||||
genArgNoParam(p, ri[i][0], result)
|
||||
inc argsCounter
|
||||
result.addArgument(argBuilder):
|
||||
genArgNoParam(p, ri[i][0], result)
|
||||
else:
|
||||
if argsCounter > 0: result.add ", "
|
||||
genArgNoParam(p, ri[i], result) #, typ.n[i].sym)
|
||||
inc argsCounter
|
||||
result.addArgument(argBuilder):
|
||||
genArgNoParam(p, ri[i], result) #, typ.n[i].sym)
|
||||
else:
|
||||
if tfVarargs notin typ.flags:
|
||||
localError(p.config, ri.info, "wrong argument count")
|
||||
else:
|
||||
if argsCounter > 0: result.add ", "
|
||||
genArgNoParam(p, ri[i], result)
|
||||
inc argsCounter
|
||||
result.addArgument(argBuilder):
|
||||
genArgNoParam(p, ri[i], result)
|
||||
|
||||
discard """
|
||||
Dot call syntax in C++
|
||||
@@ -632,7 +688,7 @@ proc skipAddrDeref(node: PNode): PNode =
|
||||
else:
|
||||
result = node
|
||||
|
||||
proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Rope) =
|
||||
proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Builder) =
|
||||
# for better or worse c2nim translates the 'this' argument to a 'var T'.
|
||||
# However manual wrappers may also use 'ptr T'. In any case we support both
|
||||
# for convenience.
|
||||
@@ -667,15 +723,15 @@ proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Rope) =
|
||||
genArgNoParam(p, ri, result) #, typ.n[i].sym)
|
||||
result.add(".")
|
||||
|
||||
proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType; result: var Rope) =
|
||||
proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType; result: var Builder) =
|
||||
var i = 0
|
||||
var j = 1
|
||||
while i < pat.len:
|
||||
case pat[i]
|
||||
of '@':
|
||||
var argsCounter = 0
|
||||
var callBuilder = default(CallBuilder) # not init call builder
|
||||
for k in j..<ri.len:
|
||||
genOtherArg(p, ri, k, typ, result, argsCounter)
|
||||
genOtherArg(p, ri, k, typ, result, callBuilder)
|
||||
inc i
|
||||
of '#':
|
||||
if i+1 < pat.len and pat[i+1] in {'+', '@'}:
|
||||
@@ -685,11 +741,11 @@ proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType; result: var Ro
|
||||
if pat[i+1] == '+': genArgNoParam(p, ri[0], result)
|
||||
result.add("(")
|
||||
if 1 < ri.len:
|
||||
var argsCounterB = 0
|
||||
genOtherArg(p, ri, 1, typ, result, argsCounterB)
|
||||
var callBuilder: CallBuilder = default(CallBuilder)
|
||||
genOtherArg(p, ri, 1, typ, result, callBuilder)
|
||||
for k in j+1..<ri.len:
|
||||
var argsCounterB = 0
|
||||
genOtherArg(p, ri, k, typ, result, argsCounterB)
|
||||
var callBuilder: CallBuilder = default(CallBuilder)
|
||||
genOtherArg(p, ri, k, typ, result, callBuilder)
|
||||
result.add(")")
|
||||
else:
|
||||
localError(p.config, ri.info, "call expression expected for C++ pattern")
|
||||
@@ -703,15 +759,15 @@ proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType; result: var Ro
|
||||
genArgNoParam(p, arg, result)
|
||||
#result.add debugTree(arg, 0, 10)
|
||||
else:
|
||||
var argsCounter = 0
|
||||
genOtherArg(p, ri, j, typ, result, argsCounter)
|
||||
var callBuilder = default(CallBuilder) # not init call builder
|
||||
genOtherArg(p, ri, j, typ, result, callBuilder)
|
||||
inc j
|
||||
inc i
|
||||
of '\'':
|
||||
var idx, stars: int = 0
|
||||
if scanCppGenericSlot(pat, i, idx, stars):
|
||||
var t = resolveStarsInCppType(typ, idx, stars)
|
||||
if t == nil: result.add("void")
|
||||
if t == nil: result.add(CVoid)
|
||||
else: result.add(getTypeDesc(p.module, t))
|
||||
else:
|
||||
let start = i
|
||||
@@ -730,7 +786,7 @@ proc genInfixCall(p: BProc, le, ri: PNode, d: var TLoc) =
|
||||
let pat = $ri[0].sym.loc.snippet
|
||||
internalAssert p.config, pat.len > 0
|
||||
if pat.contains({'#', '(', '@', '\''}):
|
||||
var pl = newRopeAppender()
|
||||
var pl = newBuilder("")
|
||||
genPatternCall(p, ri, pat, typ, pl)
|
||||
# simpler version of 'fixupCall' that works with the pl+params combination:
|
||||
var typ = skipTypes(ri[0].typ, abstractInst)
|
||||
@@ -740,32 +796,32 @@ proc genInfixCall(p: BProc, le, ri: PNode, d: var TLoc) =
|
||||
# with them to prevent undefined behaviour and because the codegen
|
||||
# is free to emit expressions multiple times!
|
||||
d.k = locCall
|
||||
d.snippet = pl
|
||||
d.snippet = extract(pl)
|
||||
excl d.flags, lfSingleUse
|
||||
else:
|
||||
if d.k == locNone: d = getTemp(p, typ.returnType)
|
||||
assert(d.t != nil) # generate an assignment to d:
|
||||
var list: TLoc = initLoc(locCall, d.lode, OnUnknown)
|
||||
list.snippet = pl
|
||||
list.snippet = extract(pl)
|
||||
genAssignment(p, d, list, {}) # no need for deep copying
|
||||
else:
|
||||
pl.add(";\n")
|
||||
line(p, cpsStmts, pl)
|
||||
p.s(cpsStmts).addStmt():
|
||||
p.s(cpsStmts).add(extract(pl))
|
||||
else:
|
||||
var pl = newRopeAppender()
|
||||
var argsCounter = 0
|
||||
var pl = newBuilder("")
|
||||
if 1 < ri.len:
|
||||
genThisArg(p, ri, 1, typ, pl)
|
||||
pl.add(op.snippet)
|
||||
var params = newRopeAppender()
|
||||
var res = newBuilder("")
|
||||
var call = initCallBuilder(res, extract(pl))
|
||||
for i in 2..<ri.len:
|
||||
genOtherArg(p, ri, i, typ, params, argsCounter)
|
||||
fixupCall(p, le, ri, d, pl, params)
|
||||
genOtherArg(p, ri, i, typ, res, call)
|
||||
fixupCall(p, le, ri, d, res, call)
|
||||
|
||||
proc genNamedParamCall(p: BProc, ri: PNode, d: var TLoc) =
|
||||
# generates a crappy ObjC call
|
||||
var op = initLocExpr(p, ri[0])
|
||||
var pl = "["
|
||||
var pl = newBuilder("[")
|
||||
# getUniqueType() is too expensive here:
|
||||
var typ = skipTypes(ri[0].typ, abstractInst)
|
||||
assert(typ.kind == tyProc)
|
||||
@@ -807,24 +863,27 @@ proc genNamedParamCall(p: BProc, ri: PNode, d: var TLoc) =
|
||||
if d.k == locNone: d = getTemp(p, typ.returnType, needsInit=true)
|
||||
pl.add("Result: ")
|
||||
pl.add(addrLoc(p.config, d))
|
||||
pl.add("];\n")
|
||||
line(p, cpsStmts, pl)
|
||||
pl.add("]")
|
||||
p.s(cpsStmts).addStmt():
|
||||
p.s(cpsStmts).add(extract(pl))
|
||||
else:
|
||||
var tmp: TLoc = getTemp(p, typ.returnType, needsInit=true)
|
||||
pl.add(addrLoc(p.config, tmp))
|
||||
pl.add("];\n")
|
||||
line(p, cpsStmts, pl)
|
||||
pl.add("]")
|
||||
p.s(cpsStmts).addStmt():
|
||||
p.s(cpsStmts).add(extract(pl))
|
||||
genAssignment(p, d, tmp, {}) # no need for deep copying
|
||||
else:
|
||||
pl.add("]")
|
||||
if d.k == locNone: d = getTemp(p, typ.returnType)
|
||||
assert(d.t != nil) # generate an assignment to d:
|
||||
var list: TLoc = initLoc(locCall, ri, OnUnknown)
|
||||
list.snippet = pl
|
||||
list.snippet = extract(pl)
|
||||
genAssignment(p, d, list, {}) # no need for deep copying
|
||||
else:
|
||||
pl.add("];\n")
|
||||
line(p, cpsStmts, pl)
|
||||
pl.add("]")
|
||||
p.s(cpsStmts).addStmt():
|
||||
p.s(cpsStmts).add(extract(pl))
|
||||
|
||||
proc notYetAlive(n: PNode): bool {.inline.} =
|
||||
let r = getRoot(n)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -36,52 +36,84 @@ proc genStringLiteralDataOnlyV1(m: BModule, s: string; result: var Rope) =
|
||||
cgsym(m, "TGenericSeq")
|
||||
let tmp = getTempName(m)
|
||||
result.add tmp
|
||||
m.s[cfsStrData].addf("STRING_LITERAL($1, $2, $3);$n",
|
||||
[tmp, makeCString(s), rope(s.len)])
|
||||
var res = newBuilder("")
|
||||
res.addVarWithTypeAndInitializer(AlwaysConst, name = tmp):
|
||||
res.addSimpleStruct(m, name = "", baseType = ""):
|
||||
res.addField(name = "Sup", typ = "TGenericSeq")
|
||||
res.addArrayField(name = "data", elementType = NimChar, len = s.len + 1)
|
||||
do:
|
||||
var strInit: StructInitializer
|
||||
res.addStructInitializer(strInit, kind = siOrderedStruct):
|
||||
res.addField(strInit, name = "Sup"):
|
||||
var seqInit: StructInitializer
|
||||
res.addStructInitializer(seqInit, kind = siOrderedStruct):
|
||||
res.addField(seqInit, name = "len"):
|
||||
res.addIntValue(s.len)
|
||||
res.addField(seqInit, name = "reserved"):
|
||||
res.add(cCast(NimInt, cOp(BitOr, NimUint, cCast(NimUint, cIntValue(s.len)), NimStrlitFlag)))
|
||||
res.addField(strInit, name = "data"):
|
||||
res.add(makeCString(s))
|
||||
m.s[cfsStrData].add(extract(res))
|
||||
|
||||
proc genStringLiteralV1(m: BModule; n: PNode; result: var Rope) =
|
||||
proc genStringLiteralV1(m: BModule; n: PNode; result: var Builder) =
|
||||
if s.isNil:
|
||||
appcg(m, result, "((#NimStringDesc*) NIM_NIL)", [])
|
||||
result.add(cCast(ptrType(cgsymValue(m, "NimStringDesc")), NimNil))
|
||||
else:
|
||||
let id = nodeTableTestOrSet(m.dataCache, n, m.labels)
|
||||
var name: string = ""
|
||||
if id == m.labels:
|
||||
# string literal not found in the cache:
|
||||
appcg(m, result, "((#NimStringDesc*) &", [])
|
||||
genStringLiteralDataOnlyV1(m, n.strVal, result)
|
||||
result.add ")"
|
||||
genStringLiteralDataOnlyV1(m, n.strVal, name)
|
||||
else:
|
||||
appcg(m, result, "((#NimStringDesc*) &$1$2)",
|
||||
[m.tmpBase, id])
|
||||
name = m.tmpBase & $id
|
||||
result.add(cCast(ptrType(cgsymValue(m, "NimStringDesc")), cAddr(name)))
|
||||
|
||||
# ------ Version 2: destructor based strings and seqs -----------------------
|
||||
|
||||
proc genStringLiteralDataOnlyV2(m: BModule, s: string; result: Rope; isConst: bool) =
|
||||
m.s[cfsStrData].addf("static $4 struct {$n" &
|
||||
" NI cap; NIM_CHAR data[$2+1];$n" &
|
||||
"} $1 = { $2 | NIM_STRLIT_FLAG, $3 };$n",
|
||||
[result, rope(s.len), makeCString(s),
|
||||
rope(if isConst: "const" else: "")])
|
||||
var res = newBuilder("")
|
||||
res.addVarWithTypeAndInitializer(
|
||||
if isConst: AlwaysConst else: Global,
|
||||
name = result):
|
||||
res.addSimpleStruct(m, name = "", baseType = ""):
|
||||
res.addField(name = "cap", typ = NimInt)
|
||||
res.addArrayField(name = "data", elementType = NimChar, len = s.len + 1)
|
||||
do:
|
||||
var structInit: StructInitializer
|
||||
res.addStructInitializer(structInit, kind = siOrderedStruct):
|
||||
res.addField(structInit, name = "cap"):
|
||||
res.add(cOp(BitOr, NimInt, cIntValue(s.len), NimStrlitFlag))
|
||||
res.addField(structInit, name = "data"):
|
||||
res.add(makeCString(s))
|
||||
m.s[cfsStrData].add(extract(res))
|
||||
|
||||
proc genStringLiteralV2(m: BModule; n: PNode; isConst: bool; result: var Rope) =
|
||||
proc genStringLiteralV2(m: BModule; n: PNode; isConst: bool; result: var Builder) =
|
||||
let id = nodeTableTestOrSet(m.dataCache, n, m.labels)
|
||||
var litName: string
|
||||
if id == m.labels:
|
||||
let pureLit = getTempName(m)
|
||||
genStringLiteralDataOnlyV2(m, n.strVal, pureLit, isConst)
|
||||
let tmp = getTempName(m)
|
||||
result.add tmp
|
||||
cgsym(m, "NimStrPayload")
|
||||
cgsym(m, "NimStringV2")
|
||||
# string literal not found in the cache:
|
||||
m.s[cfsStrData].addf("static $4 NimStringV2 $1 = {$2, (NimStrPayload*)&$3};$n",
|
||||
[tmp, rope(n.strVal.len), pureLit, rope(if isConst: "const" else: "")])
|
||||
litName = getTempName(m)
|
||||
genStringLiteralDataOnlyV2(m, n.strVal, litName, isConst)
|
||||
else:
|
||||
let tmp = getTempName(m)
|
||||
result.add tmp
|
||||
m.s[cfsStrData].addf("static $4 NimStringV2 $1 = {$2, (NimStrPayload*)&$3};$n",
|
||||
[tmp, rope(n.strVal.len), m.tmpBase & rope(id),
|
||||
rope(if isConst: "const" else: "")])
|
||||
litName = m.tmpBase & $id
|
||||
let tmp = getTempName(m)
|
||||
result.add tmp
|
||||
var res = newBuilder("")
|
||||
res.addVarWithInitializer(
|
||||
if isConst: AlwaysConst else: Global,
|
||||
name = tmp,
|
||||
typ = "NimStringV2"):
|
||||
var strInit: StructInitializer
|
||||
res.addStructInitializer(strInit, kind = siOrderedStruct):
|
||||
res.addField(strInit, name = "len"):
|
||||
res.addIntValue(n.strVal.len)
|
||||
res.addField(strInit, name = "p"):
|
||||
res.add(cCast(ptrType("NimStrPayload"), cAddr(litName)))
|
||||
m.s[cfsStrData].add(extract(res))
|
||||
|
||||
proc genStringLiteralV2Const(m: BModule; n: PNode; isConst: bool; result: var Rope) =
|
||||
proc genStringLiteralV2Const(m: BModule; n: PNode; isConst: bool; result: var Builder) =
|
||||
let id = nodeTableTestOrSet(m.dataCache, n, m.labels)
|
||||
var pureLit: Rope
|
||||
if id == m.labels:
|
||||
@@ -92,7 +124,12 @@ proc genStringLiteralV2Const(m: BModule; n: PNode; isConst: bool; result: var Ro
|
||||
genStringLiteralDataOnlyV2(m, n.strVal, pureLit, isConst)
|
||||
else:
|
||||
pureLit = m.tmpBase & rope(id)
|
||||
result.addf "{$1, (NimStrPayload*)&$2}", [rope(n.strVal.len), pureLit]
|
||||
var strInit: StructInitializer
|
||||
result.addStructInitializer(strInit, kind = siOrderedStruct):
|
||||
result.addField(strInit, name = "len"):
|
||||
result.addIntValue(n.strVal.len)
|
||||
result.addField(strInit, name = "p"):
|
||||
result.add(cCast(ptrType("NimStrPayload"), cAddr(pureLit)))
|
||||
|
||||
# ------ Version selector ---------------------------------------------------
|
||||
|
||||
@@ -107,10 +144,10 @@ proc genStringLiteralDataOnly(m: BModule; s: string; info: TLineInfo;
|
||||
else:
|
||||
localError(m.config, info, "cannot determine how to produce code for string literal")
|
||||
|
||||
proc genNilStringLiteral(m: BModule; info: TLineInfo; result: var Rope) =
|
||||
appcg(m, result, "((#NimStringDesc*) NIM_NIL)", [])
|
||||
proc genNilStringLiteral(m: BModule; info: TLineInfo; result: var Builder) =
|
||||
result.add(cCast(ptrType(cgsymValue(m, "NimStringDesc")), NimNil))
|
||||
|
||||
proc genStringLiteral(m: BModule; n: PNode; result: var Rope) =
|
||||
proc genStringLiteral(m: BModule; n: PNode; result: var Builder) =
|
||||
case detectStrVersion(m)
|
||||
of 0, 1: genStringLiteralV1(m, n, result)
|
||||
of 2: genStringLiteralV2(m, n, isConst = true, result)
|
||||
|
||||
@@ -27,25 +27,28 @@ proc specializeResetN(p: BProc, accessor: Rope, n: PNode;
|
||||
if disc.loc.snippet == "": fillObjectFields(p.module, typ)
|
||||
if disc.loc.t == nil:
|
||||
internalError(p.config, n.info, "specializeResetN()")
|
||||
lineF(p, cpsStmts, "switch ($1.$2) {$n", [accessor, disc.loc.snippet])
|
||||
for i in 1..<n.len:
|
||||
let branch = n[i]
|
||||
assert branch.kind in {nkOfBranch, nkElse}
|
||||
if branch.kind == nkOfBranch:
|
||||
genCaseRange(p, branch)
|
||||
else:
|
||||
lineF(p, cpsStmts, "default:$n", [])
|
||||
specializeResetN(p, accessor, lastSon(branch), typ)
|
||||
lineF(p, cpsStmts, "break;$n", [])
|
||||
lineF(p, cpsStmts, "} $n", [])
|
||||
specializeResetT(p, "$1.$2" % [accessor, disc.loc.snippet], disc.loc.t)
|
||||
let discField = dotField(accessor, disc.loc.snippet)
|
||||
p.s(cpsStmts).addSwitchStmt(discField):
|
||||
for i in 1..<n.len:
|
||||
let branch = n[i]
|
||||
assert branch.kind in {nkOfBranch, nkElse}
|
||||
var caseBuilder: SwitchCaseBuilder
|
||||
p.s(cpsStmts).addSwitchCase(caseBuilder):
|
||||
if branch.kind == nkOfBranch:
|
||||
genCaseRange(p, branch, caseBuilder)
|
||||
else:
|
||||
p.s(cpsStmts).addCaseElse(caseBuilder)
|
||||
do:
|
||||
specializeResetN(p, accessor, lastSon(branch), typ)
|
||||
p.s(cpsStmts).addBreak()
|
||||
specializeResetT(p, discField, disc.loc.t)
|
||||
of nkSym:
|
||||
let field = n.sym
|
||||
if field.typ.kind == tyVoid: return
|
||||
if field.loc.snippet == "": fillObjectFields(p.module, typ)
|
||||
if field.loc.t == nil:
|
||||
internalError(p.config, n.info, "specializeResetN()")
|
||||
specializeResetT(p, "$1.$2" % [accessor, field.loc.snippet], field.loc.t)
|
||||
specializeResetT(p, dotField(accessor, field.loc.snippet), field.loc.t)
|
||||
else: internalError(p.config, n.info, "specializeResetN()")
|
||||
|
||||
proc specializeResetT(p: BProc, accessor: Rope, typ: PType) =
|
||||
@@ -58,10 +61,8 @@ proc specializeResetT(p: BProc, accessor: Rope, typ: PType) =
|
||||
of tyArray:
|
||||
let arraySize = lengthOrd(p.config, typ.indexType)
|
||||
var i: TLoc = getTemp(p, getSysType(p.module.g.graph, unknownLineInfo, tyInt))
|
||||
linefmt(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n",
|
||||
[i.snippet, arraySize])
|
||||
specializeResetT(p, ropecg(p.module, "$1[$2]", [accessor, i.snippet]), typ.elementType)
|
||||
lineF(p, cpsStmts, "}$n", [])
|
||||
p.s(cpsStmts).addForRangeExclusive(i.snippet, cIntValue(0), cIntValue(arraySize)):
|
||||
specializeResetT(p, subscript(accessor, i.snippet), typ.elementType)
|
||||
of tyObject:
|
||||
var x = typ.baseClass
|
||||
if x != nil: x = x.skipTypes(skipPtrs)
|
||||
@@ -70,28 +71,34 @@ proc specializeResetT(p: BProc, accessor: Rope, typ: PType) =
|
||||
of tyTuple:
|
||||
let typ = getUniqueType(typ)
|
||||
for i, a in typ.ikids:
|
||||
specializeResetT(p, ropecg(p.module, "$1.Field$2", [accessor, i]), a)
|
||||
specializeResetT(p, dotField(accessor, "Field" & $i), a)
|
||||
|
||||
of tyString, tyRef, tySequence:
|
||||
lineCg(p, cpsStmts, "#unsureAsgnRef((void**)&$1, NIM_NIL);$n", [accessor])
|
||||
p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "unsureAsgnRef"),
|
||||
cCast(ptrType(CPointer), cAddr(accessor)),
|
||||
NimNil)
|
||||
|
||||
of tyProc:
|
||||
if typ.callConv == ccClosure:
|
||||
lineCg(p, cpsStmts, "#unsureAsgnRef((void**)&$1.ClE_0, NIM_NIL);$n", [accessor])
|
||||
lineCg(p, cpsStmts, "$1.ClP_0 = NIM_NIL;$n", [accessor])
|
||||
p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "unsureAsgnRef"),
|
||||
cCast(ptrType(CPointer), cAddr(dotField(accessor, "ClE_0"))),
|
||||
NimNil)
|
||||
p.s(cpsStmts).addFieldAssignment(accessor, "ClP_0", NimNil)
|
||||
else:
|
||||
lineCg(p, cpsStmts, "$1 = NIM_NIL;$n", [accessor])
|
||||
p.s(cpsStmts).addAssignment(accessor, NimNil)
|
||||
of tyChar, tyBool, tyEnum, tyRange, tyInt..tyUInt64:
|
||||
lineCg(p, cpsStmts, "$1 = 0;$n", [accessor])
|
||||
p.s(cpsStmts).addAssignment(accessor, cIntValue(0))
|
||||
of tyCstring, tyPointer, tyPtr, tyVar, tyLent:
|
||||
lineCg(p, cpsStmts, "$1 = NIM_NIL;$n", [accessor])
|
||||
p.s(cpsStmts).addAssignment(accessor, NimNil)
|
||||
of tySet:
|
||||
case mapSetType(p.config, typ)
|
||||
of ctArray:
|
||||
lineCg(p, cpsStmts, "#nimZeroMem($1, sizeof($2));$n",
|
||||
[accessor, getTypeDesc(p.module, typ)])
|
||||
let t = getTypeDesc(p.module, typ)
|
||||
p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimZeroMem"),
|
||||
accessor,
|
||||
cSizeof(t))
|
||||
of ctInt8, ctInt16, ctInt32, ctInt64:
|
||||
lineCg(p, cpsStmts, "$1 = 0;$n", [accessor])
|
||||
p.s(cpsStmts).addAssignment(accessor, cIntValue(0))
|
||||
else:
|
||||
raiseAssert "unexpected set type kind"
|
||||
of tyNone, tyEmpty, tyNil, tyUntyped, tyTyped, tyGenericInvocation,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -19,9 +19,12 @@ proc accessThreadLocalVar(p: BProc, s: PSym) =
|
||||
if emulatedThreadVars(p.config) and threadVarAccessed notin p.flags:
|
||||
p.flags.incl threadVarAccessed
|
||||
incl p.module.flags, usesThreadVars
|
||||
p.procSec(cpsLocals).addf("\tNimThreadVars* NimTV_;$n", [])
|
||||
p.procSec(cpsInit).add(
|
||||
ropecg(p.module, "\tNimTV_ = (NimThreadVars*) #GetThreadLocalVars();$n", []))
|
||||
p.procSec(cpsLocals).addVar(kind = Local,
|
||||
name = "NimTV_",
|
||||
typ = ptrType("NimThreadVars"))
|
||||
p.procSec(cpsInit).addAssignment("NimTV_",
|
||||
cCast(ptrType("NimThreadVars"),
|
||||
cCall(cgsymValue(p.module, "GetThreadLocalVars"))))
|
||||
|
||||
proc declareThreadVar(m: BModule, s: PSym, isExtern: bool) =
|
||||
if emulatedThreadVars(m.config):
|
||||
@@ -30,30 +33,32 @@ proc declareThreadVar(m: BModule, s: PSym, isExtern: bool) =
|
||||
# allocator for it :-(
|
||||
if not containsOrIncl(m.g.nimtvDeclared, s.id):
|
||||
m.g.nimtvDeps.add(s.loc.t)
|
||||
m.g.nimtv.addf("$1 $2;$n", [getTypeDesc(m, s.loc.t), s.loc.snippet])
|
||||
m.g.nimtv.addField(name = s.loc.snippet, typ = getTypeDesc(m, s.loc.t))
|
||||
else:
|
||||
if isExtern: m.s[cfsVars].add("extern ")
|
||||
elif lfExportLib in s.loc.flags: m.s[cfsVars].add("N_LIB_EXPORT_VAR ")
|
||||
else: m.s[cfsVars].add("N_LIB_PRIVATE ")
|
||||
if optThreads in m.config.globalOptions:
|
||||
let sym = s.typ.sym
|
||||
if sym != nil and sfCppNonPod in sym.flags:
|
||||
m.s[cfsVars].add("NIM_THREAD_LOCAL ")
|
||||
else: m.s[cfsVars].add("NIM_THREADVAR ")
|
||||
m.s[cfsVars].add(getTypeDesc(m, s.loc.t))
|
||||
m.s[cfsVars].addf(" $1;$n", [s.loc.snippet])
|
||||
let vis =
|
||||
if isExtern: Extern
|
||||
elif lfExportLib in s.loc.flags: ExportLibVar
|
||||
else: Private
|
||||
m.s[cfsVars].addVar(m, s,
|
||||
name = s.loc.snippet,
|
||||
typ = getTypeDesc(m, s.loc.t),
|
||||
kind = Threadvar,
|
||||
visibility = vis)
|
||||
|
||||
proc generateThreadLocalStorage(m: BModule) =
|
||||
if m.g.nimtv != "" and (usesThreadVars in m.flags or sfMainModule in m.module.flags):
|
||||
if m.g.nimtv.buf.len != 0 and (usesThreadVars in m.flags or sfMainModule in m.module.flags):
|
||||
for t in items(m.g.nimtvDeps): discard getTypeDesc(m, t)
|
||||
finishTypeDescriptions(m)
|
||||
m.s[cfsSeqTypes].addf("typedef struct {$1} NimThreadVars;$n", [m.g.nimtv])
|
||||
m.s[cfsSeqTypes].addTypedef(name = "NimThreadVars"):
|
||||
m.s[cfsSeqTypes].addSimpleStruct(m, name = "", baseType = ""):
|
||||
m.s[cfsSeqTypes].add(extract(m.g.nimtv))
|
||||
|
||||
proc generateThreadVarsSize(m: BModule) =
|
||||
if m.g.nimtv != "":
|
||||
if m.g.nimtv.buf.len != 0:
|
||||
let externc = if m.config.backend == backendCpp or
|
||||
sfCompileToCpp in m.module.flags: "extern \"C\" "
|
||||
else: ""
|
||||
m.s[cfsProcs].addf(
|
||||
"$#NI NimThreadVarsSize(){return (NI)sizeof(NimThreadVars);}$n",
|
||||
[externc.rope])
|
||||
sfCompileToCpp in m.module.flags: ExternC
|
||||
else: None
|
||||
m.s[cfsProcs].addDeclWithVisibility(externc):
|
||||
m.s[cfsProcs].addProcHeader("NimThreadVarsSize", NimInt, cProcParams())
|
||||
m.s[cfsProcs].finishProcHeaderWithBody():
|
||||
m.s[cfsProcs].addReturn(cCast(NimInt, cSizeof("NimThreadVars")))
|
||||
|
||||
@@ -16,13 +16,16 @@ type
|
||||
p: BProc
|
||||
visitorFrmt: string
|
||||
|
||||
const
|
||||
visitorFrmt = "#nimGCvisit((void*)$1, $2);$n"
|
||||
|
||||
proc genTraverseProc(c: TTraversalClosure, accessor: Rope, typ: PType)
|
||||
proc genCaseRange(p: BProc, branch: PNode)
|
||||
proc genCaseRange(p: BProc, branch: PNode, info: var SwitchCaseBuilder)
|
||||
proc getTemp(p: BProc, t: PType, needsInit=false): TLoc
|
||||
|
||||
proc visit(p: BProc, data, visitor: Snippet) =
|
||||
p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimGCvisit"),
|
||||
cCast(CPointer, data),
|
||||
visitor)
|
||||
|
||||
proc genTraverseProc(c: TTraversalClosure, accessor: Rope, n: PNode;
|
||||
typ: PType) =
|
||||
if n == nil: return
|
||||
@@ -37,29 +40,32 @@ proc genTraverseProc(c: TTraversalClosure, accessor: Rope, n: PNode;
|
||||
if disc.loc.snippet == "": fillObjectFields(c.p.module, typ)
|
||||
if disc.loc.t == nil:
|
||||
internalError(c.p.config, n.info, "genTraverseProc()")
|
||||
lineF(p, cpsStmts, "switch ($1.$2) {$n", [accessor, disc.loc.snippet])
|
||||
for i in 1..<n.len:
|
||||
let branch = n[i]
|
||||
assert branch.kind in {nkOfBranch, nkElse}
|
||||
if branch.kind == nkOfBranch:
|
||||
genCaseRange(c.p, branch)
|
||||
else:
|
||||
lineF(p, cpsStmts, "default:$n", [])
|
||||
genTraverseProc(c, accessor, lastSon(branch), typ)
|
||||
lineF(p, cpsStmts, "break;$n", [])
|
||||
lineF(p, cpsStmts, "} $n", [])
|
||||
let discField = dotField(accessor, disc.loc.snippet)
|
||||
p.s(cpsStmts).addSwitchStmt(discField):
|
||||
for i in 1..<n.len:
|
||||
let branch = n[i]
|
||||
assert branch.kind in {nkOfBranch, nkElse}
|
||||
var caseBuilder: SwitchCaseBuilder
|
||||
p.s(cpsStmts).addSwitchCase(caseBuilder):
|
||||
if branch.kind == nkOfBranch:
|
||||
genCaseRange(c.p, branch, caseBuilder)
|
||||
else:
|
||||
p.s(cpsStmts).addCaseElse(caseBuilder)
|
||||
do:
|
||||
genTraverseProc(c, accessor, lastSon(branch), typ)
|
||||
p.s(cpsStmts).addBreak()
|
||||
of nkSym:
|
||||
let field = n.sym
|
||||
if field.typ.kind == tyVoid: return
|
||||
if field.loc.snippet == "": fillObjectFields(c.p.module, typ)
|
||||
if field.loc.t == nil:
|
||||
internalError(c.p.config, n.info, "genTraverseProc()")
|
||||
genTraverseProc(c, "$1.$2" % [accessor, field.loc.snippet], field.loc.t)
|
||||
genTraverseProc(c, dotField(accessor, field.loc.snippet), field.loc.t)
|
||||
else: internalError(c.p.config, n.info, "genTraverseProc()")
|
||||
|
||||
proc parentObj(accessor: Rope; m: BModule): Rope {.inline.} =
|
||||
if not m.compileToCpp:
|
||||
result = "$1.Sup" % [accessor]
|
||||
result = dotField(accessor, "Sup")
|
||||
else:
|
||||
result = accessor
|
||||
|
||||
@@ -76,16 +82,14 @@ proc genTraverseProc(c: TTraversalClosure, accessor: Rope, typ: PType) =
|
||||
let arraySize = lengthOrd(c.p.config, typ.indexType)
|
||||
var i: TLoc = getTemp(p, getSysType(c.p.module.g.graph, unknownLineInfo, tyInt))
|
||||
var oldCode = p.s(cpsStmts)
|
||||
freeze oldCode
|
||||
linefmt(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n",
|
||||
[i.snippet, arraySize])
|
||||
let oldLen = p.s(cpsStmts).len
|
||||
genTraverseProc(c, ropecg(c.p.module, "$1[$2]", [accessor, i.snippet]), typ.elementType)
|
||||
if p.s(cpsStmts).len == oldLen:
|
||||
var oldLen, newLen: int
|
||||
p.s(cpsStmts).addForRangeExclusive(i.snippet, cIntValue(0), cIntValue(arraySize)):
|
||||
oldLen = p.s(cpsStmts).buf.len
|
||||
genTraverseProc(c, subscript(accessor, i.snippet), typ.elementType)
|
||||
newLen = p.s(cpsStmts).buf.len
|
||||
if oldLen == newLen:
|
||||
# do not emit dummy long loops for faster debug builds:
|
||||
p.s(cpsStmts) = oldCode
|
||||
else:
|
||||
lineF(p, cpsStmts, "}$n", [])
|
||||
of tyObject:
|
||||
var x = typ.baseClass
|
||||
if x != nil: x = x.skipTypes(skipPtrs)
|
||||
@@ -94,23 +98,25 @@ proc genTraverseProc(c: TTraversalClosure, accessor: Rope, typ: PType) =
|
||||
of tyTuple:
|
||||
let typ = getUniqueType(typ)
|
||||
for i, a in typ.ikids:
|
||||
genTraverseProc(c, ropecg(c.p.module, "$1.Field$2", [accessor, i]), a)
|
||||
genTraverseProc(c, dotField(accessor, "Field" & $i), a)
|
||||
of tyRef:
|
||||
lineCg(p, cpsStmts, visitorFrmt, [accessor, c.visitorFrmt])
|
||||
visit(p, accessor, c.visitorFrmt)
|
||||
of tySequence:
|
||||
if optSeqDestructors notin c.p.module.config.globalOptions:
|
||||
lineCg(p, cpsStmts, visitorFrmt, [accessor, c.visitorFrmt])
|
||||
visit(p, accessor, c.visitorFrmt)
|
||||
elif containsGarbageCollectedRef(typ.elementType):
|
||||
# destructor based seqs are themselves not traced but their data is, if
|
||||
# they contain a GC'ed type:
|
||||
lineCg(p, cpsStmts, "#nimGCvisitSeq((void*)$1, $2);$n", [accessor, c.visitorFrmt])
|
||||
p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimGCvisitSeq"),
|
||||
cCast(CPointer, accessor),
|
||||
c.visitorFrmt)
|
||||
#genTraverseProcSeq(c, accessor, typ)
|
||||
of tyString:
|
||||
if tfHasAsgn notin typ.flags:
|
||||
lineCg(p, cpsStmts, visitorFrmt, [accessor, c.visitorFrmt])
|
||||
visit(p, accessor, c.visitorFrmt)
|
||||
of tyProc:
|
||||
if typ.callConv == ccClosure:
|
||||
lineCg(p, cpsStmts, visitorFrmt, [ropecg(c.p.module, "$1.ClE_0", [accessor]), c.visitorFrmt])
|
||||
visit(p, dotField(accessor, "ClE_0"), c.visitorFrmt)
|
||||
else:
|
||||
discard
|
||||
|
||||
@@ -119,18 +125,17 @@ proc genTraverseProcSeq(c: TTraversalClosure, accessor: Rope, typ: PType) =
|
||||
assert typ.kind == tySequence
|
||||
var i = getTemp(p, getSysType(c.p.module.g.graph, unknownLineInfo, tyInt))
|
||||
var oldCode = p.s(cpsStmts)
|
||||
freeze oldCode
|
||||
var oldLen, newLen: int
|
||||
var a = TLoc(snippet: accessor)
|
||||
let le = lenExpr(c.p, a)
|
||||
|
||||
lineF(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n",
|
||||
[i.snippet, lenExpr(c.p, a)])
|
||||
let oldLen = p.s(cpsStmts).len
|
||||
genTraverseProc(c, "$1$3[$2]" % [accessor, i.snippet, dataField(c.p)], typ.elementType)
|
||||
if p.s(cpsStmts).len == oldLen:
|
||||
p.s(cpsStmts).addForRangeExclusive(i.snippet, cIntValue(0), le):
|
||||
oldLen = p.s(cpsStmts).buf.len
|
||||
genTraverseProc(c, subscript(dataField(c.p, accessor), i.snippet), typ.elementType)
|
||||
newLen = p.s(cpsStmts).buf.len
|
||||
if newLen == oldLen:
|
||||
# do not emit dummy long loops for faster debug builds:
|
||||
p.s(cpsStmts) = oldCode
|
||||
else:
|
||||
lineF(p, cpsStmts, "}$n", [])
|
||||
|
||||
proc genTraverseProc(m: BModule, origTyp: PType; sig: SigHash): Rope =
|
||||
var p = newProc(nil, m)
|
||||
@@ -139,11 +144,10 @@ proc genTraverseProc(m: BModule, origTyp: PType; sig: SigHash): Rope =
|
||||
hcrOn = m.hcrOn
|
||||
typ = origTyp.skipTypes(abstractInstOwned)
|
||||
markerName = if hcrOn: result & "_actual" else: result
|
||||
header = "static N_NIMCALL(void, $1)(void* p, NI op)" % [markerName]
|
||||
t = getTypeDesc(m, typ)
|
||||
|
||||
lineF(p, cpsLocals, "$1 a;$n", [t])
|
||||
lineF(p, cpsInit, "a = ($1)p;$n", [t])
|
||||
p.s(cpsLocals).addVar(kind = Local, name = "a", typ = t)
|
||||
p.s(cpsInit).addAssignment("a", cCast(t, "p"))
|
||||
|
||||
var c = TTraversalClosure(p: p,
|
||||
visitorFrmt: "op" # "#nimGCvisit((void*)$1, op);$n"
|
||||
@@ -157,18 +161,40 @@ proc genTraverseProc(m: BModule, origTyp: PType; sig: SigHash): Rope =
|
||||
# C's arrays are broken beyond repair:
|
||||
genTraverseProc(c, "a".rope, typ.elementType)
|
||||
else:
|
||||
genTraverseProc(c, "(*a)".rope, typ.elementType)
|
||||
genTraverseProc(c, cDeref("a"), typ.elementType)
|
||||
|
||||
let generatedProc = "$1 {$n$2$3$4}\n" %
|
||||
[header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts)]
|
||||
var headerBuilder = newBuilder("")
|
||||
headerBuilder.addProcHeaderWithParams(ccNimCall, markerName, CVoid):
|
||||
var paramBuilder: ProcParamBuilder
|
||||
headerBuilder.addProcParams(paramBuilder):
|
||||
headerBuilder.addParam(paramBuilder, name = "p", typ = CPointer)
|
||||
headerBuilder.addParam(paramBuilder, name = "op", typ = NimInt)
|
||||
let header = extract(headerBuilder)
|
||||
|
||||
m.s[cfsProcHeaders].addf("$1;\n", [header])
|
||||
m.s[cfsProcs].add(generatedProc)
|
||||
m.s[cfsProcHeaders].addDeclWithVisibility(StaticProc):
|
||||
m.s[cfsProcHeaders].add(header)
|
||||
m.s[cfsProcHeaders].finishProcHeaderAsProto()
|
||||
m.s[cfsProcs].addDeclWithVisibility(StaticProc):
|
||||
m.s[cfsProcs].add(header)
|
||||
m.s[cfsProcs].finishProcHeaderWithBody():
|
||||
m.s[cfsProcs].add(extract(p.s(cpsLocals)))
|
||||
m.s[cfsProcs].add(extract(p.s(cpsInit)))
|
||||
m.s[cfsProcs].add(extract(p.s(cpsStmts)))
|
||||
|
||||
if hcrOn:
|
||||
m.s[cfsProcHeaders].addf("N_NIMCALL_PTR(void, $1)(void*, NI);\n", [result])
|
||||
m.s[cfsDynLibInit].addf("\t$1 = (N_NIMCALL_PTR(void, )(void*, NI)) hcrRegisterProc($3, \"$1\", (void*)$2);\n",
|
||||
[result, markerName, getModuleDllPath(m)])
|
||||
var desc = newBuilder("")
|
||||
var unnamedParamBuilder: ProcParamBuilder
|
||||
desc.addProcParams(unnamedParamBuilder):
|
||||
desc.addUnnamedParam(unnamedParamBuilder, CPointer)
|
||||
desc.addUnnamedParam(unnamedParamBuilder, NimInt)
|
||||
let unnamedParams = extract(desc)
|
||||
m.s[cfsProcHeaders].addProcVar(ccNimCall, result, unnamedParams, CVoid)
|
||||
m.s[cfsDynLibInit].addAssignmentWithValue(result):
|
||||
m.s[cfsDynLibInit].addCast(procPtrTypeUnnamed(ccNimCall, CVoid, unnamedParams)):
|
||||
m.s[cfsDynLibInit].addCall("hcrRegisterProc",
|
||||
getModuleDllPath(m),
|
||||
'"' & result & '"',
|
||||
cCast(CPointer, markerName))
|
||||
|
||||
proc genTraverseProcForGlobal(m: BModule, s: PSym; info: TLineInfo): Rope =
|
||||
discard genTypeInfoV1(m, s.loc.t, info)
|
||||
@@ -179,17 +205,28 @@ proc genTraverseProcForGlobal(m: BModule, s: PSym; info: TLineInfo): Rope =
|
||||
|
||||
if sfThread in s.flags and emulatedThreadVars(m.config):
|
||||
accessThreadLocalVar(p, s)
|
||||
sLoc = "NimTV_->" & sLoc
|
||||
sLoc = derefField("NimTV_", sLoc)
|
||||
|
||||
var c = TTraversalClosure(p: p,
|
||||
visitorFrmt: "0" # "#nimGCvisit((void*)$1, 0);$n"
|
||||
visitorFrmt: cIntValue(0) # "#nimGCvisit((void*)$1, 0);$n"
|
||||
)
|
||||
|
||||
let header = "static N_NIMCALL(void, $1)(void)" % [result]
|
||||
genTraverseProc(c, sLoc, s.loc.t)
|
||||
|
||||
let generatedProc = "$1 {$n$2$3$4}$n" %
|
||||
[header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts)]
|
||||
var headerBuilder = newBuilder("")
|
||||
headerBuilder.addProcHeaderWithParams(ccNimCall, result, CVoid):
|
||||
var paramBuilder: ProcParamBuilder
|
||||
headerBuilder.addProcParams(paramBuilder):
|
||||
# (void)
|
||||
discard
|
||||
let header = extract(headerBuilder)
|
||||
|
||||
m.s[cfsProcHeaders].addf("$1;$n", [header])
|
||||
m.s[cfsProcs].add(generatedProc)
|
||||
m.s[cfsProcHeaders].addDeclWithVisibility(StaticProc):
|
||||
m.s[cfsProcHeaders].add(header)
|
||||
m.s[cfsProcHeaders].finishProcHeaderAsProto()
|
||||
m.s[cfsProcs].addDeclWithVisibility(StaticProc):
|
||||
m.s[cfsProcs].add(header)
|
||||
m.s[cfsProcs].finishProcHeaderWithBody():
|
||||
m.s[cfsProcs].add(extract(p.s(cpsLocals)))
|
||||
m.s[cfsProcs].add(extract(p.s(cpsInit)))
|
||||
m.s[cfsProcs].add(extract(p.s(cpsStmts)))
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
1407
compiler/cgen.nim
1407
compiler/cgen.nim
File diff suppressed because it is too large
Load Diff
@@ -11,7 +11,7 @@
|
||||
|
||||
import
|
||||
ast, ropes, options,
|
||||
lineinfos, pathutils, modulegraphs
|
||||
lineinfos, pathutils, modulegraphs, cbuilderbase
|
||||
|
||||
import std/[intsets, tables, sets]
|
||||
|
||||
@@ -43,12 +43,12 @@ type
|
||||
ctUInt, ctUInt8, ctUInt16, ctUInt32, ctUInt64,
|
||||
ctArray, ctPtrToArray, ctStruct, ctPtr, ctNimStr, ctNimSeq, ctProc,
|
||||
ctCString
|
||||
TCFileSections* = array[TCFileSection, Rope] # represents a generated C file
|
||||
TCFileSections* = array[TCFileSection, Builder] # represents a generated C file
|
||||
TCProcSection* = enum # the sections a generated C proc consists of
|
||||
cpsLocals, # section of local variables for C proc
|
||||
cpsInit, # section for init of variables for C proc
|
||||
cpsStmts # section of local statements for C proc
|
||||
TCProcSections* = array[TCProcSection, Rope] # represents a generated C proc
|
||||
TCProcSections* = array[TCProcSection, Builder] # represents a generated C proc
|
||||
BModule* = ref TCGen
|
||||
BProc* = ref TCProc
|
||||
TBlock* = object
|
||||
@@ -115,7 +115,7 @@ type
|
||||
# computing alive data on our own.
|
||||
|
||||
BModuleList* = ref object of RootObj
|
||||
mainModProcs*, mainModInit*, otherModsInit*, mainDatInit*: Rope
|
||||
mainModProcs*, mainModInit*, otherModsInit*, mainDatInit*: Builder
|
||||
mapping*: Rope # the generated mapping file (if requested)
|
||||
modules*: seq[BModule] # list of all compiled modules
|
||||
modulesClosed*: seq[BModule] # list of the same compiled modules, but in the order they were closed
|
||||
@@ -127,7 +127,7 @@ type
|
||||
graph*: ModuleGraph
|
||||
strVersion*, seqVersion*: int # version of the string/seq implementation to use
|
||||
|
||||
nimtv*: Rope # Nim thread vars; the struct body
|
||||
nimtv*: Builder # Nim thread vars; the struct body
|
||||
nimtvDeps*: seq[PType] # type deps: every module needs whole struct
|
||||
nimtvDeclared*: IntSet # so that every var/field exists only once
|
||||
# in the struct
|
||||
@@ -161,14 +161,15 @@ type
|
||||
typeInfoMarkerV2*: TypeCache
|
||||
initProc*: BProc # code for init procedure
|
||||
preInitProc*: BProc # code executed before the init proc
|
||||
hcrCreateTypeInfosProc*: Rope # type info globals are in here when HCR=on
|
||||
hcrCreateTypeInfosProc*: Builder # type info globals are in here when HCR=on
|
||||
inHcrInitGuard*: bool # We are currently within a HCR reloading guard.
|
||||
hcrInitGuard*: IfBuilder
|
||||
typeStack*: TTypeSeq # used for type generation
|
||||
dataCache*: TNodeTable
|
||||
typeNodes*, nimTypes*: int # used for type info generation
|
||||
typeNodesName*, nimTypesName*: Rope # used for type info generation
|
||||
labels*: Natural # for generating unique module-scope names
|
||||
extensionLoaders*: array['0'..'9', Rope] # special procs for the
|
||||
extensionLoaders*: array['0'..'9', Builder] # special procs for the
|
||||
# OpenGL wrapper
|
||||
sigConflicts*: CountTable[SigHash]
|
||||
g*: BModuleList
|
||||
@@ -181,18 +182,18 @@ proc includeHeader*(this: BModule; header: string) =
|
||||
if not this.headerFiles.contains header:
|
||||
this.headerFiles.add header
|
||||
|
||||
proc s*(p: BProc, s: TCProcSection): var Rope {.inline.} =
|
||||
proc s*(p: BProc, s: TCProcSection): var Builder {.inline.} =
|
||||
# section in the current block
|
||||
result = p.blocks[^1].sections[s]
|
||||
|
||||
proc procSec*(p: BProc, s: TCProcSection): var Rope {.inline.} =
|
||||
proc procSec*(p: BProc, s: TCProcSection): var Builder {.inline.} =
|
||||
# top level proc sections
|
||||
result = p.blocks[0].sections[s]
|
||||
|
||||
proc initBlock*(): TBlock =
|
||||
result = TBlock()
|
||||
for i in low(result.sections)..high(result.sections):
|
||||
result.sections[i] = newRopeAppender()
|
||||
result.sections[i] = newBuilder("")
|
||||
|
||||
proc newProc*(prc: PSym, module: BModule): BProc =
|
||||
result = BProc(
|
||||
|
||||
@@ -159,7 +159,7 @@ proc initDefines*(symbols: StringTableRef) =
|
||||
defineSymbol("nimHasEnsureMove")
|
||||
defineSymbol("nimHasNoReturnError")
|
||||
|
||||
defineSymbol("nimUseStrictDefs")
|
||||
defineSymbol("nimUseStrictDefs") # deadcode
|
||||
defineSymbol("nimHasNolineTooLong")
|
||||
|
||||
defineSymbol("nimHasCastExtendedVm")
|
||||
@@ -171,3 +171,4 @@ proc initDefines*(symbols: StringTableRef) =
|
||||
defineSymbol("nimHasJsNoLambdaLifting")
|
||||
defineSymbol("nimHasDefaultFloatRoundtrip")
|
||||
defineSymbol("nimHasXorSet")
|
||||
|
||||
|
||||
@@ -1207,6 +1207,8 @@ proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
|
||||
result.ast[pragmasPos].add newTree(nkExprColonExpr,
|
||||
newIdentNode(g.cache.getIdent("raises"), info), newNodeI(nkBracket, info))
|
||||
|
||||
if kind == attachedDestructor:
|
||||
incl result.options, optQuirky
|
||||
completePartialOp(g, idgen.module, typ, kind, result)
|
||||
|
||||
|
||||
|
||||
@@ -222,7 +222,7 @@ type
|
||||
strictEffects,
|
||||
unicodeOperators, # deadcode
|
||||
flexibleOptionalParams,
|
||||
strictDefs,
|
||||
strictDefs, # deadcode
|
||||
strictCaseObjects,
|
||||
inferGenericTypes,
|
||||
openSym, # remove nfDisabledOpenSym when this is default
|
||||
|
||||
@@ -1318,8 +1318,12 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: var int,
|
||||
pragmaProposition(c, it)
|
||||
of wEnsures:
|
||||
pragmaEnsures(c, it)
|
||||
of wEnforceNoRaises, wQuirky:
|
||||
of wEnforceNoRaises:
|
||||
sym.flags.incl sfNeverRaises
|
||||
of wQuirky:
|
||||
sym.flags.incl sfNeverRaises
|
||||
if sym.kind in {skProc, skMethod, skConverter, skFunc, skIterator}:
|
||||
sym.options.incl optQuirky
|
||||
of wSystemRaisesDefect:
|
||||
sym.flags.incl sfSystemRaisesDefect
|
||||
of wVirtual:
|
||||
|
||||
@@ -1501,7 +1501,10 @@ proc semProcTypeNode(c: PContext, n, genericParams: PNode,
|
||||
addParamOrResult(c, arg, kind)
|
||||
styleCheckDef(c, a[j].info, arg)
|
||||
onDef(a[j].info, arg)
|
||||
a[j] = newSymNode(arg)
|
||||
if a[j].kind == nkPragmaExpr:
|
||||
a[j][0] = newSymNode(arg)
|
||||
else:
|
||||
a[j] = newSymNode(arg)
|
||||
|
||||
var r: PType = nil
|
||||
if n[0].kind != nkEmpty:
|
||||
|
||||
@@ -1692,7 +1692,8 @@ proc typeRel(c: var TCandidate, f, aOrig: PType,
|
||||
if aAsObject.kind == tyObject and trIsOutParam notin flags:
|
||||
let baseType = aAsObject.base
|
||||
if baseType != nil:
|
||||
inc c.inheritancePenalty, 1 + int(c.inheritancePenalty < 0)
|
||||
if tfFinal notin aAsObject.flags:
|
||||
inc c.inheritancePenalty, 1 + int(c.inheritancePenalty < 0)
|
||||
let ret = typeRel(c, f, baseType, flags)
|
||||
return if ret in {isEqual,isGeneric}: isSubtype else: ret
|
||||
|
||||
@@ -1733,6 +1734,10 @@ proc typeRel(c: var TCandidate, f, aOrig: PType,
|
||||
let tr = typeRel(c, f[i], x[i], flags)
|
||||
if tr <= isSubtype: return
|
||||
result = isGeneric
|
||||
let impl = last(f[0])
|
||||
if impl.kind == tyObject and tfFinal notin impl.flags:
|
||||
# match non-invocation case
|
||||
inc c.inheritancePenalty, 0 + int(c.inheritancePenalty < 0)
|
||||
elif x.kind == tyGenericInst and f[0] == x[0] and
|
||||
x.len - 1 == f.len:
|
||||
for i in 1..<f.len:
|
||||
@@ -1789,7 +1794,8 @@ proc typeRel(c: var TCandidate, f, aOrig: PType,
|
||||
depth = -1
|
||||
|
||||
if depth >= 0:
|
||||
inc c.inheritancePenalty, depth + int(c.inheritancePenalty < 0)
|
||||
if aobj.kind == tyObject and tfFinal notin aobj.flags:
|
||||
inc c.inheritancePenalty, depth + int(c.inheritancePenalty < 0)
|
||||
# bug #4863: We still need to bind generic alias crap, so
|
||||
# we cannot return immediately:
|
||||
result = if depth == 0: isGeneric else: isSubtype
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
import semmacrosanity
|
||||
import
|
||||
std/[strutils, tables, parseutils],
|
||||
std/[strutils, tables, intsets, parseutils],
|
||||
msgs, vmdef, vmgen, nimsets, types,
|
||||
parser, vmdeps, idents, trees, renderer, options, transf,
|
||||
gorgeimpl, lineinfos, btrees, macrocacheimpl,
|
||||
@@ -2425,9 +2425,12 @@ proc evalConstExprAux(module: PSym; idgen: IdGenerator;
|
||||
setupGlobalCtx(module, g, idgen)
|
||||
var c = PCtx g.vm
|
||||
let oldMode = c.mode
|
||||
let oldLocals = c.locals
|
||||
c.mode = mode
|
||||
c.locals = initIntSet()
|
||||
c.cannotEval = false
|
||||
let start = genExpr(c, n, requiresValue = mode!=emStaticStmt)
|
||||
c.locals = oldLocals
|
||||
if c.cannotEval:
|
||||
return errorNode(idgen, prc, n)
|
||||
if c.code[start].opcode == opcEof: return newNodeI(nkEmpty, n.info)
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
## This module contains the type definitions for the new evaluation engine.
|
||||
## An instruction is 1-3 int32s in memory, it is a register based VM.
|
||||
|
||||
import std/[tables, strutils]
|
||||
import std/[tables, strutils, intsets]
|
||||
|
||||
import ast, idents, options, modulegraphs, lineinfos
|
||||
|
||||
@@ -272,6 +272,7 @@ type
|
||||
vmstateDiff*: seq[(PSym, PNode)] # we remember the "diff" to global state here (feature for IC)
|
||||
procToCodePos*: Table[int, int]
|
||||
cannotEval*: bool
|
||||
locals*: IntSet
|
||||
|
||||
PStackFrame* = ref TStackFrame
|
||||
TStackFrame* {.acyclic.} = object
|
||||
|
||||
@@ -1583,6 +1583,7 @@ proc checkCanEval(c: PCtx; n: PNode) =
|
||||
# are in the right scope:
|
||||
if sfGenSym in s.flags and c.prc.sym == nil: discard
|
||||
elif s.kind == skParam and s.typ.kind == tyTypeDesc: discard
|
||||
elif s.kind in {skVar, skLet} and s.id in c.locals: discard
|
||||
else: cannotEval(c, n)
|
||||
elif s.kind in {skProc, skFunc, skConverter, skMethod,
|
||||
skIterator} and sfForward in s.flags:
|
||||
@@ -1975,7 +1976,7 @@ proc genVarSection(c: PCtx; n: PNode) =
|
||||
c.gen(lowerTupleUnpacking(c.graph, a, c.idgen, c.getOwner))
|
||||
elif a[0].kind == nkSym:
|
||||
let s = a[0].sym
|
||||
checkCanEval(c, a[0])
|
||||
c.locals.incl(s.id)
|
||||
if s.isGlobal:
|
||||
let runtimeAccessToCompileTime = c.mode == emRepl and
|
||||
sfCompileTime in s.flags and s.position > 0
|
||||
|
||||
126
doc/manual.md
126
doc/manual.md
@@ -5186,22 +5186,22 @@ caught by reference. Example:
|
||||
proc fn() =
|
||||
let a = initRuntimeError("foo")
|
||||
doAssert $a.what == "foo"
|
||||
var b: cstring
|
||||
var b = ""
|
||||
try: raise initRuntimeError("foo2")
|
||||
except CStdException as e:
|
||||
doAssert e is CStdException
|
||||
b = e.what()
|
||||
doAssert $b == "foo2"
|
||||
b = $e.what()
|
||||
doAssert b == "foo2"
|
||||
|
||||
try: raise initStdException()
|
||||
except CStdException: discard
|
||||
|
||||
try: raise initRuntimeError("foo3")
|
||||
except CRuntimeError as e:
|
||||
b = e.what()
|
||||
b = $e.what()
|
||||
except CStdException:
|
||||
doAssert false
|
||||
doAssert $b == "foo3"
|
||||
doAssert b == "foo3"
|
||||
|
||||
fn()
|
||||
```
|
||||
@@ -9043,3 +9043,119 @@ This means the following compiles (for now) even though it really should not:
|
||||
inc i
|
||||
access a[i].v
|
||||
```
|
||||
|
||||
Strict definitions and `out` parameters
|
||||
=======================================
|
||||
|
||||
*every* local variable must be initialized explicitly before it can be used:
|
||||
|
||||
```nim
|
||||
proc test =
|
||||
var s: seq[string]
|
||||
s.add "abc" # invalid!
|
||||
```
|
||||
|
||||
Needs to be written as:
|
||||
|
||||
```nim
|
||||
proc test =
|
||||
var s: seq[string] = @[]
|
||||
s.add "abc" # valid!
|
||||
```
|
||||
|
||||
A control flow analysis is performed in order to prove that a variable has been written to
|
||||
before it is used. Thus the following is valid:
|
||||
|
||||
```nim
|
||||
proc test(cond: bool) =
|
||||
var s: seq[string]
|
||||
if cond:
|
||||
s = @["y"]
|
||||
else:
|
||||
s = @[]
|
||||
s.add "abc" # valid!
|
||||
```
|
||||
|
||||
In this example every path does set `s` to a value before it is used.
|
||||
|
||||
```nim
|
||||
proc test(cond: bool) =
|
||||
let s: seq[string]
|
||||
if cond:
|
||||
s = @["y"]
|
||||
else:
|
||||
s = @[]
|
||||
```
|
||||
|
||||
`let` statements are allowed to not have an initial value, but every path should set `s` to a value before it is used.
|
||||
|
||||
|
||||
`out` parameters
|
||||
----------------
|
||||
|
||||
An `out` parameter is like a `var` parameter but it must be written to before it can be used:
|
||||
|
||||
```nim
|
||||
proc myopen(f: out File; name: string): bool =
|
||||
f = default(File)
|
||||
result = open(f, name)
|
||||
```
|
||||
|
||||
While it is usually the better style to use the return type in order to return results API and ABI
|
||||
considerations might make this infeasible. Like for `var T` Nim maps `out T` to a hidden pointer.
|
||||
For example POSIX's `stat` routine can be wrapped as:
|
||||
|
||||
```nim
|
||||
proc stat*(a1: cstring, a2: out Stat): cint {.importc, header: "<sys/stat.h>".}
|
||||
```
|
||||
|
||||
When the implementation of a routine with output parameters is analysed, the compiler
|
||||
checks that every path before the (implicit or explicit) return does set every output
|
||||
parameter:
|
||||
|
||||
```nim
|
||||
proc p(x: out int; y: out string; cond: bool) =
|
||||
x = 4
|
||||
if cond:
|
||||
y = "abc"
|
||||
# error: not every path initializes 'y'
|
||||
```
|
||||
|
||||
|
||||
Out parameters and exception handling
|
||||
-------------------------------------
|
||||
|
||||
The analysis should take exceptions into account (but currently does not):
|
||||
|
||||
```nim
|
||||
proc p(x: out int; y: out string; cond: bool) =
|
||||
x = canRaise(45)
|
||||
y = "abc" # <-- error: not every path initializes 'y'
|
||||
```
|
||||
|
||||
Once the implementation takes exceptions into account it is easy enough to
|
||||
use `outParam = default(typeof(outParam))` in the beginning of the proc body.
|
||||
|
||||
Out parameters and inheritance
|
||||
------------------------------
|
||||
|
||||
It is not valid to pass an lvalue of a supertype to an `out T` parameter:
|
||||
|
||||
```nim
|
||||
type
|
||||
Superclass = object of RootObj
|
||||
a: int
|
||||
Subclass = object of Superclass
|
||||
s: string
|
||||
|
||||
proc init(x: out Superclass) =
|
||||
x = Superclass(a: 8)
|
||||
|
||||
var v: Subclass
|
||||
init v
|
||||
use v.s # the 's' field was never initialized!
|
||||
```
|
||||
|
||||
However, in the future this could be allowed and provide a better way to write object
|
||||
constructors that take inheritance into account.
|
||||
|
||||
|
||||
@@ -1919,136 +1919,6 @@ restrictions / changes:
|
||||
yet performed for ordinary slices outside of a `parallel` section.
|
||||
|
||||
|
||||
Strict definitions and `out` parameters
|
||||
=======================================
|
||||
|
||||
With `experimental: "strictDefs"` *every* local variable must be initialized explicitly before it can be used:
|
||||
|
||||
```nim
|
||||
{.experimental: "strictDefs".}
|
||||
|
||||
proc test =
|
||||
var s: seq[string]
|
||||
s.add "abc" # invalid!
|
||||
|
||||
```
|
||||
|
||||
Needs to be written as:
|
||||
|
||||
```nim
|
||||
{.experimental: "strictDefs".}
|
||||
|
||||
proc test =
|
||||
var s: seq[string] = @[]
|
||||
s.add "abc" # valid!
|
||||
|
||||
```
|
||||
|
||||
A control flow analysis is performed in order to prove that a variable has been written to
|
||||
before it is used. Thus the following is valid:
|
||||
|
||||
```nim
|
||||
{.experimental: "strictDefs".}
|
||||
|
||||
proc test(cond: bool) =
|
||||
var s: seq[string]
|
||||
if cond:
|
||||
s = @["y"]
|
||||
else:
|
||||
s = @[]
|
||||
s.add "abc" # valid!
|
||||
```
|
||||
|
||||
In this example every path does set `s` to a value before it is used.
|
||||
|
||||
```nim
|
||||
{.experimental: "strictDefs".}
|
||||
|
||||
proc test(cond: bool) =
|
||||
let s: seq[string]
|
||||
if cond:
|
||||
s = @["y"]
|
||||
else:
|
||||
s = @[]
|
||||
```
|
||||
|
||||
With `experimental: "strictDefs"`, `let` statements are allowed to not have an initial value, but every path should set `s` to a value before it is used.
|
||||
|
||||
|
||||
`out` parameters
|
||||
----------------
|
||||
|
||||
An `out` parameter is like a `var` parameter but it must be written to before it can be used:
|
||||
|
||||
```nim
|
||||
proc myopen(f: out File; name: string): bool =
|
||||
f = default(File)
|
||||
result = open(f, name)
|
||||
```
|
||||
|
||||
While it is usually the better style to use the return type in order to return results API and ABI
|
||||
considerations might make this infeasible. Like for `var T` Nim maps `out T` to a hidden pointer.
|
||||
For example POSIX's `stat` routine can be wrapped as:
|
||||
|
||||
```nim
|
||||
proc stat*(a1: cstring, a2: out Stat): cint {.importc, header: "<sys/stat.h>".}
|
||||
```
|
||||
|
||||
When the implementation of a routine with output parameters is analysed, the compiler
|
||||
checks that every path before the (implicit or explicit) return does set every output
|
||||
parameter:
|
||||
|
||||
```nim
|
||||
proc p(x: out int; y: out string; cond: bool) =
|
||||
x = 4
|
||||
if cond:
|
||||
y = "abc"
|
||||
# error: not every path initializes 'y'
|
||||
```
|
||||
|
||||
|
||||
Out parameters and exception handling
|
||||
-------------------------------------
|
||||
|
||||
The analysis should take exceptions into account (but currently does not):
|
||||
|
||||
```nim
|
||||
proc p(x: out int; y: out string; cond: bool) =
|
||||
x = canRaise(45)
|
||||
y = "abc" # <-- error: not every path initializes 'y'
|
||||
```
|
||||
|
||||
Once the implementation takes exceptions into account it is easy enough to
|
||||
use `outParam = default(typeof(outParam))` in the beginning of the proc body.
|
||||
|
||||
Out parameters and inheritance
|
||||
------------------------------
|
||||
|
||||
It is not valid to pass an lvalue of a supertype to an `out T` parameter:
|
||||
|
||||
```nim
|
||||
type
|
||||
Superclass = object of RootObj
|
||||
a: int
|
||||
Subclass = object of Superclass
|
||||
s: string
|
||||
|
||||
proc init(x: out Superclass) =
|
||||
x = Superclass(a: 8)
|
||||
|
||||
var v: Subclass
|
||||
init v
|
||||
use v.s # the 's' field was never initialized!
|
||||
```
|
||||
|
||||
However, in the future this could be allowed and provide a better way to write object
|
||||
constructors that take inheritance into account.
|
||||
|
||||
|
||||
**Note**: The implementation of "strict definitions" and "out parameters" is experimental but the concept
|
||||
is solid and it is expected that eventually this mode becomes the default in later versions.
|
||||
|
||||
|
||||
Strict case objects
|
||||
===================
|
||||
|
||||
|
||||
@@ -242,6 +242,7 @@ else:
|
||||
`=destroy`(pattern.captureNameToId)
|
||||
|
||||
proc getinfo[T](pattern: Regex, opt: cint): T =
|
||||
result = default(T)
|
||||
let retcode = pcre.fullinfo(pattern.pcreObj, pattern.pcreExtra, opt, addr result)
|
||||
|
||||
if retcode < 0:
|
||||
@@ -275,8 +276,8 @@ proc initRegex(pattern: string, flags: int, study = true): Regex =
|
||||
new(result, destroyRegex)
|
||||
result.pattern = pattern
|
||||
|
||||
var errorMsg: cstring
|
||||
var errOffset: cint
|
||||
var errorMsg: cstring = ""
|
||||
var errOffset: cint = 0
|
||||
|
||||
result.pcreObj = pcre.compile(cstring(pattern),
|
||||
# better hope int is at least 4 bytes..
|
||||
@@ -288,7 +289,7 @@ proc initRegex(pattern: string, flags: int, study = true): Regex =
|
||||
|
||||
if study:
|
||||
var options: cint = 0
|
||||
var hasJit: cint
|
||||
var hasJit: cint = cint(0)
|
||||
if pcre.config(pcre.CONFIG_JIT, addr hasJit) == 0:
|
||||
if hasJit == 1'i32:
|
||||
options = pcre.STUDY_JIT_COMPILE
|
||||
@@ -313,7 +314,7 @@ proc matchesCrLf(pattern: Regex): bool =
|
||||
return true
|
||||
|
||||
# get flags from build config
|
||||
var confFlags: cint
|
||||
var confFlags: cint = cint(0)
|
||||
if pcre.config(pcre.CONFIG_NEWLINE, addr confFlags) != 0:
|
||||
assert(false, "CONFIG_NEWLINE apparently got screwed up")
|
||||
|
||||
@@ -573,7 +574,7 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): R
|
||||
pcre.UTF8) > 0u32
|
||||
let strlen = if endpos == int.high: str.len else: endpos+1
|
||||
var offset = start
|
||||
var match: Option[RegexMatch]
|
||||
var match: Option[RegexMatch] = default(Option[RegexMatch])
|
||||
var neverMatched = true
|
||||
|
||||
while true:
|
||||
@@ -762,7 +763,7 @@ proc escapeRe*(str: string): string {.gcsafe.} =
|
||||
const SpecialCharMatcher = {'\\', '+', '*', '?', '[', '^', ']', '$', '(',
|
||||
')', '{', '}', '=', '!', '<', '>', '|', ':',
|
||||
'-'}
|
||||
|
||||
result = ""
|
||||
for c in items(str):
|
||||
case c
|
||||
of SpecialCharMatcher:
|
||||
|
||||
@@ -466,7 +466,7 @@ template `=~` *(s: string, pattern: Regex): untyped =
|
||||
doAssert parse(" # comment ... ") == """("# comment ... ",)"""
|
||||
bind MaxSubpatterns
|
||||
when not declaredInScope(matches):
|
||||
var matches {.inject.}: array[MaxSubpatterns, string]
|
||||
var matches {.inject.}: array[MaxSubpatterns, string] = default(array[MaxSubpatterns, string])
|
||||
match(s, pattern, matches)
|
||||
|
||||
# ------------------------- more string handling ------------------------------
|
||||
|
||||
@@ -470,12 +470,6 @@ typedef char* NCSTRING;
|
||||
|
||||
#define NIM_STRLIT_FLAG ((NU)(1) << ((NIM_INTBITS) - 2)) /* This has to be the same as system.strlitFlag! */
|
||||
|
||||
#define STRING_LITERAL(name, str, length) \
|
||||
static const struct { \
|
||||
TGenericSeq Sup; \
|
||||
NIM_CHAR data[(length) + 1]; \
|
||||
} name = {{length, (NI) ((NU)length | NIM_STRLIT_FLAG)}, str}
|
||||
|
||||
/* declared size of a sequence/variable length array: */
|
||||
#if defined(__cplusplus) && defined(__clang__)
|
||||
# define SEQ_DECL_SIZE 1
|
||||
|
||||
@@ -143,6 +143,7 @@ proc reversed*[T](a: openArray[T]): seq[T] {.inline.} =
|
||||
runnableExamples:
|
||||
assert [10, 11, 12].reversed == @[12, 11, 10]
|
||||
assert seq[string].default.reversed == @[]
|
||||
result = @[]
|
||||
let n = a.len
|
||||
result.setLen(n)
|
||||
for i in 0..<n: result[i] = a[n - (i + 1)]
|
||||
|
||||
@@ -264,9 +264,9 @@ proc asyncSingleProc(prc: NimNode): NimNode =
|
||||
procBody.insert(0): quote do:
|
||||
{.push warning[resultshadowed]: off.}
|
||||
when `subRetType` isnot void:
|
||||
var `resultIdent`: `subRetType`
|
||||
var `resultIdent`: `subRetType` = default(`subRetType`)
|
||||
else:
|
||||
var `resultIdent`: Future[void]
|
||||
var `resultIdent`: Future[void] = nil
|
||||
{.pop.}
|
||||
|
||||
var `needsCompletionSym` = false
|
||||
|
||||
@@ -151,10 +151,12 @@ proc encode*[T: byte|char](s: openArray[T], safe = false): string =
|
||||
assert encode(['n', 'i', 'm']) == "bmlt"
|
||||
assert encode(@['n', 'i', 'm']) == "bmlt"
|
||||
assert encode([1'u8, 2, 3, 4, 5]) == "AQIDBAU="
|
||||
result = ""
|
||||
encodeImpl()
|
||||
|
||||
proc encode*[T: SomeInteger and not byte](s: openArray[T], safe = false): string
|
||||
{.deprecated: "use `byte` or `char` instead".} =
|
||||
result = ""
|
||||
encodeImpl()
|
||||
|
||||
proc encodeMime*(s: string, lineLen = 75.Positive, newLine = "\r\n",
|
||||
|
||||
@@ -67,6 +67,7 @@ func len*[T](c: CritBitTree[T]): int {.inline.} =
|
||||
result = c.count
|
||||
|
||||
proc rawGet[T](c: CritBitTree[T], key: string): Node[T] =
|
||||
result = nil
|
||||
var it = c.root
|
||||
while it != nil:
|
||||
if not it.isLeaf:
|
||||
@@ -145,7 +146,7 @@ func exclImpl[T](c: var CritBitTree[T], key: string): int =
|
||||
var whereq: ptr Node[T] = nil
|
||||
if p == nil: return c.count
|
||||
var dir = 0
|
||||
var q: Node[T]
|
||||
var q: Node[T] = nil
|
||||
while not p.isLeaf:
|
||||
whereq = wherep
|
||||
q = p
|
||||
@@ -394,6 +395,7 @@ iterator mpairs*[T](c: var CritBitTree[T]): tuple[key: string, val: var T] =
|
||||
for x in leaves(c.root): yield (x.key, x.val)
|
||||
|
||||
proc allprefixedAux[T](c: CritBitTree[T], key: string): Node[T] =
|
||||
result = nil
|
||||
var p = c.root
|
||||
var top = p
|
||||
if p != nil:
|
||||
|
||||
@@ -92,6 +92,7 @@ proc initDeque*[T](initialSize: int = defaultInitialSize): Deque[T] =
|
||||
##
|
||||
## **See also:**
|
||||
## * `toDeque proc <#toDeque,openArray[T]>`_
|
||||
result = Deque[T]()
|
||||
result.initImpl(initialSize)
|
||||
|
||||
func len*[T](deq: Deque[T]): int {.inline.} =
|
||||
@@ -297,7 +298,7 @@ proc toDeque*[T](x: openArray[T]): Deque[T] {.since: (1, 3).} =
|
||||
let a = toDeque([7, 8, 9])
|
||||
assert len(a) == 3
|
||||
assert $a == "[7, 8, 9]"
|
||||
|
||||
result = Deque[T]()
|
||||
result.initImpl(x.len)
|
||||
for item in items(x):
|
||||
result.addLast(item)
|
||||
|
||||
@@ -157,7 +157,7 @@ proc toHeapQueue*[T](x: openArray[T]): HeapQueue[T] {.since: (1, 3).} =
|
||||
assert heap[0] == 8
|
||||
|
||||
# see https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap
|
||||
result.data = @x
|
||||
result = HeapQueue[T](data: @x)
|
||||
for i in countdown(x.len div 2 - 1, 0):
|
||||
siftdown(result, i)
|
||||
|
||||
|
||||
@@ -115,7 +115,7 @@ proc initSinglyLinkedList*[T](): SinglyLinkedList[T] =
|
||||
runnableExamples:
|
||||
let a = initSinglyLinkedList[int]()
|
||||
|
||||
discard
|
||||
result = default(SinglyLinkedList[T])
|
||||
|
||||
proc initDoublyLinkedList*[T](): DoublyLinkedList[T] =
|
||||
## Creates a new doubly linked list that is empty.
|
||||
@@ -125,7 +125,7 @@ proc initDoublyLinkedList*[T](): DoublyLinkedList[T] =
|
||||
runnableExamples:
|
||||
let a = initDoublyLinkedList[int]()
|
||||
|
||||
discard
|
||||
result = default(DoublyLinkedList[T])
|
||||
|
||||
proc initSinglyLinkedRing*[T](): SinglyLinkedRing[T] =
|
||||
## Creates a new singly linked ring that is empty.
|
||||
@@ -135,7 +135,7 @@ proc initSinglyLinkedRing*[T](): SinglyLinkedRing[T] =
|
||||
runnableExamples:
|
||||
let a = initSinglyLinkedRing[int]()
|
||||
|
||||
discard
|
||||
result = default(SinglyLinkedRing[T])
|
||||
|
||||
proc initDoublyLinkedRing*[T](): DoublyLinkedRing[T] =
|
||||
## Creates a new doubly linked ring that is empty.
|
||||
@@ -145,7 +145,7 @@ proc initDoublyLinkedRing*[T](): DoublyLinkedRing[T] =
|
||||
runnableExamples:
|
||||
let a = initDoublyLinkedRing[int]()
|
||||
|
||||
discard
|
||||
result = default(DoublyLinkedRing[T])
|
||||
|
||||
proc newDoublyLinkedNode*[T](value: T): DoublyLinkedNode[T] =
|
||||
## Creates a new doubly linked node with the given `value`.
|
||||
@@ -319,6 +319,10 @@ proc find*[T](L: SomeLinkedCollection[T], value: T): SomeLinkedNode[T] =
|
||||
let a = [9, 8].toSinglyLinkedList
|
||||
assert a.find(9).value == 9
|
||||
assert a.find(1) == nil
|
||||
when typeof(nodes(L)) is SinglyLinkedNode[T]:
|
||||
result = SinglyLinkedNode[T](nil)
|
||||
else:
|
||||
result = DoublyLinkedNode[T](nil)
|
||||
|
||||
for x in nodes(L):
|
||||
if x.value == value: return x
|
||||
|
||||
@@ -167,7 +167,7 @@ func count*[T](s: openArray[T], x: T): int =
|
||||
assert count(a, 2) == 4
|
||||
assert count(a, 99) == 0
|
||||
assert count(b, 'r') == 2
|
||||
|
||||
result = 0
|
||||
for itm in items(s):
|
||||
if itm == x:
|
||||
inc result
|
||||
@@ -244,7 +244,7 @@ func minIndex*[T](s: openArray[T]): int {.since: (1, 1).} =
|
||||
assert minIndex(b) == 3
|
||||
assert minIndex(c) == 1
|
||||
assert minIndex(d) == 2
|
||||
|
||||
result = 0
|
||||
for i in 1..high(s):
|
||||
if s[i] < s[result]: result = i
|
||||
|
||||
@@ -261,7 +261,7 @@ func maxIndex*[T](s: openArray[T]): int {.since: (1, 1).} =
|
||||
assert maxIndex(b) == 0
|
||||
assert maxIndex(c) == 2
|
||||
assert maxIndex(d) == 0
|
||||
|
||||
result = 0
|
||||
for i in 1..high(s):
|
||||
if s[i] > s[result]: result = i
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ proc enlarge[A](s: var HashSet[A]) =
|
||||
template inclImpl() {.dirty.} =
|
||||
if s.data.len == 0:
|
||||
initImpl(s, defaultInitialSize)
|
||||
var hc: Hash
|
||||
var hc: Hash = default(Hash)
|
||||
var index = rawGet(s, key, hc)
|
||||
if index < 0:
|
||||
if mustRehash(s):
|
||||
|
||||
@@ -670,7 +670,7 @@ proc initOrderedSet*[A](initialSize = defaultInitialSize): OrderedSet[A] =
|
||||
var a = initOrderedSet[int]()
|
||||
a.incl(3)
|
||||
assert len(a) == 1
|
||||
|
||||
result = OrderedSet[A]()
|
||||
result.init(initialSize)
|
||||
|
||||
proc toOrderedSet*[A](keys: openArray[A]): OrderedSet[A] =
|
||||
|
||||
@@ -139,12 +139,15 @@ template withValue*[A, B](t: var SharedTable[A, B], key: A,
|
||||
proc mget*[A, B](t: var SharedTable[A, B], key: A): var B =
|
||||
## Retrieves the value at `t[key]`. The value can be modified.
|
||||
## If `key` is not in `t`, the `KeyError` exception is raised.
|
||||
withLock t:
|
||||
var hc: Hash
|
||||
var index = rawGet(t, key, hc)
|
||||
let hasKey = index >= 0
|
||||
if hasKey: result = t.data[index].val
|
||||
if not hasKey:
|
||||
acquire(t.lock)
|
||||
var hc: Hash = Hash(0)
|
||||
var index = rawGet(t, key, hc)
|
||||
let hasKey = index >= 0
|
||||
if hasKey:
|
||||
result = t.data[index].val
|
||||
release(t.lock)
|
||||
else:
|
||||
release(t.lock)
|
||||
when compiles($key):
|
||||
raise newException(KeyError, "key not found: " & $key)
|
||||
else:
|
||||
|
||||
@@ -30,7 +30,7 @@ proc rawGetDeep[X, A](t: X, key: A, hc: var Hash): int {.inline, outParamsAt: [3
|
||||
rawGetDeepImpl()
|
||||
|
||||
proc rawInsert[X, A, B](t: var X, data: var KeyValuePairSeq[A, B],
|
||||
key: A, val: sink B, hc: Hash, h: Hash) =
|
||||
key: sink A, val: sink B, hc: Hash, h: Hash) =
|
||||
rawInsertImpl()
|
||||
|
||||
template checkIfInitialized() =
|
||||
|
||||
@@ -281,7 +281,7 @@ proc initTable*[A, B](initialSize = defaultInitialSize): Table[A, B] =
|
||||
result = default(Table[A, B])
|
||||
initImpl(result, initialSize)
|
||||
|
||||
proc `[]=`*[A, B](t: var Table[A, B], key: A, val: sink B) =
|
||||
proc `[]=`*[A, B](t: var Table[A, B], key: sink A, val: sink B) =
|
||||
## Inserts a `(key, value)` pair into `t`.
|
||||
##
|
||||
## See also:
|
||||
@@ -313,7 +313,7 @@ proc toTable*[A, B](pairs: openArray[(A, B)]): Table[A, B] =
|
||||
result = initTable[A, B](pairs.len)
|
||||
for key, val in items(pairs): result[key] = val
|
||||
|
||||
proc `[]`*[A, B](t: Table[A, B], key: A): lent B =
|
||||
proc `[]`*[A, B](t: Table[A, B], key: sink A): lent B =
|
||||
## Retrieves the value at `t[key]`.
|
||||
##
|
||||
## If `key` is not in `t`, the `KeyError` exception is raised.
|
||||
@@ -336,7 +336,7 @@ proc `[]`*[A, B](t: Table[A, B], key: A): lent B =
|
||||
echo a['z']
|
||||
get(t, key)
|
||||
|
||||
proc `[]`*[A, B](t: var Table[A, B], key: A): var B =
|
||||
proc `[]`*[A, B](t: var Table[A, B], key: sink A): var B =
|
||||
## Retrieves the value at `t[key]`. The value can be modified.
|
||||
##
|
||||
## If `key` is not in `t`, the `KeyError` exception is raised.
|
||||
@@ -494,7 +494,7 @@ proc len*[A, B](t: Table[A, B]): int =
|
||||
|
||||
result = t.counter
|
||||
|
||||
proc add*[A, B](t: var Table[A, B], key: A, val: sink B) {.deprecated:
|
||||
proc add*[A, B](t: var Table[A, B], key: sink A, val: sink B) {.deprecated:
|
||||
"Deprecated since v1.4; it was more confusing than useful, use `[]=`".} =
|
||||
## Puts a new `(key, value)` pair into `t` even if `t[key]` already exists.
|
||||
##
|
||||
@@ -628,7 +628,7 @@ template withValue*[A, B](t: var Table[A, B], key: A, value, body: untyped) =
|
||||
assert t[1].uid == 1314
|
||||
|
||||
mixin rawGet
|
||||
var hc: Hash
|
||||
var hc: Hash = default(Hash)
|
||||
var index = rawGet(t, key, hc)
|
||||
let hasKey = index >= 0
|
||||
if hasKey:
|
||||
@@ -677,7 +677,7 @@ template withValue*[A, B](t: var Table[A, B], key: A,
|
||||
body2
|
||||
|
||||
|
||||
iterator pairs*[A, B](t: Table[A, B]): (A, B) =
|
||||
iterator pairs*[A, B](t: Table[A, B]): (lent A, lent B) =
|
||||
## Iterates over any `(key, value)` pair in the table `t`.
|
||||
##
|
||||
## See also:
|
||||
@@ -864,7 +864,7 @@ proc newTableFrom*[A, B, C](collection: A, index: proc(x: B): C): TableRef[C, B]
|
||||
for item in collection:
|
||||
result[index(item)] = item
|
||||
|
||||
proc `[]`*[A, B](t: TableRef[A, B], key: A): var B =
|
||||
proc `[]`*[A, B](t: TableRef[A, B], key: sink A): var B =
|
||||
## Retrieves the value at `t[key]`.
|
||||
##
|
||||
## If `key` is not in `t`, the `KeyError` exception is raised.
|
||||
@@ -888,7 +888,7 @@ proc `[]`*[A, B](t: TableRef[A, B], key: A): var B =
|
||||
|
||||
result = t[][key]
|
||||
|
||||
proc `[]=`*[A, B](t: TableRef[A, B], key: A, val: sink B) =
|
||||
proc `[]=`*[A, B](t: TableRef[A, B], key: sink A, val: sink B) =
|
||||
## Inserts a `(key, value)` pair into `t`.
|
||||
##
|
||||
## See also:
|
||||
@@ -1045,7 +1045,7 @@ proc len*[A, B](t: TableRef[A, B]): int =
|
||||
|
||||
result = t.counter
|
||||
|
||||
proc add*[A, B](t: TableRef[A, B], key: A, val: sink B) {.deprecated:
|
||||
proc add*[A, B](t: TableRef[A, B], key: sink A, val: sink B) {.deprecated:
|
||||
"Deprecated since v1.4; it was more confusing than useful, use `[]=`".} =
|
||||
## Puts a new `(key, value)` pair into `t` even if `t[key]` already exists.
|
||||
##
|
||||
@@ -1139,7 +1139,7 @@ proc `==`*[A, B](s, t: TableRef[A, B]): bool =
|
||||
|
||||
|
||||
|
||||
iterator pairs*[A, B](t: TableRef[A, B]): (A, B) =
|
||||
iterator pairs*[A, B](t: TableRef[A, B]): (lent A, lent B) =
|
||||
## Iterates over any `(key, value)` pair in the table `t`.
|
||||
##
|
||||
## See also:
|
||||
@@ -1297,7 +1297,7 @@ proc rawGet[A, B](t: OrderedTable[A, B], key: A, hc: var Hash): int =
|
||||
|
||||
proc rawInsert[A, B](t: var OrderedTable[A, B],
|
||||
data: var OrderedKeyValuePairSeq[A, B],
|
||||
key: A, val: sink B, hc: Hash, h: Hash) =
|
||||
key: sink A, val: sink B, hc: Hash, h: Hash) =
|
||||
rawInsertImpl()
|
||||
data[h].next = -1
|
||||
if t.first < 0: t.first = h
|
||||
@@ -1349,7 +1349,7 @@ proc initOrderedTable*[A, B](initialSize = defaultInitialSize): OrderedTable[A,
|
||||
result = default(OrderedTable[A, B])
|
||||
initImpl(result, initialSize)
|
||||
|
||||
proc `[]=`*[A, B](t: var OrderedTable[A, B], key: A, val: sink B) =
|
||||
proc `[]=`*[A, B](t: var OrderedTable[A, B], key: sink A, val: sink B) =
|
||||
## Inserts a `(key, value)` pair into `t`.
|
||||
##
|
||||
## See also:
|
||||
@@ -1382,7 +1382,7 @@ proc toOrderedTable*[A, B](pairs: openArray[(A, B)]): OrderedTable[A, B] =
|
||||
result = initOrderedTable[A, B](pairs.len)
|
||||
for key, val in items(pairs): result[key] = val
|
||||
|
||||
proc `[]`*[A, B](t: OrderedTable[A, B], key: A): lent B =
|
||||
proc `[]`*[A, B](t: OrderedTable[A, B], key: sink A): lent B =
|
||||
## Retrieves the value at `t[key]`.
|
||||
##
|
||||
## If `key` is not in `t`, the `KeyError` exception is raised.
|
||||
@@ -1406,7 +1406,7 @@ proc `[]`*[A, B](t: OrderedTable[A, B], key: A): lent B =
|
||||
|
||||
get(t, key)
|
||||
|
||||
proc `[]`*[A, B](t: var OrderedTable[A, B], key: A): var B =
|
||||
proc `[]`*[A, B](t: var OrderedTable[A, B], key: sink A): var B =
|
||||
## Retrieves the value at `t[key]`. The value can be modified.
|
||||
##
|
||||
## If `key` is not in `t`, the `KeyError` exception is raised.
|
||||
@@ -1547,7 +1547,7 @@ proc len*[A, B](t: OrderedTable[A, B]): int {.inline.} =
|
||||
|
||||
result = t.counter
|
||||
|
||||
proc add*[A, B](t: var OrderedTable[A, B], key: A, val: sink B) {.deprecated:
|
||||
proc add*[A, B](t: var OrderedTable[A, B], key: sink A, val: sink B) {.deprecated:
|
||||
"Deprecated since v1.4; it was more confusing than useful, use `[]=`".} =
|
||||
## Puts a new `(key, value)` pair into `t` even if `t[key]` already exists.
|
||||
##
|
||||
@@ -1727,7 +1727,7 @@ proc `==`*[A, B](s, t: OrderedTable[A, B]): bool =
|
||||
|
||||
|
||||
|
||||
iterator pairs*[A, B](t: OrderedTable[A, B]): (A, B) =
|
||||
iterator pairs*[A, B](t: OrderedTable[A, B]): (lent A, lent B) =
|
||||
## Iterates over any `(key, value)` pair in the table `t` in insertion
|
||||
## order.
|
||||
##
|
||||
@@ -1884,7 +1884,7 @@ proc newOrderedTable*[A, B](pairs: openArray[(A, B)]): OrderedTableRef[A, B] =
|
||||
for key, val in items(pairs): result[key] = val
|
||||
|
||||
|
||||
proc `[]`*[A, B](t: OrderedTableRef[A, B], key: A): var B =
|
||||
proc `[]`*[A, B](t: OrderedTableRef[A, B], key: sink A): var B =
|
||||
## Retrieves the value at `t[key]`.
|
||||
##
|
||||
## If `key` is not in `t`, the `KeyError` exception is raised.
|
||||
@@ -1907,7 +1907,7 @@ proc `[]`*[A, B](t: OrderedTableRef[A, B], key: A): var B =
|
||||
echo a['z']
|
||||
result = t[][key]
|
||||
|
||||
proc `[]=`*[A, B](t: OrderedTableRef[A, B], key: A, val: sink B) =
|
||||
proc `[]=`*[A, B](t: OrderedTableRef[A, B], key: sink A, val: sink B) =
|
||||
## Inserts a `(key, value)` pair into `t`.
|
||||
##
|
||||
## See also:
|
||||
@@ -2048,7 +2048,7 @@ proc len*[A, B](t: OrderedTableRef[A, B]): int {.inline.} =
|
||||
|
||||
result = t.counter
|
||||
|
||||
proc add*[A, B](t: OrderedTableRef[A, B], key: A, val: sink B) {.deprecated:
|
||||
proc add*[A, B](t: OrderedTableRef[A, B], key: sink A, val: sink B) {.deprecated:
|
||||
"Deprecated since v1.4; it was more confusing than useful, use `[]=`".} =
|
||||
## Puts a new `(key, value)` pair into `t` even if `t[key]` already exists.
|
||||
##
|
||||
@@ -2150,7 +2150,7 @@ proc `==`*[A, B](s, t: OrderedTableRef[A, B]): bool =
|
||||
|
||||
|
||||
|
||||
iterator pairs*[A, B](t: OrderedTableRef[A, B]): (A, B) =
|
||||
iterator pairs*[A, B](t: OrderedTableRef[A, B]): (lent A, lent B) =
|
||||
## Iterates over any `(key, value)` pair in the table `t` in insertion
|
||||
## order.
|
||||
##
|
||||
@@ -2345,7 +2345,7 @@ proc toCountTable*[A](keys: openArray[A]): CountTable[A] =
|
||||
result = initCountTable[A](keys.len)
|
||||
for key in items(keys): result.inc(key)
|
||||
|
||||
proc `[]`*[A](t: CountTable[A], key: A): int =
|
||||
proc `[]`*[A](t: CountTable[A], key: sink A): int =
|
||||
## Retrieves the value at `t[key]` if `key` is in `t`.
|
||||
## Otherwise `0` is returned.
|
||||
##
|
||||
@@ -2413,8 +2413,7 @@ proc smallest*[A](t: CountTable[A]): tuple[key: A, val: int] =
|
||||
for h in 0 .. high(t.data):
|
||||
if t.data[h].val > 0 and (minIdx == -1 or t.data[minIdx].val > t.data[h].val):
|
||||
minIdx = h
|
||||
result.key = t.data[minIdx].key
|
||||
result.val = t.data[minIdx].val
|
||||
result = (t.data[minIdx].key, t.data[minIdx].val)
|
||||
|
||||
proc largest*[A](t: CountTable[A]): tuple[key: A, val: int] =
|
||||
## Returns the `(key, value)` pair with the largest `val`. Efficiency: O(n)
|
||||
@@ -2425,8 +2424,7 @@ proc largest*[A](t: CountTable[A]): tuple[key: A, val: int] =
|
||||
var maxIdx = 0
|
||||
for h in 1 .. high(t.data):
|
||||
if t.data[maxIdx].val < t.data[h].val: maxIdx = h
|
||||
result.key = t.data[maxIdx].key
|
||||
result.val = t.data[maxIdx].val
|
||||
result = (t.data[maxIdx].key, t.data[maxIdx].val)
|
||||
|
||||
proc hasKey*[A](t: CountTable[A], key: A): bool =
|
||||
## Returns true if `key` is in the table `t`.
|
||||
@@ -2566,7 +2564,7 @@ proc `==`*[A](s, t: CountTable[A]): bool =
|
||||
equalsImpl(s, t)
|
||||
|
||||
|
||||
iterator pairs*[A](t: CountTable[A]): (A, int) =
|
||||
iterator pairs*[A](t: CountTable[A]): (lent A, int) =
|
||||
## Iterates over any `(key, value)` pair in the table `t`.
|
||||
##
|
||||
## See also:
|
||||
@@ -2705,7 +2703,7 @@ proc newCountTable*[A](keys: openArray[A]): CountTableRef[A] =
|
||||
{.noSideEffect.}:
|
||||
for key in items(keys): result.inc(key)
|
||||
|
||||
proc `[]`*[A](t: CountTableRef[A], key: A): int =
|
||||
proc `[]`*[A](t: CountTableRef[A], key: sink A): int =
|
||||
## Retrieves the value at `t[key]` if `key` is in `t`.
|
||||
## Otherwise `0` is returned.
|
||||
##
|
||||
@@ -2847,7 +2845,7 @@ proc `==`*[A](s, t: CountTableRef[A]): bool =
|
||||
else: result = s[] == t[]
|
||||
|
||||
|
||||
iterator pairs*[A](t: CountTableRef[A]): (A, int) =
|
||||
iterator pairs*[A](t: CountTableRef[A]): (lent A, int) =
|
||||
## Iterates over any `(key, value)` pair in the table `t`.
|
||||
##
|
||||
## See also:
|
||||
@@ -2955,16 +2953,19 @@ iterator mvalues*[A](t: CountTableRef[A]): var int =
|
||||
assert(len(t) == L, "the length of the table changed while iterating over it")
|
||||
|
||||
proc hash*[K,V](s: Table[K,V]): Hash =
|
||||
result = Hash(0)
|
||||
for p in pairs(s):
|
||||
result = result xor hash(p)
|
||||
result = !$result
|
||||
|
||||
proc hash*[K,V](s: OrderedTable[K,V]): Hash =
|
||||
result = Hash(0)
|
||||
for p in pairs(s):
|
||||
result = result !& hash(p)
|
||||
result = !$result
|
||||
|
||||
proc hash*[V](s: CountTable[V]): Hash =
|
||||
result = Hash(0)
|
||||
for p in pairs(s):
|
||||
result = result xor hash(p)
|
||||
result = !$result
|
||||
|
||||
@@ -46,18 +46,15 @@ type
|
||||
|
||||
func complex*[T: SomeFloat](re: T; im: T = 0.0): Complex[T] =
|
||||
## Returns a `Complex[T]` with real part `re` and imaginary part `im`.
|
||||
result.re = re
|
||||
result.im = im
|
||||
result = Complex[T](re: re, im: im)
|
||||
|
||||
func complex32*(re: float32; im: float32 = 0.0): Complex32 =
|
||||
## Returns a `Complex32` with real part `re` and imaginary part `im`.
|
||||
result.re = re
|
||||
result.im = im
|
||||
result = Complex32(re: re, im: im)
|
||||
|
||||
func complex64*(re: float64; im: float64 = 0.0): Complex64 =
|
||||
## Returns a `Complex64` with real part `re` and imaginary part `im`.
|
||||
result.re = re
|
||||
result.im = im
|
||||
result = Complex64(re: re, im: im)
|
||||
|
||||
template im*(arg: typedesc[float32]): Complex32 = complex32(0, 1)
|
||||
## Returns the imaginary unit (`complex32(0, 1)`).
|
||||
@@ -85,15 +82,16 @@ func sgn*[T](z: Complex[T]): Complex[T] =
|
||||
let a = abs(z)
|
||||
if a != 0:
|
||||
result = z / a
|
||||
else:
|
||||
result = Complex[T]()
|
||||
|
||||
func conjugate*[T](z: Complex[T]): Complex[T] =
|
||||
## Returns the complex conjugate of `z` (`complex(z.re, -z.im)`).
|
||||
result.re = z.re
|
||||
result.im = -z.im
|
||||
result = Complex[T](re: z.re, im: -z.im)
|
||||
|
||||
func inv*[T](z: Complex[T]): Complex[T] =
|
||||
## Returns the multiplicative inverse of `z` (`1/z`).
|
||||
conjugate(z) / abs2(z)
|
||||
result = conjugate(z) / abs2(z)
|
||||
|
||||
func `==`*[T](x, y: Complex[T]): bool =
|
||||
## Compares two complex numbers for equality.
|
||||
@@ -101,58 +99,48 @@ func `==`*[T](x, y: Complex[T]): bool =
|
||||
|
||||
func `+`*[T](x: T; y: Complex[T]): Complex[T] =
|
||||
## Adds a real number to a complex number.
|
||||
result.re = x + y.re
|
||||
result.im = y.im
|
||||
result = Complex[T](re: x + y.re, im: y.im)
|
||||
|
||||
func `+`*[T](x: Complex[T]; y: T): Complex[T] =
|
||||
## Adds a complex number to a real number.
|
||||
result.re = x.re + y
|
||||
result.im = x.im
|
||||
result = Complex[T](re: x.re + y, im: x.im)
|
||||
|
||||
func `+`*[T](x, y: Complex[T]): Complex[T] =
|
||||
## Adds two complex numbers.
|
||||
result.re = x.re + y.re
|
||||
result.im = x.im + y.im
|
||||
result = Complex[T](re: x.re + y.re, im: x.im + y.im)
|
||||
|
||||
func `-`*[T](z: Complex[T]): Complex[T] =
|
||||
## Unary minus for complex numbers.
|
||||
result.re = -z.re
|
||||
result.im = -z.im
|
||||
result = Complex[T](re: -z.re, im: -z.im)
|
||||
|
||||
func `-`*[T](x: T; y: Complex[T]): Complex[T] =
|
||||
## Subtracts a complex number from a real number.
|
||||
result.re = x - y.re
|
||||
result.im = -y.im
|
||||
result = Complex[T](re: x - y.re, im: -y.im)
|
||||
|
||||
func `-`*[T](x: Complex[T]; y: T): Complex[T] =
|
||||
## Subtracts a real number from a complex number.
|
||||
result.re = x.re - y
|
||||
result.im = x.im
|
||||
result = Complex[T](re: x.re - y, im: x.im)
|
||||
|
||||
func `-`*[T](x, y: Complex[T]): Complex[T] =
|
||||
## Subtracts two complex numbers.
|
||||
result.re = x.re - y.re
|
||||
result.im = x.im - y.im
|
||||
result = Complex[T](re: x.re - y.re, im: x.im - y.im)
|
||||
|
||||
func `*`*[T](x: T; y: Complex[T]): Complex[T] =
|
||||
## Multiplies a real number with a complex number.
|
||||
result.re = x * y.re
|
||||
result.im = x * y.im
|
||||
result = Complex[T](re: x * y.re, im: x * y.im)
|
||||
|
||||
func `*`*[T](x: Complex[T]; y: T): Complex[T] =
|
||||
## Multiplies a complex number with a real number.
|
||||
result.re = x.re * y
|
||||
result.im = x.im * y
|
||||
result = Complex[T](re: x.re * y, im: x.im * y)
|
||||
|
||||
func `*`*[T](x, y: Complex[T]): Complex[T] =
|
||||
## Multiplies two complex numbers.
|
||||
result.re = x.re * y.re - x.im * y.im
|
||||
result.im = x.im * y.re + x.re * y.im
|
||||
result = Complex[T](re: x.re * y.re - x.im * y.im,
|
||||
im: x.im * y.re + x.re * y.im)
|
||||
|
||||
func `/`*[T](x: Complex[T]; y: T): Complex[T] =
|
||||
## Divides a complex number by a real number.
|
||||
result.re = x.re / y
|
||||
result.im = x.im / y
|
||||
result = Complex[T](re: x.re / y, im: x.im / y)
|
||||
|
||||
func `/`*[T](x: T; y: Complex[T]): Complex[T] =
|
||||
## Divides a real number by a complex number.
|
||||
@@ -202,10 +190,9 @@ func sqrt*[T](z: Complex[T]): Complex[T] =
|
||||
w = sqrt(y) * sqrt(0.5 * (r + sqrt(1.0 + r * r)))
|
||||
|
||||
if z.re >= 0.0:
|
||||
result.re = w
|
||||
result.im = z.im / (w * 2.0)
|
||||
result = Complex[T](re: w, im: z.im / (w * 2.0))
|
||||
else:
|
||||
result.im = if z.im >= 0.0: w else: -w
|
||||
result = Complex[T](im: if z.im >= 0.0: w else: -w)
|
||||
result.re = z.im / (result.im + result.im)
|
||||
|
||||
func exp*[T](z: Complex[T]): Complex[T] =
|
||||
@@ -213,15 +200,13 @@ func exp*[T](z: Complex[T]): Complex[T] =
|
||||
let
|
||||
rho = exp(z.re)
|
||||
theta = z.im
|
||||
result.re = rho * cos(theta)
|
||||
result.im = rho * sin(theta)
|
||||
result = Complex[T](re: rho * cos(theta), im: rho * sin(theta))
|
||||
|
||||
func ln*[T](z: Complex[T]): Complex[T] =
|
||||
## Returns the
|
||||
## ([principal value](https://en.wikipedia.org/wiki/Complex_logarithm#Principal_value)
|
||||
## of the) natural logarithm of `z`.
|
||||
result.re = ln(abs(z))
|
||||
result.im = arctan2(z.im, z.re)
|
||||
result = Complex[T](re: ln(abs(z)), im: arctan2(z.im, z.re))
|
||||
|
||||
func log10*[T](z: Complex[T]): Complex[T] =
|
||||
## Returns the logarithm base 10 of `z`.
|
||||
@@ -241,11 +226,9 @@ func pow*[T](x, y: Complex[T]): Complex[T] =
|
||||
## `x` raised to the power of `y`.
|
||||
if x.re == 0.0 and x.im == 0.0:
|
||||
if y.re == 0.0 and y.im == 0.0:
|
||||
result.re = 1.0
|
||||
result.im = 0.0
|
||||
result = Complex[T](re: 1.0, im: 0.0)
|
||||
else:
|
||||
result.re = 0.0
|
||||
result.im = 0.0
|
||||
result = Complex[T](re: 0.0, im: 0.0)
|
||||
elif y.im == 0.0:
|
||||
if y.re == 1.0:
|
||||
result = x
|
||||
@@ -257,8 +240,7 @@ func pow*[T](x, y: Complex[T]): Complex[T] =
|
||||
result = sqrt(x)
|
||||
elif x.im == 0.0:
|
||||
# Revert to real pow when both base and exponent are real
|
||||
result.re = pow(x.re, y.re)
|
||||
result.im = 0.0
|
||||
result = Complex[T](re: pow(x.re, y.re), im: 0.0)
|
||||
else:
|
||||
# Special case when the exponent is real
|
||||
let
|
||||
@@ -266,8 +248,7 @@ func pow*[T](x, y: Complex[T]): Complex[T] =
|
||||
theta = arctan2(x.im, x.re)
|
||||
s = pow(rho, y.re)
|
||||
r = y.re * theta
|
||||
result.re = s * cos(r)
|
||||
result.im = s * sin(r)
|
||||
result = Complex[T](re: s * cos(r), im: s * sin(r))
|
||||
elif x.im == 0.0 and x.re == E:
|
||||
# Special case Euler's formula
|
||||
result = exp(y)
|
||||
@@ -277,18 +258,15 @@ func pow*[T](x, y: Complex[T]): Complex[T] =
|
||||
theta = arctan2(x.im, x.re)
|
||||
s = pow(rho, y.re) * exp(-y.im * theta)
|
||||
r = y.re * theta + y.im * ln(rho)
|
||||
result.re = s * cos(r)
|
||||
result.im = s * sin(r)
|
||||
result = Complex[T](re: s * cos(r), im: s * sin(r))
|
||||
|
||||
func pow*[T](x: Complex[T]; y: T): Complex[T] =
|
||||
## The complex number `x` raised to the power of the real number `y`.
|
||||
pow(x, complex[T](y))
|
||||
|
||||
|
||||
func sin*[T](z: Complex[T]): Complex[T] =
|
||||
## Returns the sine of `z`.
|
||||
result.re = sin(z.re) * cosh(z.im)
|
||||
result.im = cos(z.re) * sinh(z.im)
|
||||
result = Complex[T](re: sin(z.re) * cosh(z.im), im: cos(z.re) * sinh(z.im))
|
||||
|
||||
func arcsin*[T](z: Complex[T]): Complex[T] =
|
||||
## Returns the inverse sine of `z`.
|
||||
@@ -296,8 +274,9 @@ func arcsin*[T](z: Complex[T]): Complex[T] =
|
||||
|
||||
func cos*[T](z: Complex[T]): Complex[T] =
|
||||
## Returns the cosine of `z`.
|
||||
result.re = cos(z.re) * cosh(z.im)
|
||||
result.im = -sin(z.re) * sinh(z.im)
|
||||
result = Complex[T](re: cos(z.re) * cosh(z.im),
|
||||
im: -sin(z.re) * sinh(z.im)
|
||||
)
|
||||
|
||||
func arccos*[T](z: Complex[T]): Complex[T] =
|
||||
## Returns the inverse cosine of `z`.
|
||||
|
||||
@@ -1213,7 +1213,7 @@ proc request*(client: HttpClient | AsyncHttpClient, url: Uri | string,
|
||||
redirectBody = body
|
||||
else:
|
||||
# Unreachable
|
||||
doAssert(false)
|
||||
raiseAssert "unreachable"
|
||||
|
||||
# Check if the redirection is to the same domain or a sub-domain (foo.com
|
||||
# -> sub.foo.com)
|
||||
|
||||
@@ -1256,7 +1256,7 @@ proc foldObjectBody(dst, typeNode, tmpSym, jsonNode, jsonPath, originalJsonPathL
|
||||
when nimvm:
|
||||
when isRefSkipDistinct(`tmpSym`.`fieldSym`):
|
||||
# workaround #12489
|
||||
var tmp: `fieldType`
|
||||
var tmp: `fieldType` = default(typeof(`fieldType`))
|
||||
initFromJson(tmp, getOrDefault(`jsonNode`,`fieldNameLit`), `jsonPath`)
|
||||
`tmpSym`.`fieldSym` = tmp
|
||||
else:
|
||||
@@ -1272,7 +1272,7 @@ proc foldObjectBody(dst, typeNode, tmpSym, jsonNode, jsonPath, originalJsonPathL
|
||||
let kindType = typeNode[0][1]
|
||||
let kindOffsetLit = newLit(uint(getOffset(kindSym)))
|
||||
dst.add quote do:
|
||||
var kindTmp: `kindType`
|
||||
var kindTmp: `kindType` = default(typeof(`kindType`))
|
||||
jsonPath.add `kindPathLit`
|
||||
initFromJson(kindTmp, `jsonNode`[`kindNameLit`], `jsonPath`)
|
||||
jsonPath.setLen `originalJsonPathLen`
|
||||
|
||||
@@ -312,7 +312,7 @@ proc store*[T](s: Stream, data: sink T) =
|
||||
storeAny(s, toAny(d), stored)
|
||||
|
||||
proc loadVM[T](typ: typedesc[T], x: T): string =
|
||||
discard "the implementation is in the compiler/vmops"
|
||||
raiseAssert "the implementation is in the compiler/vmops"
|
||||
|
||||
proc `$$`*[T](x: sink T): string =
|
||||
## Returns a string representation of `x` (serialization, marshalling).
|
||||
@@ -343,7 +343,7 @@ proc `$$`*[T](x: sink T): string =
|
||||
result = s.data
|
||||
|
||||
proc toVM[T](typ: typedesc[T], data: string): T =
|
||||
discard "the implementation is in the compiler/vmops"
|
||||
raiseAssert "the implementation is in the compiler/vmops"
|
||||
|
||||
proc to*[T](data: string): T =
|
||||
## Reads data and transforms it to a type `T` (deserialization, unmarshalling).
|
||||
@@ -363,5 +363,6 @@ proc to*[T](data: string): T =
|
||||
when nimvm:
|
||||
result = toVM(T, data)
|
||||
else:
|
||||
result = default(T)
|
||||
var tab = initTable[BiggestInt, pointer]()
|
||||
loadAny(newStringStream(data), toAny(result), tab)
|
||||
|
||||
@@ -105,7 +105,7 @@ when not defined(js) and not defined(nimscript): # C
|
||||
when compileOption("overflowChecks"):
|
||||
if y == 0:
|
||||
raise new(DivByZeroDefect)
|
||||
elif (x == T.low and y == -1.T):
|
||||
elif (x == T.low and int64(y) == -1):
|
||||
raise new(OverflowDefect)
|
||||
let res = divmod_c(x, y)
|
||||
result[0] = res.quot
|
||||
@@ -989,8 +989,9 @@ func frexp*[T: float32|float64](x: T): tuple[frac: T, exp: int] {.inline.} =
|
||||
doAssert frexp(Inf).frac == Inf # +- Inf preserved
|
||||
doAssert frexp(NaN).frac.isNaN
|
||||
|
||||
result = default(tuple[frac: T, exp: int])
|
||||
when not defined(js):
|
||||
var exp: cint
|
||||
var exp: cint = cint(0)
|
||||
result.frac = c_frexp2(x, exp)
|
||||
result.exp = exp
|
||||
else:
|
||||
@@ -1068,10 +1069,8 @@ func splitDecimal*[T: float32|float64](x: T): tuple[intpart: T, floatpart: T] =
|
||||
runnableExamples:
|
||||
doAssert splitDecimal(5.25) == (intpart: 5.0, floatpart: 0.25)
|
||||
doAssert splitDecimal(-2.73) == (intpart: -2.0, floatpart: -0.73)
|
||||
|
||||
var
|
||||
absolute: T
|
||||
absolute = abs(x)
|
||||
result = default(tuple[intpart: T, floatpart: T])
|
||||
var absolute: T = abs(x)
|
||||
result.intpart = floor(absolute)
|
||||
result.floatpart = absolute - result.intpart
|
||||
if x < 0:
|
||||
@@ -1128,7 +1127,7 @@ func sum*[T](x: openArray[T]): T =
|
||||
runnableExamples:
|
||||
doAssert sum([1, 2, 3, 4]) == 10
|
||||
doAssert sum([-4, 3, 5]) == 4
|
||||
|
||||
result = default(T)
|
||||
for i in items(x): result = result + i
|
||||
|
||||
func prod*[T](x: openArray[T]): T =
|
||||
@@ -1187,7 +1186,7 @@ func cumsummed*[T](x: openArray[T]): seq[T] =
|
||||
## * `cumsum func <#cumsum,openArray[T]>`_ for the in-place version
|
||||
runnableExamples:
|
||||
doAssert cumsummed([1, 2, 3, 4]) == @[1, 3, 6, 10]
|
||||
|
||||
result = @[]
|
||||
let xLen = x.len
|
||||
if xLen == 0:
|
||||
return @[]
|
||||
|
||||
@@ -186,6 +186,7 @@ proc parseHex*[T: SomeInteger](s: openArray[char], number: var T, maxLen = 0): i
|
||||
var num64: int64
|
||||
doAssert parseHex("4E69ED4E69ED", num64) == 12
|
||||
doAssert num64 == 86216859871725
|
||||
result = 0
|
||||
var i = 0
|
||||
var output = T(0)
|
||||
var foundDigit = false
|
||||
|
||||
@@ -563,6 +563,8 @@ template matchOrParse(mopProc: untyped) =
|
||||
# are provided which just return *discard*.
|
||||
|
||||
proc mopProc(s: string, p: Peg, start: int, c: var Captures): int {.gcsafe, raises: [].} =
|
||||
result = 0
|
||||
|
||||
proc matchBackRef(s: string, p: Peg, start: int, c: var Captures): int =
|
||||
# Parse handler code must run in an *of* clause of its own for each
|
||||
# *PegKind*, so we encapsulate the identical clause body for
|
||||
@@ -579,7 +581,7 @@ template matchOrParse(mopProc: untyped) =
|
||||
n = Peg(kind: pkTerminalIgnoreStyle, term: s.substr(a, b))
|
||||
of pkBackRefIgnoreCase:
|
||||
n = Peg(kind: pkTerminalIgnoreCase, term: s.substr(a, b))
|
||||
else: assert(false, "impossible case")
|
||||
else: raiseAssert "impossible case"
|
||||
mopProc(s, n, start, c)
|
||||
|
||||
case p.kind
|
||||
@@ -695,7 +697,7 @@ template matchOrParse(mopProc: untyped) =
|
||||
enter(pkTerminalIgnoreStyle, s, p, start)
|
||||
var
|
||||
i = 0
|
||||
a, b: Rune
|
||||
a, b: Rune = default(Rune)
|
||||
result = start
|
||||
while i < len(p.term):
|
||||
while i < len(p.term):
|
||||
@@ -1067,7 +1069,7 @@ template eventParser*(pegAst, handlers: untyped): (proc(s: string): int) =
|
||||
proc parser(s: string): int {.gensym.} =
|
||||
# the proc to be returned
|
||||
var
|
||||
ms: array[MaxSubpatterns, (int, int)]
|
||||
ms: array[MaxSubpatterns, (int, int)] = default(array[MaxSubpatterns, (int, int)])
|
||||
cs = Captures(matches: ms, ml: 0, origStart: 0)
|
||||
rawParse(s, pegAst, 0, cs)
|
||||
parser
|
||||
|
||||
@@ -228,6 +228,7 @@ proc skipRandomNumbers*(s: var Rand) =
|
||||
|
||||
proc rand[T: uint | uint64](r: var Rand; max: T): T =
|
||||
# xxx export in future work
|
||||
result = default(T)
|
||||
if max == 0: return
|
||||
else:
|
||||
let max = uint64(max)
|
||||
|
||||
@@ -57,8 +57,7 @@ func initRational*[T: SomeInteger](num, den: T): Rational[T] =
|
||||
##
|
||||
## **Note:** `den != 0` is not checked when assertions are turned off.
|
||||
assert(den != 0, "a denominator of zero is invalid")
|
||||
result.num = num
|
||||
result.den = den
|
||||
result = Rational[T](num: num, den: den)
|
||||
reduce(result)
|
||||
|
||||
func `//`*[T](num, den: T): Rational[T] =
|
||||
@@ -80,9 +79,7 @@ func toRational*[T: SomeInteger](x: T): Rational[T] =
|
||||
## Converts some integer `x` to a rational number.
|
||||
runnableExamples:
|
||||
doAssert toRational(42) == 42 // 1
|
||||
|
||||
result.num = x
|
||||
result.den = 1
|
||||
result = Rational[T](num: x, den: 1)
|
||||
|
||||
func toRational*(x: float,
|
||||
n: int = high(int) shr (sizeof(int) div 2 * 8)): Rational[int] =
|
||||
@@ -125,19 +122,18 @@ func toInt*[T](x: Rational[T]): int =
|
||||
func `+`*[T](x, y: Rational[T]): Rational[T] =
|
||||
## Adds two rational numbers.
|
||||
let common = lcm(x.den, y.den)
|
||||
result.num = common div x.den * x.num + common div y.den * y.num
|
||||
result.den = common
|
||||
result = Rational[T](num: common div x.den * x.num + common div y.den * y.num,
|
||||
den: common
|
||||
)
|
||||
reduce(result)
|
||||
|
||||
func `+`*[T](x: Rational[T], y: T): Rational[T] =
|
||||
## Adds the rational `x` to the int `y`.
|
||||
result.num = x.num + y * x.den
|
||||
result.den = x.den
|
||||
result = Rational[T](num: x.num + y * x.den, den: x.den)
|
||||
|
||||
func `+`*[T](x: T, y: Rational[T]): Rational[T] =
|
||||
## Adds the int `x` to the rational `y`.
|
||||
result.num = x * y.den + y.num
|
||||
result.den = y.den
|
||||
result = Rational[T](num: x * y.den + y.num, den: y.den)
|
||||
|
||||
func `+=`*[T](x: var Rational[T], y: Rational[T]) =
|
||||
## Adds the rational `y` to the rational `x` in-place.
|
||||
@@ -152,25 +148,23 @@ func `+=`*[T](x: var Rational[T], y: T) =
|
||||
|
||||
func `-`*[T](x: Rational[T]): Rational[T] =
|
||||
## Unary minus for rational numbers.
|
||||
result.num = -x.num
|
||||
result.den = x.den
|
||||
result = Rational[T](num: -x.num, den: x.den)
|
||||
|
||||
func `-`*[T](x, y: Rational[T]): Rational[T] =
|
||||
## Subtracts two rational numbers.
|
||||
let common = lcm(x.den, y.den)
|
||||
result.num = common div x.den * x.num - common div y.den * y.num
|
||||
result.den = common
|
||||
result = Rational[T](num: common div x.den * x.num - common div y.den * y.num,
|
||||
den: common
|
||||
)
|
||||
reduce(result)
|
||||
|
||||
func `-`*[T](x: Rational[T], y: T): Rational[T] =
|
||||
## Subtracts the int `y` from the rational `x`.
|
||||
result.num = x.num - y * x.den
|
||||
result.den = x.den
|
||||
result = Rational[T](num: x.num - y * x.den, den: x.den)
|
||||
|
||||
func `-`*[T](x: T, y: Rational[T]): Rational[T] =
|
||||
## Subtracts the rational `y` from the int `x`.
|
||||
result.num = x * y.den - y.num
|
||||
result.den = y.den
|
||||
result = Rational[T](num: x * y.den - y.num, den: y.den)
|
||||
|
||||
func `-=`*[T](x: var Rational[T], y: Rational[T]) =
|
||||
## Subtracts the rational `y` from the rational `x` in-place.
|
||||
@@ -185,20 +179,17 @@ func `-=`*[T](x: var Rational[T], y: T) =
|
||||
|
||||
func `*`*[T](x, y: Rational[T]): Rational[T] =
|
||||
## Multiplies two rational numbers.
|
||||
result.num = x.num * y.num
|
||||
result.den = x.den * y.den
|
||||
result = Rational[T](num: x.num * y.num, den: x.den * y.den)
|
||||
reduce(result)
|
||||
|
||||
func `*`*[T](x: Rational[T], y: T): Rational[T] =
|
||||
## Multiplies the rational `x` with the int `y`.
|
||||
result.num = x.num * y
|
||||
result.den = x.den
|
||||
result = Rational[T](num: x.num * y, den: x.den)
|
||||
reduce(result)
|
||||
|
||||
func `*`*[T](x: T, y: Rational[T]): Rational[T] =
|
||||
## Multiplies the int `x` with the rational `y`.
|
||||
result.num = x * y.num
|
||||
result.den = y.den
|
||||
result = Rational[T](num: x * y.num, den: y.den)
|
||||
reduce(result)
|
||||
|
||||
func `*=`*[T](x: var Rational[T], y: Rational[T]) =
|
||||
@@ -216,30 +207,25 @@ func reciprocal*[T](x: Rational[T]): Rational[T] =
|
||||
## Calculates the reciprocal of `x` (`1/x`).
|
||||
## If `x` is 0, raises `DivByZeroDefect`.
|
||||
if x.num > 0:
|
||||
result.num = x.den
|
||||
result.den = x.num
|
||||
result = Rational[T](num: x.den, den: x.num)
|
||||
elif x.num < 0:
|
||||
result.num = -x.den
|
||||
result.den = -x.num
|
||||
result = Rational[T](num: -x.den, den: -x.num)
|
||||
else:
|
||||
raise newException(DivByZeroDefect, "division by zero")
|
||||
|
||||
func `/`*[T](x, y: Rational[T]): Rational[T] =
|
||||
## Divides the rational `x` by the rational `y`.
|
||||
result.num = x.num * y.den
|
||||
result.den = x.den * y.num
|
||||
result = Rational[T](num: x.num * y.den, den: x.den * y.num)
|
||||
reduce(result)
|
||||
|
||||
func `/`*[T](x: Rational[T], y: T): Rational[T] =
|
||||
## Divides the rational `x` by the int `y`.
|
||||
result.num = x.num
|
||||
result.den = x.den * y
|
||||
result = Rational[T](num: x.num, den: x.den * y)
|
||||
reduce(result)
|
||||
|
||||
func `/`*[T](x: T, y: Rational[T]): Rational[T] =
|
||||
## Divides the int `x` by the rational `y`.
|
||||
result.num = x * y.den
|
||||
result.den = y.num
|
||||
result = Rational[T](num: x * y.den, den: y.num)
|
||||
reduce(result)
|
||||
|
||||
func `/=`*[T](x: var Rational[T], y: Rational[T]) =
|
||||
@@ -277,9 +263,7 @@ func abs*[T](x: Rational[T]): Rational[T] =
|
||||
runnableExamples:
|
||||
doAssert abs(1 // 2) == 1 // 2
|
||||
doAssert abs(-1 // 2) == 1 // 2
|
||||
|
||||
result.num = abs x.num
|
||||
result.den = abs x.den
|
||||
result = Rational[T](num: abs x.num, den: abs x.den)
|
||||
|
||||
func `div`*[T: SomeInteger](x, y: Rational[T]): T =
|
||||
## Computes the rational truncated division.
|
||||
@@ -311,6 +295,7 @@ func floorMod*[T: SomeInteger](x, y: Rational[T]): Rational[T] =
|
||||
func hash*[T](x: Rational[T]): Hash =
|
||||
## Computes the hash for the rational `x`.
|
||||
# reduce first so that hash(x) == hash(y) for x == y
|
||||
result = Hash(0)
|
||||
var copy = x
|
||||
reduce(copy)
|
||||
|
||||
@@ -331,10 +316,8 @@ func `^`*[T: SomeInteger](x: Rational[T], y: T): Rational[T] =
|
||||
doAssert (-3 // 5) ^ -2 == (25 // 9)
|
||||
|
||||
if y >= 0:
|
||||
result.num = x.num ^ y
|
||||
result.den = x.den ^ y
|
||||
result = Rational[T](num: x.num ^ y, den: x.den ^ y)
|
||||
else:
|
||||
result.num = x.den ^ -y
|
||||
result.den = x.num ^ -y
|
||||
result = Rational[T](num: x.den ^ -y, den: x.num ^ -y)
|
||||
# Note that all powers of reduced rationals are already reduced,
|
||||
# so we don't need to call reduce() here
|
||||
|
||||
@@ -336,7 +336,7 @@ else:
|
||||
elif defined(zephyr) or defined(freertos):
|
||||
FD_MAX
|
||||
else:
|
||||
var fdLim: RLimit
|
||||
var fdLim: RLimit = default(RLimit)
|
||||
var res = int(getrlimit(RLIMIT_NOFILE, fdLim))
|
||||
if res >= 0:
|
||||
res = int(fdLim.rlim_cur) - 1
|
||||
|
||||
@@ -109,7 +109,7 @@ import std/private/since
|
||||
import std/exitprocs
|
||||
|
||||
when defined(nimPreviewSlimSystem):
|
||||
import std/assertions
|
||||
import std/[assertions, syncio]
|
||||
|
||||
import std/[macros, strutils, streams, times, sets, sequtils]
|
||||
|
||||
@@ -665,9 +665,7 @@ macro check*(conditions: untyped): untyped =
|
||||
checkpoint(name & " was " & $value)
|
||||
|
||||
proc inspectArgs(exp: NimNode): tuple[assigns, check, printOuts: NimNode] =
|
||||
result.check = copyNimTree(exp)
|
||||
result.assigns = newNimNode(nnkStmtList)
|
||||
result.printOuts = newNimNode(nnkStmtList)
|
||||
result = (newNimNode(nnkStmtList), copyNimTree(exp), newNimNode(nnkStmtList))
|
||||
|
||||
var counter = 0
|
||||
|
||||
|
||||
@@ -110,6 +110,10 @@ when defined(js):
|
||||
}
|
||||
if (Number.isSafeInteger(`a`))
|
||||
`result` = `a` === 0 && 1 / `a` < 0 ? "-0.0" : `a`+".0";
|
||||
else if (isNaN(`a`)) // Number.isNaN is since ES6
|
||||
`result` = "nan"; // or it'll be "NaN"
|
||||
else if (!isFinite(`a`)) // Number.isFinite newer but unnecessary here
|
||||
`result` = `a` > 0 ? "inf" : "-inf"; // or it'll be [-]Infinity
|
||||
else {
|
||||
`result` = `a`+"";
|
||||
if(nimOnlyDigitsOrMinus(`result`)){
|
||||
@@ -140,4 +144,5 @@ proc addFloat*(result: var string; x: float | float32) {.inline.} =
|
||||
when defined(nimPreviewSlimSystem):
|
||||
func `$`*(x: float | float32): string =
|
||||
## Outplace version of `addFloat`.
|
||||
result = ""
|
||||
result.addFloat(x)
|
||||
|
||||
@@ -186,7 +186,7 @@ proc discKeyMatch[T](obj: T, json: JsonNode, key: static string): bool =
|
||||
if not json.hasKey key:
|
||||
return true
|
||||
let field = accessField(obj, key)
|
||||
var jsonVal: typeof(field)
|
||||
var jsonVal: typeof(field) = default(typeof(field))
|
||||
fromJson(jsonVal, json[key])
|
||||
if jsonVal != field:
|
||||
return false
|
||||
@@ -295,6 +295,7 @@ proc fromJson*[T](a: var T, b: JsonNode, opt = Joptions()) =
|
||||
|
||||
proc jsonTo*(b: JsonNode, T: typedesc, opt = Joptions()): T =
|
||||
## reverse of `toJson`
|
||||
result = default(T)
|
||||
fromJson(result, b, opt)
|
||||
|
||||
proc toJson*[T](a: T, opt = initToJsonOptions()): JsonNode =
|
||||
|
||||
@@ -462,7 +462,7 @@ proc union*[A](s1, s2: PackedSet[A]): PackedSet[A] =
|
||||
c = union(a, b)
|
||||
assert c.len == 5
|
||||
assert c == [1, 2, 3, 4, 5].toPackedSet
|
||||
|
||||
result = default(PackedSet[A])
|
||||
result.assign(s1)
|
||||
incl(result, s2)
|
||||
|
||||
@@ -509,7 +509,7 @@ proc symmetricDifference*[A](s1, s2: PackedSet[A]): PackedSet[A] =
|
||||
c = symmetricDifference(a, b)
|
||||
assert c.len == 4
|
||||
assert c == [1, 2, 4, 5].toPackedSet
|
||||
|
||||
result = default(PackedSet[A])
|
||||
result.assign(s1)
|
||||
for item in s2.items:
|
||||
if containsOrIncl(result, item):
|
||||
|
||||
@@ -63,7 +63,7 @@ proc threadFunc(obj: ptr seq[int]) {.thread.} =
|
||||
proc threadHandler() =
|
||||
var thr: array[0..4, Thread[ptr seq[int]]]
|
||||
var s = newSeq[int]()
|
||||
|
||||
|
||||
for i in 0..high(thr):
|
||||
createThread(thr[i], threadFunc, s.addr)
|
||||
joinThreads(thr)
|
||||
@@ -137,6 +137,7 @@ when defined(zephyr):
|
||||
{.push stack_trace:off.}
|
||||
when defined(windows):
|
||||
proc threadProcWrapper[TArg](closure: pointer): int32 {.stdcall.} =
|
||||
result = 0'i32
|
||||
nimThreadProcWrapperBody(closure)
|
||||
# implicitly return 0
|
||||
elif defined(genode):
|
||||
@@ -144,6 +145,7 @@ elif defined(genode):
|
||||
nimThreadProcWrapperBody(closure)
|
||||
else:
|
||||
proc threadProcWrapper[TArg](closure: pointer): pointer {.noconv.} =
|
||||
result = nil
|
||||
nimThreadProcWrapperBody(closure)
|
||||
{.pop.}
|
||||
|
||||
@@ -164,7 +166,7 @@ when hostOS == "windows":
|
||||
|
||||
proc joinThreads*[TArg](t: varargs[Thread[TArg]]) =
|
||||
## Waits for every thread in `t` to finish.
|
||||
var a: array[MAXIMUM_WAIT_OBJECTS, SysThread]
|
||||
var a: array[MAXIMUM_WAIT_OBJECTS, SysThread] = default(array[MAXIMUM_WAIT_OBJECTS, SysThread])
|
||||
var k = 0
|
||||
while k < len(t):
|
||||
var count = min(len(t) - k, MAXIMUM_WAIT_OBJECTS)
|
||||
@@ -220,7 +222,7 @@ when hostOS == "windows":
|
||||
when TArg isnot void: t.data = param
|
||||
t.dataFn = tp
|
||||
when hasSharedHeap: t.core.stackSize = ThreadStackSize
|
||||
var dummyThreadId: int32
|
||||
var dummyThreadId: int32 = 0'i32
|
||||
t.sys = createThread(nil, ThreadStackSize, threadProcWrapper[TArg],
|
||||
addr(t), 0'i32, dummyThreadId)
|
||||
if t.sys <= 0:
|
||||
|
||||
@@ -58,7 +58,7 @@ proc finalize(n: NimNode, lhs: NimNode, level: int): NimNode =
|
||||
if level == 0:
|
||||
result = quote: `lhs` = `n`
|
||||
else:
|
||||
result = quote: (let `lhs` = `n`)
|
||||
result = quote: (var `lhs` = `n`)
|
||||
|
||||
proc process(n: NimNode, lhs: NimNode, label: NimNode, level: int): NimNode =
|
||||
result = nil
|
||||
@@ -78,7 +78,7 @@ proc process(n: NimNode, lhs: NimNode, label: NimNode, level: int): NimNode =
|
||||
let check = it[1]
|
||||
let okSet = check[1]
|
||||
let kind1 = check[2]
|
||||
let tmp = genSym(nskLet, "tmpCase")
|
||||
let tmp = genSym(nskVar, "tmpCase")
|
||||
let body = process(objRef, tmp, label, level + 1)
|
||||
let tmp3 = nnkDerefExpr.newTree(tmp)
|
||||
it[0][0] = tmp3
|
||||
@@ -92,7 +92,7 @@ proc process(n: NimNode, lhs: NimNode, label: NimNode, level: int): NimNode =
|
||||
`assgn`
|
||||
break
|
||||
elif it.kind in {nnkHiddenDeref, nnkDerefExpr}:
|
||||
let tmp = genSym(nskLet, "tmp")
|
||||
let tmp = genSym(nskVar, "tmp")
|
||||
let body = process(it[0], tmp, label, level + 1)
|
||||
it[0] = tmp
|
||||
let assgn = finalize(n, lhs, level)
|
||||
@@ -117,7 +117,7 @@ macro `?.`*(a: typed): auto =
|
||||
let label = genSym(nskLabel, "label")
|
||||
let body = process(a, lhs, label, 0)
|
||||
result = quote do:
|
||||
var `lhs`: type(`a`)
|
||||
var `lhs`: type(`a`) = default(type(`a`))
|
||||
block `label`:
|
||||
`body`
|
||||
`lhs`
|
||||
@@ -149,9 +149,9 @@ macro `??.`*(a: typed): Option =
|
||||
let label = genSym(nskLabel, "label")
|
||||
let body = process(a, lhs2, label, 0)
|
||||
result = quote do:
|
||||
var `lhs`: Option[type(`a`)]
|
||||
var `lhs`: Option[type(`a`)] = default(Option[type(`a`)])
|
||||
block `label`:
|
||||
var `lhs2`: type(`a`)
|
||||
var `lhs2`: type(`a`) = default(type(`a`))
|
||||
`body`
|
||||
`lhs` = option(`lhs2`)
|
||||
`lhs`
|
||||
|
||||
@@ -2357,7 +2357,7 @@ when notJSnotNims:
|
||||
else:
|
||||
let c3 = cast[proc(y: int; env: pointer): int {.nimcall.}](p)
|
||||
echo c3(3, e)
|
||||
|
||||
result = nil
|
||||
{.emit: """
|
||||
`result` = (void*)`x`.ClP_0;
|
||||
""".}
|
||||
@@ -2365,12 +2365,14 @@ when notJSnotNims:
|
||||
proc rawEnv*[T: proc {.closure.} | iterator {.closure.}](x: T): pointer {.noSideEffect, inline.} =
|
||||
## Retrieves the raw environment pointer of the closure `x`. See also `rawProc`.
|
||||
## This is not available for the JS target.
|
||||
result = nil
|
||||
{.emit: """
|
||||
`result` = `x`.ClE_0;
|
||||
""".}
|
||||
|
||||
proc finished*[T: iterator {.closure.}](x: T): bool {.noSideEffect, inline, magic: "Finished".} =
|
||||
## It can be used to determine if a first class iterator has finished.
|
||||
result = false
|
||||
when defined(js):
|
||||
# TODO: mangle `:state`
|
||||
{.emit: """
|
||||
|
||||
@@ -87,6 +87,9 @@ else:
|
||||
template count(x: Cell): untyped =
|
||||
x.rc shr rcShift
|
||||
|
||||
when not defined(nimHasQuirky):
|
||||
{.pragma: quirky.}
|
||||
|
||||
proc nimNewObj(size, alignment: int): pointer {.compilerRtl.} =
|
||||
let hdrSize = align(sizeof(RefHeader), alignment)
|
||||
let s = size + hdrSize
|
||||
@@ -190,7 +193,7 @@ proc nimRawDispose(p: pointer, alignment: int) {.compilerRtl.} =
|
||||
template `=dispose`*[T](x: owned(ref T)) = nimRawDispose(cast[pointer](x), T.alignOf)
|
||||
#proc dispose*(x: pointer) = nimRawDispose(x)
|
||||
|
||||
proc nimDestroyAndDispose(p: pointer) {.compilerRtl, raises: [].} =
|
||||
proc nimDestroyAndDispose(p: pointer) {.compilerRtl, quirky, raises: [].} =
|
||||
let rti = cast[ptr PNimTypeV2](p)
|
||||
if rti.destructor != nil:
|
||||
cast[DestructorProc](rti.destructor)(p)
|
||||
|
||||
@@ -6,11 +6,11 @@ const
|
||||
## ```
|
||||
# see also std/private/since
|
||||
|
||||
NimMinor* {.intdefine.}: int = 2
|
||||
NimMinor* {.intdefine.}: int = 3
|
||||
## is the minor number of Nim's version.
|
||||
## Odd for devel, even for releases.
|
||||
|
||||
NimPatch* {.intdefine.}: int = 2
|
||||
NimPatch* {.intdefine.}: int = 1
|
||||
## is the patch number of Nim's version.
|
||||
## Odd for devel, even for releases.
|
||||
|
||||
|
||||
@@ -112,9 +112,10 @@ proc nimToCStringConv(s: NimStringV2): cstring {.compilerproc, nonReloadable, in
|
||||
|
||||
proc appendString(dest: var NimStringV2; src: NimStringV2) {.compilerproc, inline.} =
|
||||
if src.len > 0:
|
||||
# also copy the \0 terminator:
|
||||
copyMem(unsafeAddr dest.p.data[dest.len], unsafeAddr src.p.data[0], src.len+1)
|
||||
# don't copy the \0 terminator:
|
||||
copyMem(unsafeAddr dest.p.data[dest.len], unsafeAddr src.p.data[0], src.len)
|
||||
inc dest.len, src.len
|
||||
dest.p.data[dest.len] = '\0'
|
||||
|
||||
proc appendChar(dest: var NimStringV2; c: char) {.compilerproc, inline.} =
|
||||
dest.p.data[dest.len] = c
|
||||
|
||||
@@ -68,7 +68,7 @@ else:
|
||||
when defined(nimV2):
|
||||
thrd.dataFn(thrd.data)
|
||||
else:
|
||||
var x: TArg
|
||||
var x: TArg = default(TArg)
|
||||
deepCopy(x, thrd.data)
|
||||
thrd.dataFn(x)
|
||||
except:
|
||||
|
||||
@@ -16,6 +16,8 @@ import ../compiler / [idents, llstream, ast, msgs, syntaxes, options, pathutils,
|
||||
|
||||
import parseopt, strutils, os, sequtils
|
||||
|
||||
import std/tempfiles
|
||||
|
||||
const
|
||||
Version = "0.2"
|
||||
Usage = "nimpretty - Nim Pretty Printer Version " & Version & """
|
||||
@@ -26,6 +28,7 @@ Usage:
|
||||
Options:
|
||||
--out:file set the output file (default: overwrite the input file)
|
||||
--outDir:dir set the output dir (default: overwrite the input files)
|
||||
--stdin read input from stdin and write output to stdout
|
||||
--indent:N[=0] set the number of spaces that is used for indentation
|
||||
--indent:0 means autodetection (default behaviour)
|
||||
--maxLineLen:N set the desired maximum line length (default: 80)
|
||||
@@ -84,7 +87,7 @@ proc finalCheck(content: string; origAst: PNode): bool {.nimcall.} =
|
||||
closeParser(parser)
|
||||
result = conf.errorCounter == oldErrors # and goodEnough(newAst, origAst)
|
||||
|
||||
proc prettyPrint*(infile, outfile: string, opt: PrettyOptions) =
|
||||
proc prettyPrint*(infile, outfile: string; opt: PrettyOptions) =
|
||||
var conf = newConfigRef()
|
||||
let fileIdx = fileInfoIdx(conf, AbsoluteFile infile)
|
||||
let f = splitFile(outfile.expandTilde)
|
||||
@@ -99,12 +102,28 @@ proc prettyPrint*(infile, outfile: string, opt: PrettyOptions) =
|
||||
when defined(nimpretty):
|
||||
closeEmitter(parser.em, fullAst, finalCheck)
|
||||
|
||||
proc handleStdinInput(opt: PrettyOptions) =
|
||||
var content = readAll(stdin)
|
||||
|
||||
var (cfile, path) = createTempFile("nimpretty_", ".nim")
|
||||
|
||||
writeFile(path, content)
|
||||
|
||||
prettyPrint(path, path, opt)
|
||||
|
||||
echo(readAll(cfile))
|
||||
|
||||
close(cfile)
|
||||
removeFile(path)
|
||||
|
||||
proc main =
|
||||
var outfile, outdir: string
|
||||
|
||||
var infiles = newSeq[string]()
|
||||
var outfiles = newSeq[string]()
|
||||
|
||||
var isStdin = false
|
||||
|
||||
var backup = false
|
||||
# when `on`, create a backup file of input in case
|
||||
# `prettyPrint` could overwrite it (note that the backup may happen even
|
||||
@@ -112,7 +131,6 @@ proc main =
|
||||
# --backup was un-documented (rely on git instead).
|
||||
var opt = PrettyOptions(indWidth: 0, maxLineLen: 80)
|
||||
|
||||
|
||||
for kind, key, val in getopt():
|
||||
case kind
|
||||
of cmdArgument:
|
||||
@@ -132,8 +150,15 @@ proc main =
|
||||
of "outDir", "outdir": outdir = val
|
||||
of "indent": opt.indWidth = parseInt(val)
|
||||
of "maxlinelen": opt.maxLineLen = parseInt(val)
|
||||
# "" is equal to '-' as input
|
||||
of "stdin", "": isStdin = true
|
||||
else: writeHelp()
|
||||
of cmdEnd: assert(false) # cannot happen
|
||||
|
||||
if isStdin:
|
||||
handleStdinInput(opt)
|
||||
return
|
||||
|
||||
if infiles.len == 0:
|
||||
quit "[Error] no input file."
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ pkg "hts", "nim c -o:htss src/hts.nim"
|
||||
pkg "httpauth"
|
||||
pkg "httputils"
|
||||
pkg "illwill", "nimble examples"
|
||||
pkg "inim"
|
||||
# pkg "inim"
|
||||
pkg "itertools", "nim doc src/itertools.nim"
|
||||
pkg "iterutils"
|
||||
pkg "json_rpc"
|
||||
|
||||
@@ -38,6 +38,7 @@ proc splitTestFile*(file: string): tuple[cat: string, path: string] =
|
||||
## At least one directory is required in the path, to use as a category name
|
||||
runnableExamples:
|
||||
doAssert splitTestFile("tests/fakedir/tfakename.nim") == ("fakedir", "tests/fakedir/tfakename.nim".unixToNativePath)
|
||||
result = ("", "")
|
||||
for p in file.parentDirs(inclusive = false):
|
||||
let parent = p.parentDir
|
||||
if parent.lastPathPart == testsFname:
|
||||
|
||||
@@ -6,13 +6,18 @@ proc mismatch*[T](lhs: T, rhs: T): string =
|
||||
## while avoiding pulling too many dependencies. On failure, diagnostic
|
||||
## information is provided that in particular makes it easy to spot
|
||||
## whitespace mismatches and where the mismatch is.
|
||||
result = ""
|
||||
|
||||
proc replaceInvisible(s: string): string =
|
||||
result = ""
|
||||
for a in s:
|
||||
case a
|
||||
of '\n': result.add "\\n\n"
|
||||
else: result.add a
|
||||
|
||||
proc quoted(s: string): string = result.addQuoted s
|
||||
proc quoted(s: string): string =
|
||||
result = ""
|
||||
result.addQuoted s
|
||||
|
||||
result.add '\n'
|
||||
result.add "lhs:{" & replaceInvisible(
|
||||
|
||||
20
tests/arc/t24720.nim
Normal file
20
tests/arc/t24720.nim
Normal file
@@ -0,0 +1,20 @@
|
||||
discard """
|
||||
matrix: "--mm:orc"
|
||||
output: '''
|
||||
found entry
|
||||
'''
|
||||
"""
|
||||
|
||||
import std/tables
|
||||
type NoCopies = object
|
||||
|
||||
proc `=copy`(a: var NoCopies, b: NoCopies) {.error.}
|
||||
|
||||
# bug #24720
|
||||
proc foo() =
|
||||
var t: Table[int, NoCopies]
|
||||
t[3] = NoCopies() # only moves
|
||||
for k, v in t.pairs(): # lent values, no need to copy!
|
||||
echo "found entry"
|
||||
|
||||
foo()
|
||||
@@ -1,3 +1,7 @@
|
||||
discard """
|
||||
ccodecheck: "'Result[(i_1 - 0)] = eqdup'"
|
||||
"""
|
||||
|
||||
# issue #24626
|
||||
|
||||
proc arrayWith2[T](y: T, size: static int): array[size, T] {.noinit, nodestroy, raises: [].} =
|
||||
|
||||
16
tests/arc/tvalgrind.nim
Normal file
16
tests/arc/tvalgrind.nim
Normal file
@@ -0,0 +1,16 @@
|
||||
discard """
|
||||
cmd: "nim c --mm:orc -d:useMalloc $file"
|
||||
valgrind: "true"
|
||||
"""
|
||||
|
||||
import std/streams
|
||||
|
||||
|
||||
proc foo() =
|
||||
var name = newStringStream("2r2")
|
||||
raise newException(ValueError, "sh")
|
||||
|
||||
try:
|
||||
foo()
|
||||
except:
|
||||
discard
|
||||
@@ -1,7 +1,7 @@
|
||||
discard """
|
||||
matrix: "--mm:refc"
|
||||
output: "Hello"
|
||||
ccodecheck: "\\i@'a = ((NimStringDesc*) NIM_NIL)'"
|
||||
ccodecheck: "\\i@'a_1 = ((NimStringDesc*) NIM_NIL)'"
|
||||
"""
|
||||
|
||||
proc main() =
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
discard """
|
||||
output: "1"
|
||||
cmd: r"nim c --hints:on $options --mm:refc -d:release $file"
|
||||
ccodecheck: "'NI volatile state;'"
|
||||
ccodecheck: "'NI volatile state_1;'"
|
||||
targets: "c"
|
||||
"""
|
||||
|
||||
|
||||
32
tests/ccgbugs/tunioninit.nim
Normal file
32
tests/ccgbugs/tunioninit.nim
Normal file
@@ -0,0 +1,32 @@
|
||||
# issue #20653
|
||||
|
||||
type
|
||||
EmptySeq* {.bycopy.} = object
|
||||
|
||||
ChoiceWithEmptySeq_d* {.bycopy.} = object
|
||||
a*: bool
|
||||
|
||||
INNER_C_UNION* {.bycopy, union.} = object
|
||||
a*: char
|
||||
b*: EmptySeq
|
||||
c*: byte
|
||||
d*: ChoiceWithEmptySeq_d
|
||||
|
||||
ChoiceWithEmptySeq_selection* = enum
|
||||
ChoiceWithEmptySeq_NONE,
|
||||
ChoiceWithEmptySeq_a_PRESENT,
|
||||
ChoiceWithEmptySeq_b_PRESENT,
|
||||
ChoiceWithEmptySeq_c_PRESENT,
|
||||
ChoiceWithEmptySeq_d_PRESENT
|
||||
|
||||
ChoiceWithEmptySeq* {.bycopy.} = object
|
||||
kind*: ChoiceWithEmptySeq_selection
|
||||
u*: INNER_C_UNION
|
||||
|
||||
Og_Context* {.bycopy.} = object
|
||||
state*: int
|
||||
init_done*: bool
|
||||
ch*: ChoiceWithEmptySeq
|
||||
em*: EmptySeq
|
||||
|
||||
var context* : Og_Context = Og_Context(init_done: false)
|
||||
@@ -45,3 +45,14 @@ block: # bug #22354
|
||||
|
||||
|
||||
main()
|
||||
|
||||
proc main = # bug #24677
|
||||
let NULL = 1
|
||||
doAssert NULL == 1
|
||||
|
||||
var COMMA = 1
|
||||
doAssert COMMA == 1
|
||||
|
||||
for NDEBUG in 0..2:
|
||||
doAssert NDEBUG == NDEBUG
|
||||
main()
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
discard """
|
||||
# doesn't work on macos 13 seemingly due to libc++ linking issue https://stackoverflow.com/a/77375947
|
||||
disabled: osx
|
||||
targets: cpp
|
||||
"""
|
||||
|
||||
@@ -18,21 +16,21 @@ proc initStdException(): CStdException {.importcpp: "std::exception()", construc
|
||||
proc fn() =
|
||||
let a = initRuntimeError("foo")
|
||||
doAssert $a.what == "foo"
|
||||
var b: cstring
|
||||
var b = ""
|
||||
try: raise initRuntimeError("foo2")
|
||||
except CStdException as e:
|
||||
doAssert e is CStdException
|
||||
b = e.what()
|
||||
doAssert $b == "foo2"
|
||||
b = $e.what()
|
||||
doAssert b == "foo2"
|
||||
|
||||
try: raise initStdException()
|
||||
except CStdException: discard
|
||||
|
||||
try: raise initRuntimeError("foo3")
|
||||
except CRuntimeError as e:
|
||||
b = e.what()
|
||||
b = $e.what()
|
||||
except CStdException:
|
||||
doAssert false
|
||||
doAssert $b == "foo3"
|
||||
doAssert b == "foo3"
|
||||
|
||||
fn()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
discard """
|
||||
nimoutFull: true
|
||||
action: "reject"
|
||||
cmd: "nim r --hint:Conf:off $file"
|
||||
cmd: "nim r --hint:Conf:off --warnings:off $file"
|
||||
nimout: '''
|
||||
tdiagnostic_messages.nim(36, 6) Error: 'a' can have side effects
|
||||
> tdiagnostic_messages.nim(37, 30) Hint: 'a' calls `.sideEffect` 'callWithSideEffects'
|
||||
|
||||
@@ -164,7 +164,9 @@ runnableExamples:
|
||||
|
||||
# bug #13491
|
||||
block:
|
||||
proc fun(): int = doAssert false
|
||||
proc fun(): int =
|
||||
result = 0
|
||||
doAssert false
|
||||
doAssertRaises(AssertionDefect, (discard fun()))
|
||||
|
||||
block:
|
||||
|
||||
@@ -673,11 +673,11 @@ template main {.dirty.} =
|
||||
result = v
|
||||
|
||||
proc failed(): Result[int, string] =
|
||||
discard
|
||||
result = default(Result[int, string])
|
||||
|
||||
proc calling(): Result[int, string] =
|
||||
let _ = ? failed()
|
||||
doAssert false
|
||||
raiseAssert "false"
|
||||
|
||||
let r = calling()
|
||||
doAssert assigned
|
||||
|
||||
16
tests/pragmas/tparamcustompragma.nim
Normal file
16
tests/pragmas/tparamcustompragma.nim
Normal file
@@ -0,0 +1,16 @@
|
||||
discard """
|
||||
nimout: '''
|
||||
proc foo(a {.attr.}: int) =
|
||||
discard
|
||||
|
||||
'''
|
||||
"""
|
||||
|
||||
# fixes #24702
|
||||
|
||||
import macros
|
||||
template attr*() {.pragma.}
|
||||
proc foo(a {.attr.}: int) = discard
|
||||
macro showImpl(a: typed) =
|
||||
echo repr getImpl(a)
|
||||
showImpl(foo)
|
||||
@@ -22,7 +22,7 @@ heyho
|
||||
Val1
|
||||
Val1
|
||||
'''
|
||||
matrix: "--hints:off --mm:orc; --hints:off --mm:refc"
|
||||
matrix: "--hints:off --warnings:off --mm:orc; --hints:off --warnings:off --mm:refc"
|
||||
"""
|
||||
|
||||
import macros
|
||||
|
||||
@@ -3,3 +3,5 @@ switch("styleCheck", "error")
|
||||
switch("define", "nimPreviewSlimSystem")
|
||||
switch("define", "nimPreviewCstringConversion")
|
||||
switch("define", "nimPreviewProcConversion")
|
||||
switch("warningAserror", "ProveInit")
|
||||
switch("warningAserror", "Uninit")
|
||||
|
||||
@@ -124,7 +124,7 @@ proc main() =
|
||||
var x = @[1, 7, 8, 11, 21, 33, 45, 99]
|
||||
var y = @[6, 7, 9, 12, 57, 66]
|
||||
|
||||
var merged: seq[int]
|
||||
var merged: seq[int] = @[]
|
||||
merged.merge(x, y)
|
||||
doAssert merged.isSorted
|
||||
doAssert merged == sorted(x & y)
|
||||
@@ -133,7 +133,7 @@ proc main() =
|
||||
var x = @[111, 88, 76, 56, 45, 31, 22, 19, 11, 3]
|
||||
var y = @[99, 85, 83, 82, 69, 64, 48, 42, 33, 31, 26, 13]
|
||||
|
||||
var merged: seq[int]
|
||||
var merged: seq[int] = @[]
|
||||
merged.merge(x, y, (x, y) => -system.cmp(x, y))
|
||||
doAssert merged.isSorted((x, y) => -system.cmp(x, y))
|
||||
doAssert merged == sorted(x & y, SortOrder.Descending)
|
||||
@@ -142,7 +142,7 @@ proc main() =
|
||||
var x: seq[int] = @[]
|
||||
var y = @[1]
|
||||
|
||||
var merged: seq[int]
|
||||
var merged: seq[int] = @[]
|
||||
merged.merge(x, y)
|
||||
doAssert merged.isSorted
|
||||
doAssert merged.isSorted(SortOrder.Descending)
|
||||
@@ -152,7 +152,7 @@ proc main() =
|
||||
var x = [1, 3, 5, 5, 7]
|
||||
var y: seq[int] = @[]
|
||||
|
||||
var merged: seq[int]
|
||||
var merged: seq[int] = @[]
|
||||
merged.merge(x, y)
|
||||
doAssert merged.isSorted
|
||||
doAssert merged == @x
|
||||
@@ -167,26 +167,26 @@ proc main() =
|
||||
|
||||
|
||||
block:
|
||||
var x: array[0, int]
|
||||
var x = default(array[0, int])
|
||||
var y = [1, 4, 6, 7, 9]
|
||||
|
||||
var merged: seq[int]
|
||||
var merged: seq[int] = @[]
|
||||
merged.merge(x, y)
|
||||
doAssert merged.isSorted
|
||||
doAssert merged == @y
|
||||
|
||||
block:
|
||||
var x: array[0, int]
|
||||
var y: array[0, int]
|
||||
var x: array[0, int] = []
|
||||
var y: array[0, int] = []
|
||||
|
||||
var merged: seq[int]
|
||||
var merged: seq[int] = @[]
|
||||
merged.merge(x, y)
|
||||
doAssert merged.isSorted
|
||||
doAssert merged.len == 0
|
||||
|
||||
block:
|
||||
var x: array[0, int]
|
||||
var y: array[0, int]
|
||||
var x: array[0, int] = []
|
||||
var y: array[0, int] = []
|
||||
|
||||
var merged: seq[int] = @[99, 99, 99]
|
||||
merged.setLen(0)
|
||||
@@ -195,10 +195,10 @@ proc main() =
|
||||
doAssert merged.len == 0
|
||||
|
||||
block:
|
||||
var x: seq[int]
|
||||
var y: seq[int]
|
||||
var x: seq[int] = @[]
|
||||
var y: seq[int] = @[]
|
||||
|
||||
var merged: seq[int]
|
||||
var merged: seq[int] = @[]
|
||||
merged.merge(x, y)
|
||||
doAssert merged.isSorted
|
||||
doAssert merged.len == 0
|
||||
@@ -245,7 +245,7 @@ proc main() =
|
||||
var x = @[r(-12), r(1), r(3), r(8), r(13), r(88)]
|
||||
var y = @[r(4), r(7), r(12), r(13), r(77), r(99)]
|
||||
|
||||
var merged: seq[Record]
|
||||
var merged: seq[Record] = @[]
|
||||
merged.setLen(0)
|
||||
merged.merge(x, y, ascendingCmp)
|
||||
doAssert merged.isSorted(ascendingCmp)
|
||||
@@ -267,7 +267,7 @@ proc main() =
|
||||
doAssert merged == sorted(x & y, ascendingCmp)
|
||||
|
||||
|
||||
var x: seq[(int, int)]
|
||||
var x: seq[(int, int)] = @[]
|
||||
x.merge([(1,1)], [(1,2)], (a,b) => a[0] - b[0])
|
||||
doAssert x == @[(1, 1), (1, 2)]
|
||||
|
||||
|
||||
@@ -173,7 +173,7 @@ proc main() =
|
||||
|
||||
block:
|
||||
# basic mask operations (mutating)
|
||||
var v: uint8
|
||||
var v: uint8 = 0'u8
|
||||
v.setMask(0b1100_0000)
|
||||
v.setMask(0b0000_1100)
|
||||
doAssert v == 0b1100_1100
|
||||
@@ -254,7 +254,7 @@ proc main() =
|
||||
doAssert a.clearMasked(3 .. 6) == 0b1000_0100
|
||||
block:
|
||||
# single bit operations
|
||||
var v: uint8
|
||||
var v: uint8 = 0'u8
|
||||
v.setBit(0)
|
||||
doAssert v == 0x0000_0001
|
||||
v.setBit(1)
|
||||
@@ -269,7 +269,7 @@ proc main() =
|
||||
doAssert not v.testBit(6)
|
||||
block:
|
||||
# multi bit operations
|
||||
var v: uint8
|
||||
var v: uint8 = 0'u8
|
||||
v.setBits(0, 1, 7)
|
||||
doAssert v == 0b1000_0011
|
||||
v.flipBits(2, 3)
|
||||
@@ -278,11 +278,11 @@ proc main() =
|
||||
doAssert v == 0b0000_1100
|
||||
block:
|
||||
# signed
|
||||
var v: int8
|
||||
var v: int8 = 0'i8
|
||||
v.setBit(7)
|
||||
doAssert v == -128
|
||||
block:
|
||||
var v: uint64
|
||||
var v: uint64 = 0'u64
|
||||
v.setBit(63)
|
||||
doAssert v == 0b1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000'u64
|
||||
|
||||
@@ -335,7 +335,7 @@ proc main() =
|
||||
|
||||
block: # not ready for vm because exception is compile error
|
||||
try:
|
||||
var v: uint32
|
||||
var v: uint32 = 0'u32
|
||||
var i = 32
|
||||
v.setBit(i)
|
||||
doAssert false
|
||||
|
||||
@@ -190,7 +190,7 @@ proc main() =
|
||||
doAssert $a == "[10, 20, 30]"
|
||||
|
||||
block:
|
||||
var a, b: Deque[int]
|
||||
var a, b: Deque[int] = initDeque[int]()
|
||||
for i in 1 .. 256:
|
||||
a.addLast(i)
|
||||
for i in 1 .. 255:
|
||||
|
||||
@@ -8,6 +8,7 @@ import std/strutils
|
||||
import std/assertions
|
||||
|
||||
proc testHelper(f: seq[Item]): string =
|
||||
result = ""
|
||||
for it in f:
|
||||
result.add(
|
||||
$it.deletedA & "." & $it.insertedB & "." & $it.startA & "." & $it.startB & "*"
|
||||
|
||||
@@ -25,7 +25,7 @@ proc leakCheck(f: AsyncFD | int | FileHandle | SocketHandle, msg: string,
|
||||
var args = @[$f.int, msg, $expectLeak]
|
||||
|
||||
when defined(windows):
|
||||
var refFd: Handle
|
||||
var refFd: Handle = default(Handle)
|
||||
# NOTE: This function shouldn't be used to duplicate sockets,
|
||||
# as this function may mess with the socket internal refcounting.
|
||||
# but due to the lack of type segmentation in the stdlib for
|
||||
@@ -51,7 +51,7 @@ proc leakCheck(f: AsyncFD | int | FileHandle | SocketHandle, msg: string,
|
||||
proc isValidHandle(f: int): bool =
|
||||
## Check if a handle is valid. Requires OS-native handles.
|
||||
when defined(windows):
|
||||
var flags: DWORD
|
||||
var flags: DWORD = default(DWORD)
|
||||
result = getHandleInformation(f.Handle, addr flags) != 0
|
||||
else:
|
||||
result = fcntl(f.cint, F_GETFD) != -1
|
||||
@@ -88,7 +88,7 @@ proc main() =
|
||||
defer: close client
|
||||
client.connect("127.0.0.1", port)
|
||||
|
||||
var input: Socket
|
||||
var input: Socket = default(Socket)
|
||||
server.accept(input)
|
||||
|
||||
leakCheck(input.getFd, "accept()")
|
||||
|
||||
@@ -12,12 +12,12 @@ when manualTest:
|
||||
import strformat
|
||||
|
||||
proc frexp_test(lo, hi, step: float64) =
|
||||
var exp: int
|
||||
var exp: int = 0
|
||||
var frac: float64
|
||||
|
||||
var eps = 1e-15.float64
|
||||
|
||||
var x:float64 = lo
|
||||
var x: float64 = lo
|
||||
while x <= hi:
|
||||
frac = frexp(x.float, exp)
|
||||
let rslt = pow(2.0, float(exp)) * frac
|
||||
|
||||
@@ -54,7 +54,7 @@ proc main =
|
||||
x.a = val
|
||||
|
||||
m1()
|
||||
var x0: Foo
|
||||
var x0: Foo = Foo()
|
||||
x0.a1 = 10
|
||||
doAssert x0 == Foo(a: 10)
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ proc main() =
|
||||
|
||||
when sizeof(int) == 8 or defined(js):
|
||||
block:
|
||||
var s: seq[Hash]
|
||||
var s: seq[Hash] = @[]
|
||||
for a in [0.0, 1.0, -1.0, 1000.0, -1000.0]:
|
||||
let b = hash(a)
|
||||
doAssert b notin s
|
||||
@@ -197,7 +197,7 @@ proc main() =
|
||||
doAssert hash(Obj5(t: false, x: 1)) != hash(Obj5(t: true, y: 2))
|
||||
|
||||
block: # hash(ref|ptr|pointer)
|
||||
var a: array[10, uint8]
|
||||
var a: array[10, uint8] = default(array[10, uint8])
|
||||
# disableVm:
|
||||
whenVMorJs:
|
||||
# pending fix proposed in https://github.com/nim-lang/Nim/issues/15952#issuecomment-786312417
|
||||
|
||||
@@ -45,7 +45,7 @@ when not defined(windows) and not disableSSLTesting():
|
||||
proc runServer(port: Port): bool {.thread.} =
|
||||
## Run a trivial HTTPS server in a {.thread.}
|
||||
## Exit after serving one request
|
||||
|
||||
result = false
|
||||
var socket = newSocket()
|
||||
socket.setSockOpt(OptReusePort, true)
|
||||
socket.bindAddr(port)
|
||||
@@ -55,7 +55,7 @@ when not defined(windows) and not disableSSLTesting():
|
||||
## Handle one connection
|
||||
socket.listen()
|
||||
|
||||
var client: Socket
|
||||
var client: Socket = default(Socket)
|
||||
var address = ""
|
||||
|
||||
log "server: ready"
|
||||
|
||||
@@ -125,7 +125,7 @@ proc main(moveZeroesOut: static bool) =
|
||||
doAssert data.extract.id == 12
|
||||
|
||||
block:
|
||||
var x: seq[Isolated[JsonNode]]
|
||||
var x: seq[Isolated[JsonNode]] = @[]
|
||||
x.add isolate(newJString("1234"))
|
||||
|
||||
doAssert $x == """@[(value: "1234")]"""
|
||||
|
||||
@@ -15,7 +15,7 @@ proc testRoundtrip[T](t: T, expected: string) =
|
||||
let j = t.toJson
|
||||
doAssert $j == expected, "\n" & $j & "\n" & expected
|
||||
doAssert j.jsonTo(T).toJson == j
|
||||
var t2: T
|
||||
var t2: T = default(T)
|
||||
t2.fromJson(j)
|
||||
doAssert t2.toJson == j
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ block: # bug #17454
|
||||
block: # unpackVarargs
|
||||
block:
|
||||
proc bar1(a: varargs[int]): string =
|
||||
result = ""
|
||||
for ai in a: result.add " " & $ai
|
||||
proc bar2(a: varargs[int]) =
|
||||
let s1 = bar1(a)
|
||||
|
||||
@@ -545,3 +545,8 @@ when not defined(js) and not defined(danger):
|
||||
doAssertRaises(OverflowDefect):
|
||||
discard sum(x)
|
||||
|
||||
block: # bug #24673
|
||||
let x: Natural = 5
|
||||
let y: Natural = 3
|
||||
|
||||
doAssert divmod(x, y) == (Natural 1, Natural 2)
|
||||
|
||||
@@ -94,10 +94,10 @@ block: # "IpAddress/Sockaddr conversion"
|
||||
|
||||
doAssert($ipaddrstr == $ipaddr_1)
|
||||
|
||||
var sockaddr: Sockaddr_storage
|
||||
var socklen: SockLen
|
||||
var ipaddr_2: IpAddress
|
||||
var port_2: Port
|
||||
var sockaddr: Sockaddr_storage = default(Sockaddr_storage)
|
||||
var socklen: SockLen = default(SockLen)
|
||||
var ipaddr_2: IpAddress = default(IpAddress)
|
||||
var port_2: Port = default(Port)
|
||||
|
||||
toSockAddr(ipaddr_1, Port(0), sockaddr, socklen)
|
||||
fromSockAddr(sockaddr, socklen, ipaddr_2, port_2)
|
||||
@@ -108,11 +108,11 @@ block: # "IpAddress/Sockaddr conversion"
|
||||
doAssert($ipaddr_1 == $ipaddr_2)
|
||||
|
||||
if sockaddr.ss_family.cint == AF_INET.toInt:
|
||||
var sockaddr4: Sockaddr_in
|
||||
var sockaddr4: Sockaddr_in = default(Sockaddr_in)
|
||||
copyMem(addr sockaddr4, addr sockaddr, sizeof(sockaddr4))
|
||||
fromSockAddr(sockaddr4, socklen, ipaddr_2, port_2)
|
||||
elif sockaddr.ss_family.cint == AF_INET6.toInt:
|
||||
var sockaddr6: Sockaddr_in6
|
||||
var sockaddr6: Sockaddr_in6 = default(Sockaddr_in6)
|
||||
copyMem(addr sockaddr6, addr sockaddr, sizeof(sockaddr6))
|
||||
fromSockAddr(sockaddr6, socklen, ipaddr_2, port_2)
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ proc testThread() {.thread.} =
|
||||
|
||||
proc test() =
|
||||
let serverFd = initIPv6Server("::1", port)
|
||||
var t: Thread[void]
|
||||
var t: Thread[void] = default(Thread[void])
|
||||
createThread(t, testThread)
|
||||
|
||||
var done = false
|
||||
|
||||
@@ -47,6 +47,7 @@ proc main() =
|
||||
|
||||
block example:
|
||||
proc find(haystack: string, needle: char): Option[int] =
|
||||
result = none(int)
|
||||
for i, c in haystack:
|
||||
if c == needle:
|
||||
return some i
|
||||
@@ -105,7 +106,7 @@ proc main() =
|
||||
block filter:
|
||||
doAssert(some(123).filter(proc (v: int): bool = v == 123) == some(123))
|
||||
doAssert(some(456).filter(proc (v: int): bool = v == 123).isNone)
|
||||
doAssert(intNone.filter(proc (v: int): bool = doAssert false).isNone)
|
||||
doAssert(intNone.filter(proc (v: int): bool = raiseAssert "false").isNone)
|
||||
|
||||
block flatMap:
|
||||
proc addOneIfNotZero(v: int): Option[int] =
|
||||
@@ -136,7 +137,7 @@ proc main() =
|
||||
doAssert(some(0).flatMap(maybeToString).flatMap(maybeExclaim) == none(string))
|
||||
|
||||
block SomePointer:
|
||||
var intref: ref int
|
||||
var intref: ref int = nil
|
||||
doAssert(option(intref).isNone)
|
||||
intref.new
|
||||
doAssert(option(intref).isSome)
|
||||
|
||||
@@ -44,12 +44,12 @@ proc test() =
|
||||
doAssert(parseSaturatedNatural("1_000_000", value) == 9)
|
||||
doAssert value == 1_000_000
|
||||
|
||||
var i64Value: int64
|
||||
var i64Value: int64 = 0'i64
|
||||
discard parseBiggestInt("9223372036854775807", i64Value)
|
||||
doAssert i64Value == 9223372036854775807
|
||||
|
||||
block:
|
||||
var f: float
|
||||
var f: float = 0.0
|
||||
let res = collect:
|
||||
for x in ["9.123456789012345+","11.123456789012345+","9.123456789012345-","8.123456789012345+","9.12345678901234-","9.123456789012345"]:
|
||||
(parseFloat(x, f, 0), $f)
|
||||
|
||||
@@ -192,7 +192,7 @@ block:
|
||||
expr.rule = sequence(capture(ident), *sequence(
|
||||
nonterminal(ws), term('+'), nonterminal(ws), nonterminal(expr)))
|
||||
|
||||
var c: Captures
|
||||
var c: Captures = default(Captures)
|
||||
var s = "a+b + c +d+e+f"
|
||||
doAssert rawMatch(s, expr.rule, 0, c) == len(s)
|
||||
var a = ""
|
||||
@@ -208,7 +208,7 @@ block:
|
||||
doAssert match("_______ana", peg"A <- 'ana' / . A")
|
||||
doAssert match("abcs%%%", peg"A <- ..A / .A / '%'")
|
||||
|
||||
var matches: array[0..MaxSubpatterns-1, string]
|
||||
var matches: array[0..MaxSubpatterns-1, string] = default(array[0..MaxSubpatterns-1, string])
|
||||
if "abc" =~ peg"{'a'}'bc' 'xyz' / {\ident}":
|
||||
doAssert matches[0] == "abc"
|
||||
else:
|
||||
@@ -325,7 +325,7 @@ block:
|
||||
call()
|
||||
call()
|
||||
"""
|
||||
var c: Captures
|
||||
var c: Captures = default(Captures)
|
||||
doAssert program.len == program.rawMatch(grammar, 0, c)
|
||||
doAssert c.ml == 1
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ when not defined(js):
|
||||
randomize(233)
|
||||
|
||||
proc main() =
|
||||
var occur: array[1000, int]
|
||||
var occur: array[1000, int] = default(array[1000, int])
|
||||
|
||||
for i in 0..100_000:
|
||||
let x = rand(high(occur))
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user