ccgexprs.nim 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # included from cgen.nim
  10. # -------------------------- constant expressions ------------------------
  11. proc int64Literal(i: BiggestInt): Rope =
  12. if i > low(int64):
  13. result = rfmt(nil, "IL64($1)", rope(i))
  14. else:
  15. result = ~"(IL64(-9223372036854775807) - IL64(1))"
  16. proc uint64Literal(i: uint64): Rope = rope($i & "ULL")
  17. proc intLiteral(i: BiggestInt): Rope =
  18. if i > low(int32) and i <= high(int32):
  19. result = rope(i)
  20. elif i == low(int32):
  21. # Nim has the same bug for the same reasons :-)
  22. result = ~"(-2147483647 -1)"
  23. elif i > low(int64):
  24. result = rfmt(nil, "IL64($1)", rope(i))
  25. else:
  26. result = ~"(IL64(-9223372036854775807) - IL64(1))"
  27. proc getStrLit(m: BModule, s: string): Rope =
  28. discard cgsym(m, "TGenericSeq")
  29. result = getTempName(m)
  30. addf(m.s[cfsData], "STRING_LITERAL($1, $2, $3);$n",
  31. [result, makeCString(s), rope(len(s))])
  32. proc genLiteral(p: BProc, n: PNode, ty: PType): Rope =
  33. if ty == nil: internalError(n.info, "genLiteral: ty is nil")
  34. case n.kind
  35. of nkCharLit..nkUInt64Lit:
  36. case skipTypes(ty, abstractVarRange).kind
  37. of tyChar, tyNil:
  38. result = intLiteral(n.intVal)
  39. of tyBool:
  40. if n.intVal != 0: result = ~"NIM_TRUE"
  41. else: result = ~"NIM_FALSE"
  42. of tyInt64: result = int64Literal(n.intVal)
  43. of tyUInt64: result = uint64Literal(uint64(n.intVal))
  44. else:
  45. result = "(($1) $2)" % [getTypeDesc(p.module,
  46. ty), intLiteral(n.intVal)]
  47. of nkNilLit:
  48. let t = skipTypes(ty, abstractVarRange)
  49. if t.kind == tyProc and t.callConv == ccClosure:
  50. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  51. result = p.module.tmpBase & rope(id)
  52. if id == p.module.labels:
  53. # not found in cache:
  54. inc(p.module.labels)
  55. addf(p.module.s[cfsData],
  56. "static NIM_CONST $1 $2 = {NIM_NIL,NIM_NIL};$n",
  57. [getTypeDesc(p.module, ty), result])
  58. else:
  59. result = rope("NIM_NIL")
  60. of nkStrLit..nkTripleStrLit:
  61. if n.strVal.isNil:
  62. result = ropecg(p.module, "((#NimStringDesc*) NIM_NIL)", [])
  63. elif skipTypes(ty, abstractVarRange).kind == tyString:
  64. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  65. if id == p.module.labels:
  66. # string literal not found in the cache:
  67. result = ropecg(p.module, "((#NimStringDesc*) &$1)",
  68. [getStrLit(p.module, n.strVal)])
  69. else:
  70. result = ropecg(p.module, "((#NimStringDesc*) &$1$2)",
  71. [p.module.tmpBase, rope(id)])
  72. else:
  73. result = makeCString(n.strVal)
  74. of nkFloatLit, nkFloat64Lit:
  75. result = rope(n.floatVal.toStrMaxPrecision)
  76. of nkFloat32Lit:
  77. result = rope(n.floatVal.toStrMaxPrecision("f"))
  78. else:
  79. internalError(n.info, "genLiteral(" & $n.kind & ')')
  80. result = nil
  81. proc genLiteral(p: BProc, n: PNode): Rope =
  82. result = genLiteral(p, n, n.typ)
  83. proc bitSetToWord(s: TBitSet, size: int): BiggestInt =
  84. result = 0
  85. when true:
  86. for j in countup(0, size - 1):
  87. if j < len(s): result = result or `shl`(ze64(s[j]), j * 8)
  88. else:
  89. # not needed, too complex thinking:
  90. if CPU[platform.hostCPU].endian == CPU[targetCPU].endian:
  91. for j in countup(0, size - 1):
  92. if j < len(s): result = result or `shl`(Ze64(s[j]), j * 8)
  93. else:
  94. for j in countup(0, size - 1):
  95. if j < len(s): result = result or `shl`(Ze64(s[j]), (Size - 1 - j) * 8)
  96. proc genRawSetData(cs: TBitSet, size: int): Rope =
  97. var frmt: FormatStr
  98. if size > 8:
  99. result = "{$n" % []
  100. for i in countup(0, size - 1):
  101. if i < size - 1:
  102. # not last iteration?
  103. if (i + 1) mod 8 == 0: frmt = "0x$1,$n"
  104. else: frmt = "0x$1, "
  105. else:
  106. frmt = "0x$1}$n"
  107. addf(result, frmt, [rope(toHex(ze64(cs[i]), 2))])
  108. else:
  109. result = intLiteral(bitSetToWord(cs, size))
  110. # result := rope('0x' + ToHex(bitSetToWord(cs, size), size * 2))
  111. proc genSetNode(p: BProc, n: PNode): Rope =
  112. var cs: TBitSet
  113. var size = int(getSize(n.typ))
  114. toBitSet(n, cs)
  115. if size > 8:
  116. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  117. result = p.module.tmpBase & rope(id)
  118. if id == p.module.labels:
  119. # not found in cache:
  120. inc(p.module.labels)
  121. addf(p.module.s[cfsData], "static NIM_CONST $1 $2 = $3;$n",
  122. [getTypeDesc(p.module, n.typ), result, genRawSetData(cs, size)])
  123. else:
  124. result = genRawSetData(cs, size)
  125. proc getStorageLoc(n: PNode): TStorageLoc =
  126. case n.kind
  127. of nkSym:
  128. case n.sym.kind
  129. of skParam, skTemp:
  130. result = OnStack
  131. of skVar, skForVar, skResult, skLet:
  132. if sfGlobal in n.sym.flags: result = OnHeap
  133. else: result = OnStack
  134. of skConst:
  135. if sfGlobal in n.sym.flags: result = OnHeap
  136. else: result = OnUnknown
  137. else: result = OnUnknown
  138. of nkDerefExpr, nkHiddenDeref:
  139. case n.sons[0].typ.kind
  140. of tyVar: result = OnUnknown
  141. of tyPtr: result = OnStack
  142. of tyRef: result = OnHeap
  143. else: internalError(n.info, "getStorageLoc")
  144. of nkBracketExpr, nkDotExpr, nkObjDownConv, nkObjUpConv:
  145. result = getStorageLoc(n.sons[0])
  146. else: result = OnUnknown
  147. proc canMove(n: PNode): bool =
  148. # for now we're conservative here:
  149. if n.kind == nkBracket:
  150. # This needs to be kept consistent with 'const' seq code
  151. # generation!
  152. if not isDeepConstExpr(n) or n.len == 0:
  153. if skipTypes(n.typ, abstractVarRange).kind == tySequence:
  154. return true
  155. result = n.kind in nkCallKinds
  156. #if result:
  157. # echo n.info, " optimized ", n
  158. # result = false
  159. proc genRefAssign(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  160. if dest.storage == OnStack or not usesNativeGC():
  161. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  162. elif dest.storage == OnHeap:
  163. # location is on heap
  164. # now the writer barrier is inlined for performance:
  165. #
  166. # if afSrcIsNotNil in flags:
  167. # UseMagic(p.module, 'nimGCref')
  168. # lineF(p, cpsStmts, 'nimGCref($1);$n', [rdLoc(src)])
  169. # elif afSrcIsNil notin flags:
  170. # UseMagic(p.module, 'nimGCref')
  171. # lineF(p, cpsStmts, 'if ($1) nimGCref($1);$n', [rdLoc(src)])
  172. # if afDestIsNotNil in flags:
  173. # UseMagic(p.module, 'nimGCunref')
  174. # lineF(p, cpsStmts, 'nimGCunref($1);$n', [rdLoc(dest)])
  175. # elif afDestIsNil notin flags:
  176. # UseMagic(p.module, 'nimGCunref')
  177. # lineF(p, cpsStmts, 'if ($1) nimGCunref($1);$n', [rdLoc(dest)])
  178. # lineF(p, cpsStmts, '$1 = $2;$n', [rdLoc(dest), rdLoc(src)])
  179. if canFormAcycle(dest.t):
  180. linefmt(p, cpsStmts, "#asgnRef((void**) $1, $2);$n",
  181. addrLoc(dest), rdLoc(src))
  182. else:
  183. linefmt(p, cpsStmts, "#asgnRefNoCycle((void**) $1, $2);$n",
  184. addrLoc(dest), rdLoc(src))
  185. else:
  186. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n",
  187. addrLoc(dest), rdLoc(src))
  188. proc asgnComplexity(n: PNode): int =
  189. if n != nil:
  190. case n.kind
  191. of nkSym: result = 1
  192. of nkRecCase:
  193. # 'case objects' are too difficult to inline their assignment operation:
  194. result = 100
  195. of nkRecList:
  196. for t in items(n):
  197. result += asgnComplexity(t)
  198. else: discard
  199. proc optAsgnLoc(a: TLoc, t: PType, field: Rope): TLoc =
  200. assert field != nil
  201. result.k = locField
  202. result.storage = a.storage
  203. result.lode = lodeTyp t
  204. result.r = rdLoc(a) & "." & field
  205. proc genOptAsgnTuple(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  206. let newflags =
  207. if src.storage == OnStatic:
  208. flags + {needToCopy}
  209. elif tfShallow in dest.t.flags:
  210. flags - {needToCopy}
  211. else:
  212. flags
  213. let t = skipTypes(dest.t, abstractInst).getUniqueType()
  214. for i in 0 .. <t.len:
  215. let t = t.sons[i]
  216. let field = "Field$1" % [i.rope]
  217. genAssignment(p, optAsgnLoc(dest, t, field),
  218. optAsgnLoc(src, t, field), newflags)
  219. proc genOptAsgnObject(p: BProc, dest, src: TLoc, flags: TAssignmentFlags,
  220. t: PNode, typ: PType) =
  221. if t == nil: return
  222. let newflags =
  223. if src.storage == OnStatic:
  224. flags + {needToCopy}
  225. elif tfShallow in dest.t.flags:
  226. flags - {needToCopy}
  227. else:
  228. flags
  229. case t.kind
  230. of nkSym:
  231. let field = t.sym
  232. if field.loc.r == nil: fillObjectFields(p.module, typ)
  233. genAssignment(p, optAsgnLoc(dest, field.typ, field.loc.r),
  234. optAsgnLoc(src, field.typ, field.loc.r), newflags)
  235. of nkRecList:
  236. for child in items(t): genOptAsgnObject(p, dest, src, newflags, child, typ)
  237. else: discard
  238. proc genGenericAsgn(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  239. # Consider:
  240. # type TMyFastString {.shallow.} = string
  241. # Due to the implementation of pragmas this would end up to set the
  242. # tfShallow flag for the built-in string type too! So we check only
  243. # here for this flag, where it is reasonably safe to do so
  244. # (for objects, etc.):
  245. if needToCopy notin flags or
  246. tfShallow in skipTypes(dest.t, abstractVarRange).flags:
  247. if dest.storage == OnStack or not usesNativeGC():
  248. useStringh(p.module)
  249. linefmt(p, cpsStmts,
  250. "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
  251. addrLoc(dest), addrLoc(src), rdLoc(dest))
  252. else:
  253. linefmt(p, cpsStmts, "#genericShallowAssign((void*)$1, (void*)$2, $3);$n",
  254. addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t))
  255. else:
  256. linefmt(p, cpsStmts, "#genericAssign((void*)$1, (void*)$2, $3);$n",
  257. addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t))
  258. proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  259. # This function replaces all other methods for generating
  260. # the assignment operation in C.
  261. if src.t != nil and src.t.kind == tyPtr:
  262. # little HACK to support the new 'var T' as return type:
  263. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  264. return
  265. let ty = skipTypes(dest.t, abstractRange + tyUserTypeClasses)
  266. case ty.kind
  267. of tyRef:
  268. genRefAssign(p, dest, src, flags)
  269. of tySequence:
  270. if (needToCopy notin flags and src.storage != OnStatic) or canMove(src.lode):
  271. genRefAssign(p, dest, src, flags)
  272. else:
  273. linefmt(p, cpsStmts, "#genericSeqAssign($1, $2, $3);$n",
  274. addrLoc(dest), rdLoc(src), genTypeInfo(p.module, dest.t))
  275. of tyString:
  276. if (needToCopy notin flags and src.storage != OnStatic) or canMove(src.lode):
  277. genRefAssign(p, dest, src, flags)
  278. else:
  279. if dest.storage == OnStack or not usesNativeGC():
  280. linefmt(p, cpsStmts, "$1 = #copyString($2);$n", dest.rdLoc, src.rdLoc)
  281. elif dest.storage == OnHeap:
  282. # we use a temporary to care for the dreaded self assignment:
  283. var tmp: TLoc
  284. getTemp(p, ty, tmp)
  285. linefmt(p, cpsStmts, "$3 = $1; $1 = #copyStringRC1($2);$n",
  286. dest.rdLoc, src.rdLoc, tmp.rdLoc)
  287. linefmt(p, cpsStmts, "if ($1) #nimGCunrefNoCycle($1);$n", tmp.rdLoc)
  288. else:
  289. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, #copyString($2));$n",
  290. addrLoc(dest), rdLoc(src))
  291. of tyProc:
  292. if needsComplexAssignment(dest.t):
  293. # optimize closure assignment:
  294. let a = optAsgnLoc(dest, dest.t, "ClE_0".rope)
  295. let b = optAsgnLoc(src, dest.t, "ClE_0".rope)
  296. genRefAssign(p, a, b, flags)
  297. linefmt(p, cpsStmts, "$1.ClP_0 = $2.ClP_0;$n", rdLoc(dest), rdLoc(src))
  298. else:
  299. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  300. of tyTuple:
  301. if needsComplexAssignment(dest.t):
  302. if dest.t.len <= 4: genOptAsgnTuple(p, dest, src, flags)
  303. else: genGenericAsgn(p, dest, src, flags)
  304. else:
  305. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  306. of tyObject:
  307. # XXX: check for subtyping?
  308. if ty.isImportedCppType:
  309. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  310. elif not isObjLackingTypeField(ty):
  311. genGenericAsgn(p, dest, src, flags)
  312. elif needsComplexAssignment(ty):
  313. if ty.sons[0].isNil and asgnComplexity(ty.n) <= 4:
  314. discard getTypeDesc(p.module, ty)
  315. internalAssert ty.n != nil
  316. genOptAsgnObject(p, dest, src, flags, ty.n, ty)
  317. else:
  318. genGenericAsgn(p, dest, src, flags)
  319. else:
  320. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  321. of tyArray:
  322. if needsComplexAssignment(dest.t):
  323. genGenericAsgn(p, dest, src, flags)
  324. else:
  325. useStringh(p.module)
  326. linefmt(p, cpsStmts,
  327. "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
  328. rdLoc(dest), rdLoc(src), getTypeDesc(p.module, dest.t))
  329. of tyOpenArray, tyVarargs:
  330. # open arrays are always on the stack - really? What if a sequence is
  331. # passed to an open array?
  332. if needsComplexAssignment(dest.t):
  333. linefmt(p, cpsStmts, # XXX: is this correct for arrays?
  334. "#genericAssignOpenArray((void*)$1, (void*)$2, $1Len_0, $3);$n",
  335. addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t))
  336. else:
  337. useStringh(p.module)
  338. linefmt(p, cpsStmts,
  339. "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($1[0])*$1Len_0);$n",
  340. rdLoc(dest), rdLoc(src))
  341. of tySet:
  342. if mapType(ty) == ctArray:
  343. useStringh(p.module)
  344. linefmt(p, cpsStmts, "memcpy((void*)$1, (NIM_CONST void*)$2, $3);$n",
  345. rdLoc(dest), rdLoc(src), rope(getSize(dest.t)))
  346. else:
  347. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  348. of tyPtr, tyPointer, tyChar, tyBool, tyEnum, tyCString,
  349. tyInt..tyUInt64, tyRange, tyVar:
  350. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  351. else: internalError("genAssignment: " & $ty.kind)
  352. if optMemTracker in p.options and dest.storage in {OnHeap, OnUnknown}:
  353. #writeStackTrace()
  354. #echo p.currLineInfo, " requesting"
  355. linefmt(p, cpsStmts, "#memTrackerWrite((void*)$1, $2, $3, $4);$n",
  356. addrLoc(dest), rope getSize(dest.t),
  357. makeCString(p.currLineInfo.toFullPath),
  358. rope p.currLineInfo.safeLineNm)
  359. proc genDeepCopy(p: BProc; dest, src: TLoc) =
  360. template addrLocOrTemp(a: TLoc): Rope =
  361. if a.k == locExpr:
  362. var tmp: TLoc
  363. getTemp(p, a.t, tmp)
  364. genAssignment(p, tmp, a, {})
  365. addrLoc(tmp)
  366. else:
  367. addrLoc(a)
  368. var ty = skipTypes(dest.t, abstractVarRange)
  369. case ty.kind
  370. of tyPtr, tyRef, tyProc, tyTuple, tyObject, tyArray:
  371. # XXX optimize this
  372. linefmt(p, cpsStmts, "#genericDeepCopy((void*)$1, (void*)$2, $3);$n",
  373. addrLoc(dest), addrLocOrTemp(src), genTypeInfo(p.module, dest.t))
  374. of tySequence, tyString:
  375. linefmt(p, cpsStmts, "#genericSeqDeepCopy($1, $2, $3);$n",
  376. addrLoc(dest), rdLoc(src), genTypeInfo(p.module, dest.t))
  377. of tyOpenArray, tyVarargs:
  378. linefmt(p, cpsStmts,
  379. "#genericDeepCopyOpenArray((void*)$1, (void*)$2, $1Len_0, $3);$n",
  380. addrLoc(dest), addrLocOrTemp(src), genTypeInfo(p.module, dest.t))
  381. of tySet:
  382. if mapType(ty) == ctArray:
  383. useStringh(p.module)
  384. linefmt(p, cpsStmts, "memcpy((void*)$1, (NIM_CONST void*)$2, $3);$n",
  385. rdLoc(dest), rdLoc(src), rope(getSize(dest.t)))
  386. else:
  387. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  388. of tyPointer, tyChar, tyBool, tyEnum, tyCString,
  389. tyInt..tyUInt64, tyRange, tyVar:
  390. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  391. else: internalError("genDeepCopy: " & $ty.kind)
  392. proc putLocIntoDest(p: BProc, d: var TLoc, s: TLoc) =
  393. if d.k != locNone:
  394. if lfNoDeepCopy in d.flags: genAssignment(p, d, s, {})
  395. else: genAssignment(p, d, s, {needToCopy})
  396. else:
  397. d = s # ``d`` is free, so fill it with ``s``
  398. proc putDataIntoDest(p: BProc, d: var TLoc, n: PNode, r: Rope) =
  399. var a: TLoc
  400. if d.k != locNone:
  401. # need to generate an assignment here
  402. initLoc(a, locData, n, OnStatic)
  403. a.r = r
  404. if lfNoDeepCopy in d.flags: genAssignment(p, d, a, {})
  405. else: genAssignment(p, d, a, {needToCopy})
  406. else:
  407. # we cannot call initLoc() here as that would overwrite
  408. # the flags field!
  409. d.k = locData
  410. d.lode = n
  411. d.r = r
  412. proc putIntoDest(p: BProc, d: var TLoc, n: PNode, r: Rope; s=OnUnknown) =
  413. var a: TLoc
  414. if d.k != locNone:
  415. # need to generate an assignment here
  416. initLoc(a, locExpr, n, s)
  417. a.r = r
  418. if lfNoDeepCopy in d.flags: genAssignment(p, d, a, {})
  419. else: genAssignment(p, d, a, {needToCopy})
  420. else:
  421. # we cannot call initLoc() here as that would overwrite
  422. # the flags field!
  423. d.k = locExpr
  424. d.lode = n
  425. d.r = r
  426. proc binaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  427. var a, b: TLoc
  428. if d.k != locNone: internalError(e.info, "binaryStmt")
  429. initLocExpr(p, e.sons[1], a)
  430. initLocExpr(p, e.sons[2], b)
  431. lineCg(p, cpsStmts, frmt, rdLoc(a), rdLoc(b))
  432. proc unaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  433. var a: TLoc
  434. if d.k != locNone: internalError(e.info, "unaryStmt")
  435. initLocExpr(p, e.sons[1], a)
  436. lineCg(p, cpsStmts, frmt, [rdLoc(a)])
  437. proc binaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  438. var a, b: TLoc
  439. assert(e.sons[1].typ != nil)
  440. assert(e.sons[2].typ != nil)
  441. initLocExpr(p, e.sons[1], a)
  442. initLocExpr(p, e.sons[2], b)
  443. putIntoDest(p, d, e, ropecg(p.module, frmt, [rdLoc(a), rdLoc(b)]))
  444. proc binaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  445. var a, b: TLoc
  446. assert(e.sons[1].typ != nil)
  447. assert(e.sons[2].typ != nil)
  448. initLocExpr(p, e.sons[1], a)
  449. initLocExpr(p, e.sons[2], b)
  450. putIntoDest(p, d, e, ropecg(p.module, frmt, [a.rdCharLoc, b.rdCharLoc]))
  451. proc unaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  452. var a: TLoc
  453. initLocExpr(p, e.sons[1], a)
  454. putIntoDest(p, d, e, ropecg(p.module, frmt, [rdLoc(a)]))
  455. proc unaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  456. var a: TLoc
  457. initLocExpr(p, e.sons[1], a)
  458. putIntoDest(p, d, e, ropecg(p.module, frmt, [rdCharLoc(a)]))
  459. proc binaryArithOverflowRaw(p: BProc, t: PType, a, b: TLoc;
  460. frmt: string): Rope =
  461. var size = getSize(t)
  462. let storage = if size < platform.intSize: rope("NI")
  463. else: getTypeDesc(p.module, t)
  464. result = getTempName(p.module)
  465. linefmt(p, cpsLocals, "$1 $2;$n", storage, result)
  466. lineCg(p, cpsStmts, frmt, result, rdCharLoc(a), rdCharLoc(b))
  467. if size < platform.intSize or t.kind in {tyRange, tyEnum}:
  468. linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n",
  469. result, intLiteral(firstOrd(t)), intLiteral(lastOrd(t)))
  470. proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  471. const
  472. prc: array[mAddI..mPred, string] = [
  473. "$# = #addInt($#, $#);$n", "$# = #subInt($#, $#);$n",
  474. "$# = #mulInt($#, $#);$n", "$# = #divInt($#, $#);$n",
  475. "$# = #modInt($#, $#);$n",
  476. "$# = #addInt($#, $#);$n", "$# = #subInt($#, $#);$n"]
  477. prc64: array[mAddI..mPred, string] = [
  478. "$# = #addInt64($#, $#);$n", "$# = #subInt64($#, $#);$n",
  479. "$# = #mulInt64($#, $#);$n", "$# = #divInt64($#, $#);$n",
  480. "$# = #modInt64($#, $#);$n",
  481. "$# = #addInt64($#, $#);$n", "$# = #subInt64($#, $#);$n"]
  482. opr: array[mAddI..mPred, string] = [
  483. "($#)($# + $#)", "($#)($# - $#)", "($#)($# * $#)",
  484. "($#)($# / $#)", "($#)($# % $#)",
  485. "($#)($# + $#)", "($#)($# - $#)"]
  486. var a, b: TLoc
  487. assert(e.sons[1].typ != nil)
  488. assert(e.sons[2].typ != nil)
  489. initLocExpr(p, e.sons[1], a)
  490. initLocExpr(p, e.sons[2], b)
  491. # skipping 'range' is correct here as we'll generate a proper range check
  492. # later via 'chckRange'
  493. let t = e.typ.skipTypes(abstractRange)
  494. if optOverflowCheck notin p.options:
  495. let res = opr[m] % [getTypeDesc(p.module, e.typ), rdLoc(a), rdLoc(b)]
  496. putIntoDest(p, d, e, res)
  497. else:
  498. let res = binaryArithOverflowRaw(p, t, a, b,
  499. if t.kind == tyInt64: prc64[m] else: prc[m])
  500. putIntoDest(p, d, e, "($#)($#)" % [getTypeDesc(p.module, e.typ), res])
  501. proc unaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  502. const
  503. opr: array[mUnaryMinusI..mAbsI, string] = [
  504. mUnaryMinusI: "((NI$2)-($1))",
  505. mUnaryMinusI64: "-($1)",
  506. mAbsI: "($1 > 0? ($1) : -($1))"]
  507. var
  508. a: TLoc
  509. t: PType
  510. assert(e.sons[1].typ != nil)
  511. initLocExpr(p, e.sons[1], a)
  512. t = skipTypes(e.typ, abstractRange)
  513. if optOverflowCheck in p.options:
  514. linefmt(p, cpsStmts, "if ($1 == $2) #raiseOverflow();$n",
  515. rdLoc(a), intLiteral(firstOrd(t)))
  516. putIntoDest(p, d, e, opr[m] % [rdLoc(a), rope(getSize(t) * 8)])
  517. proc binaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  518. const
  519. binArithTab: array[mAddF64..mXor, string] = [
  520. "(($4)($1) + ($4)($2))", # AddF64
  521. "(($4)($1) - ($4)($2))", # SubF64
  522. "(($4)($1) * ($4)($2))", # MulF64
  523. "(($4)($1) / ($4)($2))", # DivF64
  524. "($4)((NU$5)($1) >> (NU$3)($2))", # ShrI
  525. "($4)((NU$3)($1) << (NU$3)($2))", # ShlI
  526. "($4)($1 & $2)", # BitandI
  527. "($4)($1 | $2)", # BitorI
  528. "($4)($1 ^ $2)", # BitxorI
  529. "(($1 <= $2) ? $1 : $2)", # MinI
  530. "(($1 >= $2) ? $1 : $2)", # MaxI
  531. "(($1 <= $2) ? $1 : $2)", # MinF64
  532. "(($1 >= $2) ? $1 : $2)", # MaxF64
  533. "($4)((NU$3)($1) + (NU$3)($2))", # AddU
  534. "($4)((NU$3)($1) - (NU$3)($2))", # SubU
  535. "($4)((NU$3)($1) * (NU$3)($2))", # MulU
  536. "($4)((NU$3)($1) / (NU$3)($2))", # DivU
  537. "($4)((NU$3)($1) % (NU$3)($2))", # ModU
  538. "($1 == $2)", # EqI
  539. "($1 <= $2)", # LeI
  540. "($1 < $2)", # LtI
  541. "($1 == $2)", # EqF64
  542. "($1 <= $2)", # LeF64
  543. "($1 < $2)", # LtF64
  544. "((NU$3)($1) <= (NU$3)($2))", # LeU
  545. "((NU$3)($1) < (NU$3)($2))", # LtU
  546. "((NU64)($1) <= (NU64)($2))", # LeU64
  547. "((NU64)($1) < (NU64)($2))", # LtU64
  548. "($1 == $2)", # EqEnum
  549. "($1 <= $2)", # LeEnum
  550. "($1 < $2)", # LtEnum
  551. "((NU8)($1) == (NU8)($2))", # EqCh
  552. "((NU8)($1) <= (NU8)($2))", # LeCh
  553. "((NU8)($1) < (NU8)($2))", # LtCh
  554. "($1 == $2)", # EqB
  555. "($1 <= $2)", # LeB
  556. "($1 < $2)", # LtB
  557. "($1 == $2)", # EqRef
  558. "($1 == $2)", # EqPtr
  559. "($1 <= $2)", # LePtr
  560. "($1 < $2)", # LtPtr
  561. "($1 != $2)"] # Xor
  562. var
  563. a, b: TLoc
  564. s, k: BiggestInt
  565. assert(e.sons[1].typ != nil)
  566. assert(e.sons[2].typ != nil)
  567. initLocExpr(p, e.sons[1], a)
  568. initLocExpr(p, e.sons[2], b)
  569. # BUGFIX: cannot use result-type here, as it may be a boolean
  570. s = max(getSize(a.t), getSize(b.t)) * 8
  571. k = getSize(a.t) * 8
  572. putIntoDest(p, d, e,
  573. binArithTab[op] % [rdLoc(a), rdLoc(b), rope(s),
  574. getSimpleTypeDesc(p.module, e.typ), rope(k)])
  575. proc genEqProc(p: BProc, e: PNode, d: var TLoc) =
  576. var a, b: TLoc
  577. assert(e.sons[1].typ != nil)
  578. assert(e.sons[2].typ != nil)
  579. initLocExpr(p, e.sons[1], a)
  580. initLocExpr(p, e.sons[2], b)
  581. if a.t.skipTypes(abstractInst).callConv == ccClosure:
  582. putIntoDest(p, d, e,
  583. "($1.ClP_0 == $2.ClP_0 && $1.ClE_0 == $2.ClE_0)" % [rdLoc(a), rdLoc(b)])
  584. else:
  585. putIntoDest(p, d, e, "($1 == $2)" % [rdLoc(a), rdLoc(b)])
  586. proc genIsNil(p: BProc, e: PNode, d: var TLoc) =
  587. let t = skipTypes(e.sons[1].typ, abstractRange)
  588. if t.kind == tyProc and t.callConv == ccClosure:
  589. unaryExpr(p, e, d, "($1.ClP_0 == 0)")
  590. else:
  591. unaryExpr(p, e, d, "($1 == 0)")
  592. proc unaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  593. const
  594. unArithTab: array[mNot..mToBiggestInt, string] = ["!($1)", # Not
  595. "$1", # UnaryPlusI
  596. "($3)((NU$2) ~($1))", # BitnotI
  597. "$1", # UnaryPlusF64
  598. "-($1)", # UnaryMinusF64
  599. "($1 < 0? -($1) : ($1))", # AbsF64; BUGFIX: fabs() makes problems
  600. # for Tiny C, so we don't use it
  601. "(($3)(NU)(NU8)($1))", # mZe8ToI
  602. "(($3)(NU64)(NU8)($1))", # mZe8ToI64
  603. "(($3)(NU)(NU16)($1))", # mZe16ToI
  604. "(($3)(NU64)(NU16)($1))", # mZe16ToI64
  605. "(($3)(NU64)(NU32)($1))", # mZe32ToI64
  606. "(($3)(NU64)(NU)($1))", # mZeIToI64
  607. "(($3)(NU8)(NU)($1))", # ToU8
  608. "(($3)(NU16)(NU)($1))", # ToU16
  609. "(($3)(NU32)(NU64)($1))", # ToU32
  610. "((double) ($1))", # ToFloat
  611. "((double) ($1))", # ToBiggestFloat
  612. "float64ToInt32($1)", # ToInt
  613. "float64ToInt64($1)"] # ToBiggestInt
  614. var
  615. a: TLoc
  616. t: PType
  617. assert(e.sons[1].typ != nil)
  618. initLocExpr(p, e.sons[1], a)
  619. t = skipTypes(e.typ, abstractRange)
  620. putIntoDest(p, d, e,
  621. unArithTab[op] % [rdLoc(a), rope(getSize(t) * 8),
  622. getSimpleTypeDesc(p.module, e.typ)])
  623. proc isCppRef(p: BProc; typ: PType): bool {.inline.} =
  624. result = p.module.compileToCpp and
  625. skipTypes(typ, abstractInst).kind == tyVar and
  626. tfVarIsPtr notin skipTypes(typ, abstractInst).flags
  627. proc genDeref(p: BProc, e: PNode, d: var TLoc; enforceDeref=false) =
  628. let mt = mapType(e.sons[0].typ)
  629. if mt in {ctArray, ctPtrToArray} and not enforceDeref:
  630. # XXX the amount of hacks for C's arrays is incredible, maybe we should
  631. # simply wrap them in a struct? --> Losing auto vectorization then?
  632. #if e[0].kind != nkBracketExpr:
  633. # message(e.info, warnUser, "CAME HERE " & renderTree(e))
  634. expr(p, e.sons[0], d)
  635. if e.sons[0].typ.skipTypes(abstractInst).kind == tyRef:
  636. d.storage = OnHeap
  637. else:
  638. var a: TLoc
  639. var typ = skipTypes(e.sons[0].typ, abstractInst)
  640. if typ.kind in {tyUserTypeClass, tyUserTypeClassInst} and typ.isResolvedUserTypeClass:
  641. typ = typ.lastSon
  642. if typ.kind == tyVar and tfVarIsPtr notin typ.flags and p.module.compileToCpp and e.sons[0].kind == nkHiddenAddr:
  643. initLocExprSingleUse(p, e[0][0], d)
  644. return
  645. else:
  646. initLocExprSingleUse(p, e.sons[0], a)
  647. if d.k == locNone:
  648. # dest = *a; <-- We do not know that 'dest' is on the heap!
  649. # It is completely wrong to set 'd.storage' here, unless it's not yet
  650. # been assigned to.
  651. case typ.kind
  652. of tyRef:
  653. d.storage = OnHeap
  654. of tyVar:
  655. d.storage = OnUnknown
  656. if tfVarIsPtr notin typ.flags and p.module.compileToCpp and
  657. e.kind == nkHiddenDeref:
  658. putIntoDest(p, d, e, rdLoc(a), a.storage)
  659. return
  660. of tyPtr:
  661. d.storage = OnUnknown # BUGFIX!
  662. else:
  663. internalError(e.info, "genDeref " & $typ.kind)
  664. elif p.module.compileToCpp:
  665. if typ.kind == tyVar and tfVarIsPtr notin typ.flags and
  666. e.kind == nkHiddenDeref:
  667. putIntoDest(p, d, e, rdLoc(a), a.storage)
  668. return
  669. if enforceDeref and mt == ctPtrToArray:
  670. # we lie about the type for better C interop: 'ptr array[3,T]' is
  671. # translated to 'ptr T', but for deref'ing this produces wrong code.
  672. # See tmissingderef. So we get rid of the deref instead. The codegen
  673. # ends up using 'memcpy' for the array assignment,
  674. # so the '&' and '*' cancel out:
  675. putIntoDest(p, d, lodeTyp(a.t.sons[0]), rdLoc(a), a.storage)
  676. else:
  677. putIntoDest(p, d, e, "(*$1)" % [rdLoc(a)], a.storage)
  678. proc genAddr(p: BProc, e: PNode, d: var TLoc) =
  679. # careful 'addr(myptrToArray)' needs to get the ampersand:
  680. if e.sons[0].typ.skipTypes(abstractInst).kind in {tyRef, tyPtr}:
  681. var a: TLoc
  682. initLocExpr(p, e.sons[0], a)
  683. putIntoDest(p, d, e, "&" & a.r, a.storage)
  684. #Message(e.info, warnUser, "HERE NEW &")
  685. elif mapType(e.sons[0].typ) == ctArray or isCppRef(p, e.sons[0].typ):
  686. expr(p, e.sons[0], d)
  687. else:
  688. var a: TLoc
  689. initLocExpr(p, e.sons[0], a)
  690. putIntoDest(p, d, e, addrLoc(a), a.storage)
  691. template inheritLocation(d: var TLoc, a: TLoc) =
  692. if d.k == locNone: d.storage = a.storage
  693. proc genRecordFieldAux(p: BProc, e: PNode, d, a: var TLoc) =
  694. initLocExpr(p, e.sons[0], a)
  695. if e.sons[1].kind != nkSym: internalError(e.info, "genRecordFieldAux")
  696. d.inheritLocation(a)
  697. discard getTypeDesc(p.module, a.t) # fill the record's fields.loc
  698. proc genTupleElem(p: BProc, e: PNode, d: var TLoc) =
  699. var
  700. a: TLoc
  701. i: int
  702. initLocExpr(p, e.sons[0], a)
  703. let tupType = a.t.skipTypes(abstractInst)
  704. assert tupType.kind == tyTuple
  705. d.inheritLocation(a)
  706. discard getTypeDesc(p.module, a.t) # fill the record's fields.loc
  707. var r = rdLoc(a)
  708. case e.sons[1].kind
  709. of nkIntLit..nkUInt64Lit: i = int(e.sons[1].intVal)
  710. else: internalError(e.info, "genTupleElem")
  711. addf(r, ".Field$1", [rope(i)])
  712. putIntoDest(p, d, e, r, a.storage)
  713. proc lookupFieldAgain(p: BProc, ty: PType; field: PSym; r: var Rope;
  714. resTyp: ptr PType = nil): PSym =
  715. var ty = ty
  716. assert r != nil
  717. while ty != nil:
  718. ty = ty.skipTypes(skipPtrs)
  719. assert(ty.kind in {tyTuple, tyObject})
  720. result = lookupInRecord(ty.n, field.name)
  721. if result != nil:
  722. if resTyp != nil: resTyp[] = ty
  723. break
  724. if not p.module.compileToCpp: add(r, ".Sup")
  725. ty = ty.sons[0]
  726. if result == nil: internalError(field.info, "genCheckedRecordField")
  727. proc genRecordField(p: BProc, e: PNode, d: var TLoc) =
  728. var a: TLoc
  729. genRecordFieldAux(p, e, d, a)
  730. var r = rdLoc(a)
  731. var f = e.sons[1].sym
  732. let ty = skipTypes(a.t, abstractInst + tyUserTypeClasses)
  733. if ty.kind == tyTuple:
  734. # we found a unique tuple type which lacks field information
  735. # so we use Field$i
  736. addf(r, ".Field$1", [rope(f.position)])
  737. putIntoDest(p, d, e, r, a.storage)
  738. else:
  739. var rtyp: PType
  740. let field = lookupFieldAgain(p, ty, f, r, addr rtyp)
  741. if field.loc.r == nil and rtyp != nil: fillObjectFields(p.module, rtyp)
  742. if field.loc.r == nil: internalError(e.info, "genRecordField 3 " & typeToString(ty))
  743. addf(r, ".$1", [field.loc.r])
  744. putIntoDest(p, d, e, r, a.storage)
  745. proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc)
  746. proc genFieldCheck(p: BProc, e: PNode, obj: Rope, field: PSym;
  747. origTy: PType) =
  748. var test, u, v: TLoc
  749. for i in countup(1, sonsLen(e) - 1):
  750. var it = e.sons[i]
  751. assert(it.kind in nkCallKinds)
  752. assert(it.sons[0].kind == nkSym)
  753. let op = it.sons[0].sym
  754. if op.magic == mNot: it = it.sons[1]
  755. let disc = it.sons[2].skipConv
  756. assert(disc.kind == nkSym)
  757. initLoc(test, locNone, it, OnStack)
  758. initLocExpr(p, it.sons[1], u)
  759. var o = obj
  760. let d = lookupFieldAgain(p, origTy, disc.sym, o)
  761. initLoc(v, locExpr, disc, OnUnknown)
  762. v.r = o
  763. v.r.add(".")
  764. v.r.add(d.loc.r)
  765. genInExprAux(p, it, u, v, test)
  766. let id = nodeTableTestOrSet(p.module.dataCache,
  767. newStrNode(nkStrLit, field.name.s), p.module.labels)
  768. let strLit = if id == p.module.labels: getStrLit(p.module, field.name.s)
  769. else: p.module.tmpBase & rope(id)
  770. if op.magic == mNot:
  771. linefmt(p, cpsStmts,
  772. "if ($1) #raiseFieldError(((#NimStringDesc*) &$2));$n",
  773. rdLoc(test), strLit)
  774. else:
  775. linefmt(p, cpsStmts,
  776. "if (!($1)) #raiseFieldError(((#NimStringDesc*) &$2));$n",
  777. rdLoc(test), strLit)
  778. proc genCheckedRecordField(p: BProc, e: PNode, d: var TLoc) =
  779. if optFieldCheck in p.options:
  780. var a: TLoc
  781. genRecordFieldAux(p, e.sons[0], d, a)
  782. let ty = skipTypes(a.t, abstractInst)
  783. var r = rdLoc(a)
  784. let f = e.sons[0].sons[1].sym
  785. let field = lookupFieldAgain(p, ty, f, r)
  786. if field.loc.r == nil: fillObjectFields(p.module, ty)
  787. if field.loc.r == nil:
  788. internalError(e.info, "genCheckedRecordField") # generate the checks:
  789. genFieldCheck(p, e, r, field, ty)
  790. add(r, rfmt(nil, ".$1", field.loc.r))
  791. putIntoDest(p, d, e.sons[0], r, a.storage)
  792. else:
  793. genRecordField(p, e.sons[0], d)
  794. proc genArrayElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  795. var a, b: TLoc
  796. initLocExpr(p, x, a)
  797. initLocExpr(p, y, b)
  798. var ty = skipTypes(skipTypes(a.t, abstractVarRange), abstractPtrs)
  799. var first = intLiteral(firstOrd(ty))
  800. # emit range check:
  801. if optBoundsCheck in p.options and tfUncheckedArray notin ty.flags:
  802. if not isConstExpr(y):
  803. # semantic pass has already checked for const index expressions
  804. if firstOrd(ty) == 0:
  805. if (firstOrd(b.t) < firstOrd(ty)) or (lastOrd(b.t) > lastOrd(ty)):
  806. linefmt(p, cpsStmts, "if ((NU)($1) > (NU)($2)) #raiseIndexError();$n",
  807. rdCharLoc(b), intLiteral(lastOrd(ty)))
  808. else:
  809. linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseIndexError();$n",
  810. rdCharLoc(b), first, intLiteral(lastOrd(ty)))
  811. else:
  812. let idx = getOrdValue(y)
  813. if idx < firstOrd(ty) or idx > lastOrd(ty):
  814. localError(x.info, errIndexOutOfBounds)
  815. d.inheritLocation(a)
  816. putIntoDest(p, d, n,
  817. rfmt(nil, "$1[($2)- $3]", rdLoc(a), rdCharLoc(b), first), a.storage)
  818. proc genCStringElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  819. var a, b: TLoc
  820. initLocExpr(p, x, a)
  821. initLocExpr(p, y, b)
  822. var ty = skipTypes(a.t, abstractVarRange)
  823. inheritLocation(d, a)
  824. putIntoDest(p, d, n,
  825. rfmt(nil, "$1[$2]", rdLoc(a), rdCharLoc(b)), a.storage)
  826. proc genOpenArrayElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  827. var a, b: TLoc
  828. initLocExpr(p, x, a)
  829. initLocExpr(p, y, b) # emit range check:
  830. if optBoundsCheck in p.options:
  831. linefmt(p, cpsStmts, "if ((NU)($1) >= (NU)($2Len_0)) #raiseIndexError();$n",
  832. rdLoc(b), rdLoc(a)) # BUGFIX: ``>=`` and not ``>``!
  833. inheritLocation(d, a)
  834. putIntoDest(p, d, n,
  835. rfmt(nil, "$1[$2]", rdLoc(a), rdCharLoc(b)), a.storage)
  836. proc genSeqElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  837. var a, b: TLoc
  838. initLocExpr(p, x, a)
  839. initLocExpr(p, y, b)
  840. var ty = skipTypes(a.t, abstractVarRange)
  841. if ty.kind in {tyRef, tyPtr}:
  842. ty = skipTypes(ty.lastSon, abstractVarRange) # emit range check:
  843. if optBoundsCheck in p.options:
  844. if ty.kind == tyString:
  845. linefmt(p, cpsStmts,
  846. "if ((NU)($1) > (NU)($2->$3)) #raiseIndexError();$n",
  847. rdLoc(b), rdLoc(a), lenField(p))
  848. else:
  849. linefmt(p, cpsStmts,
  850. "if ((NU)($1) >= (NU)($2->$3)) #raiseIndexError();$n",
  851. rdLoc(b), rdLoc(a), lenField(p))
  852. if d.k == locNone: d.storage = OnHeap
  853. if skipTypes(a.t, abstractVar).kind in {tyRef, tyPtr}:
  854. a.r = rfmt(nil, "(*$1)", a.r)
  855. putIntoDest(p, d, n,
  856. rfmt(nil, "$1->data[$2]", rdLoc(a), rdCharLoc(b)), a.storage)
  857. proc genBracketExpr(p: BProc; n: PNode; d: var TLoc) =
  858. var ty = skipTypes(n.sons[0].typ, abstractVarRange + tyUserTypeClasses)
  859. if ty.kind in {tyRef, tyPtr}: ty = skipTypes(ty.lastSon, abstractVarRange)
  860. case ty.kind
  861. of tyArray: genArrayElem(p, n, n.sons[0], n.sons[1], d)
  862. of tyOpenArray, tyVarargs: genOpenArrayElem(p, n, n.sons[0], n.sons[1], d)
  863. of tySequence, tyString: genSeqElem(p, n, n.sons[0], n.sons[1], d)
  864. of tyCString: genCStringElem(p, n, n.sons[0], n.sons[1], d)
  865. of tyTuple: genTupleElem(p, n, d)
  866. else: internalError(n.info, "expr(nkBracketExpr, " & $ty.kind & ')')
  867. proc genAndOr(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  868. # how to generate code?
  869. # 'expr1 and expr2' becomes:
  870. # result = expr1
  871. # fjmp result, end
  872. # result = expr2
  873. # end:
  874. # ... (result computed)
  875. # BUGFIX:
  876. # a = b or a
  877. # used to generate:
  878. # a = b
  879. # if a: goto end
  880. # a = a
  881. # end:
  882. # now it generates:
  883. # tmp = b
  884. # if tmp: goto end
  885. # tmp = a
  886. # end:
  887. # a = tmp
  888. var
  889. L: TLabel
  890. tmp: TLoc
  891. getTemp(p, e.typ, tmp) # force it into a temp!
  892. inc p.splitDecls
  893. expr(p, e.sons[1], tmp)
  894. L = getLabel(p)
  895. if m == mOr:
  896. lineF(p, cpsStmts, "if ($1) goto $2;$n", [rdLoc(tmp), L])
  897. else:
  898. lineF(p, cpsStmts, "if (!($1)) goto $2;$n", [rdLoc(tmp), L])
  899. expr(p, e.sons[2], tmp)
  900. fixLabel(p, L)
  901. if d.k == locNone:
  902. d = tmp
  903. else:
  904. genAssignment(p, d, tmp, {}) # no need for deep copying
  905. dec p.splitDecls
  906. proc genEcho(p: BProc, n: PNode) =
  907. # this unusal way of implementing it ensures that e.g. ``echo("hallo", 45)``
  908. # is threadsafe.
  909. internalAssert n.kind == nkBracket
  910. if platform.targetOS == osGenode:
  911. # bypass libc and print directly to the Genode LOG session
  912. var args: Rope = nil
  913. var a: TLoc
  914. for i in countup(0, n.len-1):
  915. if n.sons[i].skipConv.kind == nkNilLit:
  916. add(args, ", \"nil\"")
  917. else:
  918. initLocExpr(p, n.sons[i], a)
  919. addf(args, ", $1? ($1)->data:\"nil\"", [rdLoc(a)])
  920. p.module.includeHeader("<base/log.h>")
  921. linefmt(p, cpsStmts, """Genode::log(""$1);$n""", args)
  922. else:
  923. if n.len == 0:
  924. linefmt(p, cpsStmts, "#echoBinSafe(NIM_NIL, $1);$n", n.len.rope)
  925. else:
  926. var a: TLoc
  927. initLocExpr(p, n, a)
  928. linefmt(p, cpsStmts, "#echoBinSafe($1, $2);$n", a.rdLoc, n.len.rope)
  929. when false:
  930. p.module.includeHeader("<stdio.h>")
  931. linefmt(p, cpsStmts, "printf($1$2);$n",
  932. makeCString(repeat("%s", n.len) & tnl), args)
  933. linefmt(p, cpsStmts, "fflush(stdout);$n")
  934. proc gcUsage(n: PNode) =
  935. if gSelectedGC == gcNone: message(n.info, warnGcMem, n.renderTree)
  936. proc genStrConcat(p: BProc, e: PNode, d: var TLoc) =
  937. # <Nim code>
  938. # s = 'Hello ' & name & ', how do you feel?' & 'z'
  939. #
  940. # <generated C code>
  941. # {
  942. # string tmp0;
  943. # ...
  944. # tmp0 = rawNewString(6 + 17 + 1 + s2->len);
  945. # // we cannot generate s = rawNewString(...) here, because
  946. # // ``s`` may be used on the right side of the expression
  947. # appendString(tmp0, strlit_1);
  948. # appendString(tmp0, name);
  949. # appendString(tmp0, strlit_2);
  950. # appendChar(tmp0, 'z');
  951. # asgn(s, tmp0);
  952. # }
  953. var a, tmp: TLoc
  954. getTemp(p, e.typ, tmp)
  955. var L = 0
  956. var appends: Rope = nil
  957. var lens: Rope = nil
  958. for i in countup(0, sonsLen(e) - 2):
  959. # compute the length expression:
  960. initLocExpr(p, e.sons[i + 1], a)
  961. if skipTypes(e.sons[i + 1].typ, abstractVarRange).kind == tyChar:
  962. inc(L)
  963. add(appends, rfmt(p.module, "#appendChar($1, $2);$n", tmp.r, rdLoc(a)))
  964. else:
  965. if e.sons[i + 1].kind in {nkStrLit..nkTripleStrLit}:
  966. inc(L, len(e.sons[i + 1].strVal))
  967. else:
  968. addf(lens, "$1->$2 + ", [rdLoc(a), lenField(p)])
  969. add(appends, rfmt(p.module, "#appendString($1, $2);$n", tmp.r, rdLoc(a)))
  970. linefmt(p, cpsStmts, "$1 = #rawNewString($2$3);$n", tmp.r, lens, rope(L))
  971. add(p.s(cpsStmts), appends)
  972. if d.k == locNone:
  973. d = tmp
  974. else:
  975. genAssignment(p, d, tmp, {}) # no need for deep copying
  976. gcUsage(e)
  977. proc genStrAppend(p: BProc, e: PNode, d: var TLoc) =
  978. # <Nim code>
  979. # s &= 'Hello ' & name & ', how do you feel?' & 'z'
  980. # // BUG: what if s is on the left side too?
  981. # <generated C code>
  982. # {
  983. # s = resizeString(s, 6 + 17 + 1 + name->len);
  984. # appendString(s, strlit_1);
  985. # appendString(s, name);
  986. # appendString(s, strlit_2);
  987. # appendChar(s, 'z');
  988. # }
  989. var
  990. a, dest: TLoc
  991. appends, lens: Rope
  992. assert(d.k == locNone)
  993. var L = 0
  994. initLocExpr(p, e.sons[1], dest)
  995. for i in countup(0, sonsLen(e) - 3):
  996. # compute the length expression:
  997. initLocExpr(p, e.sons[i + 2], a)
  998. if skipTypes(e.sons[i + 2].typ, abstractVarRange).kind == tyChar:
  999. inc(L)
  1000. add(appends, rfmt(p.module, "#appendChar($1, $2);$n",
  1001. rdLoc(dest), rdLoc(a)))
  1002. else:
  1003. if e.sons[i + 2].kind in {nkStrLit..nkTripleStrLit}:
  1004. inc(L, len(e.sons[i + 2].strVal))
  1005. else:
  1006. addf(lens, "$1->$2 + ", [rdLoc(a), lenField(p)])
  1007. add(appends, rfmt(p.module, "#appendString($1, $2);$n",
  1008. rdLoc(dest), rdLoc(a)))
  1009. linefmt(p, cpsStmts, "$1 = #resizeString($1, $2$3);$n",
  1010. rdLoc(dest), lens, rope(L))
  1011. add(p.s(cpsStmts), appends)
  1012. gcUsage(e)
  1013. proc genSeqElemAppend(p: BProc, e: PNode, d: var TLoc) =
  1014. # seq &= x -->
  1015. # seq = (typeof seq) incrSeq(&seq->Sup, sizeof(x));
  1016. # seq->data[seq->len-1] = x;
  1017. let seqAppendPattern = if not p.module.compileToCpp:
  1018. "$1 = ($2) #incrSeqV2(&($1)->Sup, sizeof($3));$n"
  1019. else:
  1020. "$1 = ($2) #incrSeqV2($1, sizeof($3));$n"
  1021. var a, b, dest, tmpL: TLoc
  1022. initLocExpr(p, e.sons[1], a)
  1023. initLocExpr(p, e.sons[2], b)
  1024. let bt = skipTypes(e.sons[2].typ, {tyVar})
  1025. lineCg(p, cpsStmts, seqAppendPattern, [
  1026. rdLoc(a),
  1027. getTypeDesc(p.module, e.sons[1].typ),
  1028. getTypeDesc(p.module, bt)])
  1029. #if bt != b.t:
  1030. # echo "YES ", e.info, " new: ", typeToString(bt), " old: ", typeToString(b.t)
  1031. initLoc(dest, locExpr, e.sons[2], OnHeap)
  1032. getIntTemp(p, tmpL)
  1033. lineCg(p, cpsStmts, "$1 = $2->$3++;$n", tmpL.r, rdLoc(a), lenField(p))
  1034. dest.r = rfmt(nil, "$1->data[$2]", rdLoc(a), tmpL.r)
  1035. genAssignment(p, dest, b, {needToCopy, afDestIsNil})
  1036. gcUsage(e)
  1037. proc genReset(p: BProc, n: PNode) =
  1038. var a: TLoc
  1039. initLocExpr(p, n.sons[1], a)
  1040. linefmt(p, cpsStmts, "#genericReset((void*)$1, $2);$n",
  1041. addrLoc(a), genTypeInfo(p.module, skipTypes(a.t, {tyVar})))
  1042. proc rawGenNew(p: BProc, a: TLoc, sizeExpr: Rope) =
  1043. var sizeExpr = sizeExpr
  1044. let typ = a.t
  1045. var b: TLoc
  1046. initLoc(b, locExpr, a.lode, OnHeap)
  1047. let refType = typ.skipTypes(abstractInst)
  1048. assert refType.kind == tyRef
  1049. let bt = refType.lastSon
  1050. if sizeExpr.isNil:
  1051. sizeExpr = "sizeof($1)" %
  1052. [getTypeDesc(p.module, bt)]
  1053. let args = [getTypeDesc(p.module, typ),
  1054. genTypeInfo(p.module, typ),
  1055. sizeExpr]
  1056. if a.storage == OnHeap and usesNativeGC():
  1057. # use newObjRC1 as an optimization
  1058. if canFormAcycle(a.t):
  1059. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefRC1($1); $1 = NIM_NIL; }$n", a.rdLoc)
  1060. else:
  1061. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefNoCycle($1); $1 = NIM_NIL; }$n", a.rdLoc)
  1062. b.r = ropecg(p.module, "($1) #newObjRC1($2, $3)", args)
  1063. linefmt(p, cpsStmts, "$1 = $2;$n", a.rdLoc, b.rdLoc)
  1064. else:
  1065. b.r = ropecg(p.module, "($1) #newObj($2, $3)", args)
  1066. genAssignment(p, a, b, {}) # set the object type:
  1067. genObjectInit(p, cpsStmts, bt, a, false)
  1068. proc genNew(p: BProc, e: PNode) =
  1069. var a: TLoc
  1070. initLocExpr(p, e.sons[1], a)
  1071. # 'genNew' also handles 'unsafeNew':
  1072. if e.len == 3:
  1073. var se: TLoc
  1074. initLocExpr(p, e.sons[2], se)
  1075. rawGenNew(p, a, se.rdLoc)
  1076. else:
  1077. rawGenNew(p, a, nil)
  1078. gcUsage(e)
  1079. proc genNewSeqAux(p: BProc, dest: TLoc, length: Rope) =
  1080. let seqtype = skipTypes(dest.t, abstractVarRange)
  1081. let args = [getTypeDesc(p.module, seqtype),
  1082. genTypeInfo(p.module, seqtype), length]
  1083. var call: TLoc
  1084. initLoc(call, locExpr, dest.lode, OnHeap)
  1085. if dest.storage == OnHeap and usesNativeGC():
  1086. if canFormAcycle(dest.t):
  1087. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefRC1($1); $1 = NIM_NIL; }$n", dest.rdLoc)
  1088. else:
  1089. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefNoCycle($1); $1 = NIM_NIL; }$n", dest.rdLoc)
  1090. call.r = ropecg(p.module, "($1) #newSeqRC1($2, $3)", args)
  1091. linefmt(p, cpsStmts, "$1 = $2;$n", dest.rdLoc, call.rdLoc)
  1092. else:
  1093. call.r = ropecg(p.module, "($1) #newSeq($2, $3)", args)
  1094. genAssignment(p, dest, call, {})
  1095. proc genNewSeq(p: BProc, e: PNode) =
  1096. var a, b: TLoc
  1097. initLocExpr(p, e.sons[1], a)
  1098. initLocExpr(p, e.sons[2], b)
  1099. genNewSeqAux(p, a, b.rdLoc)
  1100. gcUsage(e)
  1101. proc genNewSeqOfCap(p: BProc; e: PNode; d: var TLoc) =
  1102. let seqtype = skipTypes(e.typ, abstractVarRange)
  1103. var a: TLoc
  1104. initLocExpr(p, e.sons[1], a)
  1105. putIntoDest(p, d, e, ropecg(p.module,
  1106. "($1)#nimNewSeqOfCap($2, $3)", [
  1107. getTypeDesc(p.module, seqtype),
  1108. genTypeInfo(p.module, seqtype), a.rdLoc]))
  1109. gcUsage(e)
  1110. proc genConstExpr(p: BProc, n: PNode): Rope
  1111. proc handleConstExpr(p: BProc, n: PNode, d: var TLoc): bool =
  1112. if d.k == locNone and n.len > ord(n.kind == nkObjConstr) and n.isDeepConstExpr:
  1113. let t = n.typ
  1114. discard getTypeDesc(p.module, t) # so that any fields are initialized
  1115. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  1116. fillLoc(d, locData, n, p.module.tmpBase & rope(id), OnStatic)
  1117. if id == p.module.labels:
  1118. # expression not found in the cache:
  1119. inc(p.module.labels)
  1120. addf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
  1121. [getTypeDesc(p.module, t), d.r, genConstExpr(p, n)])
  1122. result = true
  1123. else:
  1124. result = false
  1125. proc genObjConstr(p: BProc, e: PNode, d: var TLoc) =
  1126. #echo rendertree e, " ", e.isDeepConstExpr
  1127. # inheritance in C++ does not allow struct initialization so
  1128. # we skip this step here:
  1129. if not p.module.compileToCpp:
  1130. if handleConstExpr(p, e, d): return
  1131. var tmp: TLoc
  1132. var t = e.typ.skipTypes(abstractInst)
  1133. getTemp(p, t, tmp)
  1134. let isRef = t.kind == tyRef
  1135. var r = rdLoc(tmp)
  1136. if isRef:
  1137. rawGenNew(p, tmp, nil)
  1138. t = t.lastSon.skipTypes(abstractInst)
  1139. r = "(*$1)" % [r]
  1140. gcUsage(e)
  1141. else:
  1142. constructLoc(p, tmp)
  1143. discard getTypeDesc(p.module, t)
  1144. let ty = getUniqueType(t)
  1145. for i in 1 .. <e.len:
  1146. let it = e.sons[i]
  1147. var tmp2: TLoc
  1148. tmp2.r = r
  1149. let field = lookupFieldAgain(p, ty, it.sons[0].sym, tmp2.r)
  1150. if field.loc.r == nil: fillObjectFields(p.module, ty)
  1151. if field.loc.r == nil: internalError(e.info, "genObjConstr")
  1152. if it.len == 3 and optFieldCheck in p.options:
  1153. genFieldCheck(p, it.sons[2], r, field, ty)
  1154. add(tmp2.r, ".")
  1155. add(tmp2.r, field.loc.r)
  1156. tmp2.k = locTemp
  1157. tmp2.lode = it.sons[1]
  1158. tmp2.storage = if isRef: OnHeap else: OnStack
  1159. expr(p, it.sons[1], tmp2)
  1160. if d.k == locNone:
  1161. d = tmp
  1162. else:
  1163. genAssignment(p, d, tmp, {})
  1164. proc genSeqConstr(p: BProc, n: PNode, d: var TLoc) =
  1165. var arr: TLoc
  1166. if d.k == locNone:
  1167. getTemp(p, n.typ, d)
  1168. # generate call to newSeq before adding the elements per hand:
  1169. genNewSeqAux(p, d, intLiteral(sonsLen(n)))
  1170. for i in countup(0, sonsLen(n) - 1):
  1171. initLoc(arr, locExpr, n[i], OnHeap)
  1172. arr.r = rfmt(nil, "$1->data[$2]", rdLoc(d), intLiteral(i))
  1173. arr.storage = OnHeap # we know that sequences are on the heap
  1174. expr(p, n[i], arr)
  1175. gcUsage(n)
  1176. proc genArrToSeq(p: BProc, n: PNode, d: var TLoc) =
  1177. var elem, a, arr: TLoc
  1178. if n.sons[1].kind == nkBracket:
  1179. n.sons[1].typ = n.typ
  1180. genSeqConstr(p, n.sons[1], d)
  1181. return
  1182. if d.k == locNone:
  1183. getTemp(p, n.typ, d)
  1184. # generate call to newSeq before adding the elements per hand:
  1185. let L = int(lengthOrd(n.sons[1].typ))
  1186. genNewSeqAux(p, d, intLiteral(L))
  1187. initLocExpr(p, n.sons[1], a)
  1188. # bug #5007; do not produce excessive C source code:
  1189. if L < 10:
  1190. for i in countup(0, L - 1):
  1191. initLoc(elem, locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), OnHeap)
  1192. elem.r = rfmt(nil, "$1->data[$2]", rdLoc(d), intLiteral(i))
  1193. elem.storage = OnHeap # we know that sequences are on the heap
  1194. initLoc(arr, locExpr, lodeTyp elemType(skipTypes(n.sons[1].typ, abstractInst)), a.storage)
  1195. arr.r = rfmt(nil, "$1[$2]", rdLoc(a), intLiteral(i))
  1196. genAssignment(p, elem, arr, {afDestIsNil, needToCopy})
  1197. else:
  1198. var i: TLoc
  1199. getTemp(p, getSysType(tyInt), i)
  1200. let oldCode = p.s(cpsStmts)
  1201. linefmt(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n", i.r, L.rope)
  1202. initLoc(elem, locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), OnHeap)
  1203. elem.r = rfmt(nil, "$1->data[$2]", rdLoc(d), rdLoc(i))
  1204. elem.storage = OnHeap # we know that sequences are on the heap
  1205. initLoc(arr, locExpr, lodeTyp elemType(skipTypes(n.sons[1].typ, abstractInst)), a.storage)
  1206. arr.r = rfmt(nil, "$1[$2]", rdLoc(a), rdLoc(i))
  1207. genAssignment(p, elem, arr, {afDestIsNil, needToCopy})
  1208. lineF(p, cpsStmts, "}$n", [])
  1209. proc genNewFinalize(p: BProc, e: PNode) =
  1210. var
  1211. a, b, f: TLoc
  1212. refType, bt: PType
  1213. ti: Rope
  1214. refType = skipTypes(e.sons[1].typ, abstractVarRange)
  1215. initLocExpr(p, e.sons[1], a)
  1216. initLocExpr(p, e.sons[2], f)
  1217. initLoc(b, locExpr, a.lode, OnHeap)
  1218. ti = genTypeInfo(p.module, refType)
  1219. addf(p.module.s[cfsTypeInit3], "$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)])
  1220. b.r = ropecg(p.module, "($1) #newObj($2, sizeof($3))", [
  1221. getTypeDesc(p.module, refType),
  1222. ti, getTypeDesc(p.module, skipTypes(refType.lastSon, abstractRange))])
  1223. genAssignment(p, a, b, {}) # set the object type:
  1224. bt = skipTypes(refType.lastSon, abstractRange)
  1225. genObjectInit(p, cpsStmts, bt, a, false)
  1226. gcUsage(e)
  1227. proc genOfHelper(p: BProc; dest: PType; a: Rope): Rope =
  1228. # unfortunately 'genTypeInfo' sets tfObjHasKids as a side effect, so we
  1229. # have to call it here first:
  1230. let ti = genTypeInfo(p.module, dest)
  1231. if tfFinal in dest.flags or (objHasKidsValid in p.module.flags and
  1232. tfObjHasKids notin dest.flags):
  1233. result = "$1.m_type == $2" % [a, ti]
  1234. else:
  1235. discard cgsym(p.module, "TNimType")
  1236. inc p.module.labels
  1237. let cache = "Nim_OfCheck_CACHE" & p.module.labels.rope
  1238. addf(p.module.s[cfsVars], "static TNimType* $#[2];$n", [cache])
  1239. result = rfmt(p.module, "#isObjWithCache($#.m_type, $#, $#)", a, ti, cache)
  1240. when false:
  1241. # former version:
  1242. result = rfmt(p.module, "#isObj($1.m_type, $2)",
  1243. a, genTypeInfo(p.module, dest))
  1244. proc genOf(p: BProc, x: PNode, typ: PType, d: var TLoc) =
  1245. var a: TLoc
  1246. initLocExpr(p, x, a)
  1247. var dest = skipTypes(typ, typedescPtrs)
  1248. var r = rdLoc(a)
  1249. var nilCheck: Rope = nil
  1250. var t = skipTypes(a.t, abstractInst)
  1251. while t.kind in {tyVar, tyPtr, tyRef}:
  1252. if t.kind != tyVar: nilCheck = r
  1253. if t.kind != tyVar or not p.module.compileToCpp:
  1254. r = rfmt(nil, "(*$1)", r)
  1255. t = skipTypes(t.lastSon, typedescInst)
  1256. if not p.module.compileToCpp:
  1257. while t.kind == tyObject and t.sons[0] != nil:
  1258. add(r, ~".Sup")
  1259. t = skipTypes(t.sons[0], skipPtrs)
  1260. if isObjLackingTypeField(t):
  1261. globalError(x.info, errGenerated,
  1262. "no 'of' operator available for pure objects")
  1263. if nilCheck != nil:
  1264. r = rfmt(p.module, "(($1) && ($2))", nilCheck, genOfHelper(p, dest, r))
  1265. else:
  1266. r = rfmt(p.module, "($1)", genOfHelper(p, dest, r))
  1267. putIntoDest(p, d, x, r, a.storage)
  1268. proc genOf(p: BProc, n: PNode, d: var TLoc) =
  1269. genOf(p, n.sons[1], n.sons[2].typ, d)
  1270. proc genRepr(p: BProc, e: PNode, d: var TLoc) =
  1271. var a: TLoc
  1272. initLocExpr(p, e.sons[1], a)
  1273. var t = skipTypes(e.sons[1].typ, abstractVarRange)
  1274. case t.kind
  1275. of tyInt..tyInt64, tyUInt..tyUInt64:
  1276. putIntoDest(p, d, e,
  1277. ropecg(p.module, "#reprInt((NI64)$1)", [rdLoc(a)]), a.storage)
  1278. of tyFloat..tyFloat128:
  1279. putIntoDest(p, d, e, ropecg(p.module, "#reprFloat($1)", [rdLoc(a)]), a.storage)
  1280. of tyBool:
  1281. putIntoDest(p, d, e, ropecg(p.module, "#reprBool($1)", [rdLoc(a)]), a.storage)
  1282. of tyChar:
  1283. putIntoDest(p, d, e, ropecg(p.module, "#reprChar($1)", [rdLoc(a)]), a.storage)
  1284. of tyEnum, tyOrdinal:
  1285. putIntoDest(p, d, e,
  1286. ropecg(p.module, "#reprEnum((NI)$1, $2)", [
  1287. rdLoc(a), genTypeInfo(p.module, t)]), a.storage)
  1288. of tyString:
  1289. putIntoDest(p, d, e, ropecg(p.module, "#reprStr($1)", [rdLoc(a)]), a.storage)
  1290. of tySet:
  1291. putIntoDest(p, d, e, ropecg(p.module, "#reprSet($1, $2)", [
  1292. addrLoc(a), genTypeInfo(p.module, t)]), a.storage)
  1293. of tyOpenArray, tyVarargs:
  1294. var b: TLoc
  1295. case a.t.kind
  1296. of tyOpenArray, tyVarargs:
  1297. putIntoDest(p, b, e, "$1, $1Len_0" % [rdLoc(a)], a.storage)
  1298. of tyString, tySequence:
  1299. putIntoDest(p, b, e,
  1300. "$1->data, $1->$2" % [rdLoc(a), lenField(p)], a.storage)
  1301. of tyArray:
  1302. putIntoDest(p, b, e,
  1303. "$1, $2" % [rdLoc(a), rope(lengthOrd(a.t))], a.storage)
  1304. else: internalError(e.sons[0].info, "genRepr()")
  1305. putIntoDest(p, d, e,
  1306. ropecg(p.module, "#reprOpenArray($1, $2)", [rdLoc(b),
  1307. genTypeInfo(p.module, elemType(t))]), a.storage)
  1308. of tyCString, tyArray, tyRef, tyPtr, tyPointer, tyNil, tySequence:
  1309. putIntoDest(p, d, e,
  1310. ropecg(p.module, "#reprAny($1, $2)", [
  1311. rdLoc(a), genTypeInfo(p.module, t)]), a.storage)
  1312. of tyEmpty, tyVoid:
  1313. localError(e.info, "'repr' doesn't support 'void' type")
  1314. else:
  1315. putIntoDest(p, d, e, ropecg(p.module, "#reprAny($1, $2)",
  1316. [addrLoc(a), genTypeInfo(p.module, t)]),
  1317. a.storage)
  1318. gcUsage(e)
  1319. proc genGetTypeInfo(p: BProc, e: PNode, d: var TLoc) =
  1320. let t = e.sons[1].typ
  1321. putIntoDest(p, d, e, genTypeInfo(p.module, t))
  1322. proc genDollar(p: BProc, n: PNode, d: var TLoc, frmt: string) =
  1323. var a: TLoc
  1324. initLocExpr(p, n.sons[1], a)
  1325. a.r = ropecg(p.module, frmt, [rdLoc(a)])
  1326. if d.k == locNone: getTemp(p, n.typ, d)
  1327. genAssignment(p, d, a, {})
  1328. gcUsage(n)
  1329. proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1330. var a = e.sons[1]
  1331. if a.kind == nkHiddenAddr: a = a.sons[0]
  1332. var typ = skipTypes(a.typ, abstractVar + tyUserTypeClasses)
  1333. case typ.kind
  1334. of tyOpenArray, tyVarargs:
  1335. if op == mHigh: unaryExpr(p, e, d, "($1Len_0-1)")
  1336. else: unaryExpr(p, e, d, "$1Len_0")
  1337. of tyCString:
  1338. useStringh(p.module)
  1339. if op == mHigh: unaryExpr(p, e, d, "($1 ? (strlen($1)-1) : -1)")
  1340. else: unaryExpr(p, e, d, "($1 ? strlen($1) : 0)")
  1341. of tyString:
  1342. if not p.module.compileToCpp:
  1343. if op == mHigh: unaryExpr(p, e, d, "($1 ? ($1->Sup.len-1) : -1)")
  1344. else: unaryExpr(p, e, d, "($1 ? $1->Sup.len : 0)")
  1345. else:
  1346. if op == mHigh: unaryExpr(p, e, d, "($1 ? ($1->len-1) : -1)")
  1347. else: unaryExpr(p, e, d, "($1 ? $1->len : 0)")
  1348. of tySequence:
  1349. var a, tmp: TLoc
  1350. initLocExpr(p, e[1], a)
  1351. getIntTemp(p, tmp)
  1352. var frmt: FormatStr
  1353. if not p.module.compileToCpp:
  1354. if op == mHigh:
  1355. frmt = "$1 = ($2 ? ($2->Sup.len-1) : -1);$n"
  1356. else:
  1357. frmt = "$1 = ($2 ? $2->Sup.len : 0);$n"
  1358. else:
  1359. if op == mHigh:
  1360. frmt = "$1 = ($2 ? ($2->len-1) : -1);$n"
  1361. else:
  1362. frmt = "$1 = ($2 ? $2->len : 0);$n"
  1363. lineCg(p, cpsStmts, frmt, tmp.r, rdLoc(a))
  1364. putIntoDest(p, d, e, tmp.r)
  1365. of tyArray:
  1366. # YYY: length(sideeffect) is optimized away incorrectly?
  1367. if op == mHigh: putIntoDest(p, d, e, rope(lastOrd(typ)))
  1368. else: putIntoDest(p, d, e, rope(lengthOrd(typ)))
  1369. else: internalError(e.info, "genArrayLen()")
  1370. proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) =
  1371. var a, b: TLoc
  1372. assert(d.k == locNone)
  1373. var x = e.sons[1]
  1374. if x.kind in {nkAddr, nkHiddenAddr}: x = x[0]
  1375. initLocExpr(p, x, a)
  1376. initLocExpr(p, e.sons[2], b)
  1377. let t = skipTypes(e.sons[1].typ, {tyVar})
  1378. let setLenPattern = if not p.module.compileToCpp:
  1379. "$1 = ($3) #setLengthSeq(&($1)->Sup, sizeof($4), $2);$n"
  1380. else:
  1381. "$1 = ($3) #setLengthSeq($1, sizeof($4), $2);$n"
  1382. lineCg(p, cpsStmts, setLenPattern, [
  1383. rdLoc(a), rdLoc(b), getTypeDesc(p.module, t),
  1384. getTypeDesc(p.module, t.skipTypes(abstractInst).sons[0])])
  1385. gcUsage(e)
  1386. proc genSetLengthStr(p: BProc, e: PNode, d: var TLoc) =
  1387. binaryStmt(p, e, d, "$1 = #setLengthStr($1, $2);$n")
  1388. gcUsage(e)
  1389. proc genSwap(p: BProc, e: PNode, d: var TLoc) =
  1390. # swap(a, b) -->
  1391. # temp = a
  1392. # a = b
  1393. # b = temp
  1394. var a, b, tmp: TLoc
  1395. getTemp(p, skipTypes(e.sons[1].typ, abstractVar), tmp)
  1396. initLocExpr(p, e.sons[1], a) # eval a
  1397. initLocExpr(p, e.sons[2], b) # eval b
  1398. genAssignment(p, tmp, a, {})
  1399. genAssignment(p, a, b, {})
  1400. genAssignment(p, b, tmp, {})
  1401. proc rdSetElemLoc(a: TLoc, setType: PType): Rope =
  1402. # read a location of an set element; it may need a subtraction operation
  1403. # before the set operation
  1404. result = rdCharLoc(a)
  1405. assert(setType.kind == tySet)
  1406. if firstOrd(setType) != 0:
  1407. result = "($1- $2)" % [result, rope(firstOrd(setType))]
  1408. proc fewCmps(s: PNode): bool =
  1409. # this function estimates whether it is better to emit code
  1410. # for constructing the set or generating a bunch of comparisons directly
  1411. if s.kind != nkCurly: internalError(s.info, "fewCmps")
  1412. if (getSize(s.typ) <= platform.intSize) and (nfAllConst in s.flags):
  1413. result = false # it is better to emit the set generation code
  1414. elif elemType(s.typ).kind in {tyInt, tyInt16..tyInt64}:
  1415. result = true # better not emit the set if int is basetype!
  1416. else:
  1417. result = sonsLen(s) <= 8 # 8 seems to be a good value
  1418. proc binaryExprIn(p: BProc, e: PNode, a, b, d: var TLoc, frmt: string) =
  1419. putIntoDest(p, d, e, frmt % [rdLoc(a), rdSetElemLoc(b, a.t)])
  1420. proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc) =
  1421. case int(getSize(skipTypes(e.sons[1].typ, abstractVar)))
  1422. of 1: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&7U)))!=0)")
  1423. of 2: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&15U)))!=0)")
  1424. of 4: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&31U)))!=0)")
  1425. of 8: binaryExprIn(p, e, a, b, d, "(($1 &((NU64)1<<((NU)($2)&63U)))!=0)")
  1426. else: binaryExprIn(p, e, a, b, d, "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)")
  1427. proc binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  1428. var a, b: TLoc
  1429. assert(d.k == locNone)
  1430. initLocExpr(p, e.sons[1], a)
  1431. initLocExpr(p, e.sons[2], b)
  1432. lineF(p, cpsStmts, frmt, [rdLoc(a), rdSetElemLoc(b, a.t)])
  1433. proc genInOp(p: BProc, e: PNode, d: var TLoc) =
  1434. var a, b, x, y: TLoc
  1435. if (e.sons[1].kind == nkCurly) and fewCmps(e.sons[1]):
  1436. # a set constructor but not a constant set:
  1437. # do not emit the set, but generate a bunch of comparisons; and if we do
  1438. # so, we skip the unnecessary range check: This is a semantical extension
  1439. # that code now relies on. :-/ XXX
  1440. let ea = if e.sons[2].kind in {nkChckRange, nkChckRange64}:
  1441. e.sons[2].sons[0]
  1442. else:
  1443. e.sons[2]
  1444. initLocExpr(p, ea, a)
  1445. initLoc(b, locExpr, e, OnUnknown)
  1446. b.r = rope("(")
  1447. var length = sonsLen(e.sons[1])
  1448. for i in countup(0, length - 1):
  1449. if e.sons[1].sons[i].kind == nkRange:
  1450. initLocExpr(p, e.sons[1].sons[i].sons[0], x)
  1451. initLocExpr(p, e.sons[1].sons[i].sons[1], y)
  1452. addf(b.r, "$1 >= $2 && $1 <= $3",
  1453. [rdCharLoc(a), rdCharLoc(x), rdCharLoc(y)])
  1454. else:
  1455. initLocExpr(p, e.sons[1].sons[i], x)
  1456. addf(b.r, "$1 == $2", [rdCharLoc(a), rdCharLoc(x)])
  1457. if i < length - 1: add(b.r, " || ")
  1458. add(b.r, ")")
  1459. putIntoDest(p, d, e, b.r)
  1460. else:
  1461. assert(e.sons[1].typ != nil)
  1462. assert(e.sons[2].typ != nil)
  1463. initLocExpr(p, e.sons[1], a)
  1464. initLocExpr(p, e.sons[2], b)
  1465. genInExprAux(p, e, a, b, d)
  1466. proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1467. const
  1468. lookupOpr: array[mLeSet..mSymDiffSet, string] = [
  1469. "for ($1 = 0; $1 < $2; $1++) { $n" &
  1470. " $3 = (($4[$1] & ~ $5[$1]) == 0);$n" &
  1471. " if (!$3) break;}$n", "for ($1 = 0; $1 < $2; $1++) { $n" &
  1472. " $3 = (($4[$1] & ~ $5[$1]) == 0);$n" & " if (!$3) break;}$n" &
  1473. "if ($3) $3 = (memcmp($4, $5, $2) != 0);$n",
  1474. "&", "|", "& ~", "^"]
  1475. var a, b, i: TLoc
  1476. var setType = skipTypes(e.sons[1].typ, abstractVar)
  1477. var size = int(getSize(setType))
  1478. case size
  1479. of 1, 2, 4, 8:
  1480. case op
  1481. of mIncl:
  1482. var ts = "NU" & $(size * 8)
  1483. binaryStmtInExcl(p, e, d,
  1484. "$1 |= ((" & ts & ")1)<<(($2)%(sizeof(" & ts & ")*8));$n")
  1485. of mExcl:
  1486. var ts = "NU" & $(size * 8)
  1487. binaryStmtInExcl(p, e, d, "$1 &= ~(((" & ts & ")1) << (($2) % (sizeof(" &
  1488. ts & ")*8)));$n")
  1489. of mCard:
  1490. if size <= 4: unaryExprChar(p, e, d, "#countBits32($1)")
  1491. else: unaryExprChar(p, e, d, "#countBits64($1)")
  1492. of mLtSet: binaryExprChar(p, e, d, "(($1 & ~ $2 ==0)&&($1 != $2))")
  1493. of mLeSet: binaryExprChar(p, e, d, "(($1 & ~ $2)==0)")
  1494. of mEqSet: binaryExpr(p, e, d, "($1 == $2)")
  1495. of mMulSet: binaryExpr(p, e, d, "($1 & $2)")
  1496. of mPlusSet: binaryExpr(p, e, d, "($1 | $2)")
  1497. of mMinusSet: binaryExpr(p, e, d, "($1 & ~ $2)")
  1498. of mSymDiffSet: binaryExpr(p, e, d, "($1 ^ $2)")
  1499. of mInSet:
  1500. genInOp(p, e, d)
  1501. else: internalError(e.info, "genSetOp()")
  1502. else:
  1503. case op
  1504. of mIncl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n")
  1505. of mExcl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n")
  1506. of mCard: unaryExprChar(p, e, d, "#cardSet($1, " & $size & ')')
  1507. of mLtSet, mLeSet:
  1508. getTemp(p, getSysType(tyInt), i) # our counter
  1509. initLocExpr(p, e.sons[1], a)
  1510. initLocExpr(p, e.sons[2], b)
  1511. if d.k == locNone: getTemp(p, getSysType(tyBool), d)
  1512. lineF(p, cpsStmts, lookupOpr[op],
  1513. [rdLoc(i), rope(size), rdLoc(d), rdLoc(a), rdLoc(b)])
  1514. of mEqSet:
  1515. useStringh(p.module)
  1516. binaryExprChar(p, e, d, "(memcmp($1, $2, " & $(size) & ")==0)")
  1517. of mMulSet, mPlusSet, mMinusSet, mSymDiffSet:
  1518. # we inline the simple for loop for better code generation:
  1519. getTemp(p, getSysType(tyInt), i) # our counter
  1520. initLocExpr(p, e.sons[1], a)
  1521. initLocExpr(p, e.sons[2], b)
  1522. if d.k == locNone: getTemp(p, a.t, d)
  1523. lineF(p, cpsStmts,
  1524. "for ($1 = 0; $1 < $2; $1++) $n" &
  1525. " $3[$1] = $4[$1] $6 $5[$1];$n", [
  1526. rdLoc(i), rope(size), rdLoc(d), rdLoc(a), rdLoc(b),
  1527. rope(lookupOpr[op])])
  1528. of mInSet: genInOp(p, e, d)
  1529. else: internalError(e.info, "genSetOp")
  1530. proc genOrd(p: BProc, e: PNode, d: var TLoc) =
  1531. unaryExprChar(p, e, d, "$1")
  1532. proc genSomeCast(p: BProc, e: PNode, d: var TLoc) =
  1533. const
  1534. ValueTypes = {tyTuple, tyObject, tyArray, tyOpenArray, tyVarargs}
  1535. # we use whatever C gives us. Except if we have a value-type, we need to go
  1536. # through its address:
  1537. var a: TLoc
  1538. initLocExpr(p, e.sons[1], a)
  1539. let etyp = skipTypes(e.typ, abstractRange)
  1540. if etyp.kind in ValueTypes and lfIndirect notin a.flags:
  1541. putIntoDest(p, d, e, "(*($1*) ($2))" %
  1542. [getTypeDesc(p.module, e.typ), addrLoc(a)], a.storage)
  1543. elif etyp.kind == tyProc and etyp.callConv == ccClosure:
  1544. putIntoDest(p, d, e, "(($1) ($2))" %
  1545. [getClosureType(p.module, etyp, clHalfWithEnv), rdCharLoc(a)], a.storage)
  1546. else:
  1547. putIntoDest(p, d, e, "(($1) ($2))" %
  1548. [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
  1549. proc genCast(p: BProc, e: PNode, d: var TLoc) =
  1550. const ValueTypes = {tyFloat..tyFloat128, tyTuple, tyObject, tyArray}
  1551. let
  1552. destt = skipTypes(e.typ, abstractRange)
  1553. srct = skipTypes(e.sons[1].typ, abstractRange)
  1554. if destt.kind in ValueTypes or srct.kind in ValueTypes:
  1555. # 'cast' and some float type involved? --> use a union.
  1556. inc(p.labels)
  1557. var lbl = p.labels.rope
  1558. var tmp: TLoc
  1559. tmp.r = "LOC$1.source" % [lbl]
  1560. linefmt(p, cpsLocals, "union { $1 source; $2 dest; } LOC$3;$n",
  1561. getTypeDesc(p.module, e.sons[1].typ), getTypeDesc(p.module, e.typ), lbl)
  1562. tmp.k = locExpr
  1563. tmp.lode = lodeTyp srct
  1564. tmp.storage = OnStack
  1565. tmp.flags = {}
  1566. expr(p, e.sons[1], tmp)
  1567. putIntoDest(p, d, e, "LOC$#.dest" % [lbl], tmp.storage)
  1568. else:
  1569. # I prefer the shorter cast version for pointer types -> generate less
  1570. # C code; plus it's the right thing to do for closures:
  1571. genSomeCast(p, e, d)
  1572. proc genRangeChck(p: BProc, n: PNode, d: var TLoc, magic: string) =
  1573. var a: TLoc
  1574. var dest = skipTypes(n.typ, abstractVar)
  1575. # range checks for unsigned turned out to be buggy and annoying:
  1576. if optRangeCheck notin p.options or dest.skipTypes({tyRange}).kind in
  1577. {tyUInt..tyUInt64}:
  1578. initLocExpr(p, n.sons[0], a)
  1579. putIntoDest(p, d, n, "(($1) ($2))" %
  1580. [getTypeDesc(p.module, dest), rdCharLoc(a)], a.storage)
  1581. else:
  1582. initLocExpr(p, n.sons[0], a)
  1583. putIntoDest(p, d, lodeTyp dest, ropecg(p.module, "(($1)#$5($2, $3, $4))", [
  1584. getTypeDesc(p.module, dest), rdCharLoc(a),
  1585. genLiteral(p, n.sons[1], dest), genLiteral(p, n.sons[2], dest),
  1586. rope(magic)]), a.storage)
  1587. proc genConv(p: BProc, e: PNode, d: var TLoc) =
  1588. let destType = e.typ.skipTypes({tyVar, tyGenericInst, tyAlias})
  1589. if compareTypes(destType, e.sons[1].typ, dcEqIgnoreDistinct):
  1590. expr(p, e.sons[1], d)
  1591. else:
  1592. genSomeCast(p, e, d)
  1593. proc convStrToCStr(p: BProc, n: PNode, d: var TLoc) =
  1594. var a: TLoc
  1595. initLocExpr(p, n.sons[0], a)
  1596. putIntoDest(p, d, n, "$1->data" % [rdLoc(a)],
  1597. a.storage)
  1598. proc convCStrToStr(p: BProc, n: PNode, d: var TLoc) =
  1599. var a: TLoc
  1600. initLocExpr(p, n.sons[0], a)
  1601. putIntoDest(p, d, n,
  1602. ropecg(p.module, "#cstrToNimstr($1)", [rdLoc(a)]),
  1603. a.storage)
  1604. gcUsage(n)
  1605. proc genStrEquals(p: BProc, e: PNode, d: var TLoc) =
  1606. var x: TLoc
  1607. var a = e.sons[1]
  1608. var b = e.sons[2]
  1609. if (a.kind == nkNilLit) or (b.kind == nkNilLit):
  1610. binaryExpr(p, e, d, "($1 == $2)")
  1611. elif (a.kind in {nkStrLit..nkTripleStrLit}) and (a.strVal == ""):
  1612. initLocExpr(p, e.sons[2], x)
  1613. putIntoDest(p, d, e,
  1614. rfmt(nil, "(($1) && ($1)->$2 == 0)", rdLoc(x), lenField(p)))
  1615. elif (b.kind in {nkStrLit..nkTripleStrLit}) and (b.strVal == ""):
  1616. initLocExpr(p, e.sons[1], x)
  1617. putIntoDest(p, d, e,
  1618. rfmt(nil, "(($1) && ($1)->$2 == 0)", rdLoc(x), lenField(p)))
  1619. else:
  1620. binaryExpr(p, e, d, "#eqStrings($1, $2)")
  1621. proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  1622. if {optNaNCheck, optInfCheck} * p.options != {}:
  1623. const opr: array[mAddF64..mDivF64, string] = ["+", "-", "*", "/"]
  1624. var a, b: TLoc
  1625. assert(e.sons[1].typ != nil)
  1626. assert(e.sons[2].typ != nil)
  1627. initLocExpr(p, e.sons[1], a)
  1628. initLocExpr(p, e.sons[2], b)
  1629. putIntoDest(p, d, e, rfmt(nil, "(($4)($2) $1 ($4)($3))",
  1630. rope(opr[m]), rdLoc(a), rdLoc(b),
  1631. getSimpleTypeDesc(p.module, e[1].typ)))
  1632. if optNaNCheck in p.options:
  1633. linefmt(p, cpsStmts, "#nanCheck($1);$n", rdLoc(d))
  1634. if optInfCheck in p.options:
  1635. linefmt(p, cpsStmts, "#infCheck($1);$n", rdLoc(d))
  1636. else:
  1637. binaryArith(p, e, d, m)
  1638. proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1639. case op
  1640. of mOr, mAnd: genAndOr(p, e, d, op)
  1641. of mNot..mToBiggestInt: unaryArith(p, e, d, op)
  1642. of mUnaryMinusI..mAbsI: unaryArithOverflow(p, e, d, op)
  1643. of mAddF64..mDivF64: binaryFloatArith(p, e, d, op)
  1644. of mShrI..mXor: binaryArith(p, e, d, op)
  1645. of mEqProc: genEqProc(p, e, d)
  1646. of mAddI..mPred: binaryArithOverflow(p, e, d, op)
  1647. of mRepr: genRepr(p, e, d)
  1648. of mGetTypeInfo: genGetTypeInfo(p, e, d)
  1649. of mSwap: genSwap(p, e, d)
  1650. of mUnaryLt:
  1651. if optOverflowCheck notin p.options: unaryExpr(p, e, d, "($1 - 1)")
  1652. else: unaryExpr(p, e, d, "#subInt($1, 1)")
  1653. of mInc, mDec:
  1654. const opr: array[mInc..mDec, string] = ["$1 += $2;$n", "$1 -= $2;$n"]
  1655. const fun64: array[mInc..mDec, string] = ["$# = #addInt64($#, $#);$n",
  1656. "$# = #subInt64($#, $#);$n"]
  1657. const fun: array[mInc..mDec, string] = ["$# = #addInt($#, $#);$n",
  1658. "$# = #subInt($#, $#);$n"]
  1659. let underlying = skipTypes(e.sons[1].typ, {tyGenericInst, tyAlias, tyVar, tyRange})
  1660. if optOverflowCheck notin p.options or underlying.kind in {tyUInt..tyUInt64}:
  1661. binaryStmt(p, e, d, opr[op])
  1662. else:
  1663. var a, b: TLoc
  1664. assert(e.sons[1].typ != nil)
  1665. assert(e.sons[2].typ != nil)
  1666. initLocExpr(p, e.sons[1], a)
  1667. initLocExpr(p, e.sons[2], b)
  1668. let ranged = skipTypes(e.sons[1].typ, {tyGenericInst, tyAlias, tyVar})
  1669. let res = binaryArithOverflowRaw(p, ranged, a, b,
  1670. if underlying.kind == tyInt64: fun64[op] else: fun[op])
  1671. putIntoDest(p, a, e.sons[1], "($#)($#)" % [
  1672. getTypeDesc(p.module, ranged), res])
  1673. of mConStrStr: genStrConcat(p, e, d)
  1674. of mAppendStrCh: binaryStmt(p, e, d, "$1 = #addChar($1, $2);$n")
  1675. of mAppendStrStr: genStrAppend(p, e, d)
  1676. of mAppendSeqElem: genSeqElemAppend(p, e, d)
  1677. of mEqStr: genStrEquals(p, e, d)
  1678. of mLeStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) <= 0)")
  1679. of mLtStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) < 0)")
  1680. of mIsNil: genIsNil(p, e, d)
  1681. of mIntToStr: genDollar(p, e, d, "#nimIntToStr($1)")
  1682. of mInt64ToStr: genDollar(p, e, d, "#nimInt64ToStr($1)")
  1683. of mBoolToStr: genDollar(p, e, d, "#nimBoolToStr($1)")
  1684. of mCharToStr: genDollar(p, e, d, "#nimCharToStr($1)")
  1685. of mFloatToStr: genDollar(p, e, d, "#nimFloatToStr($1)")
  1686. of mCStrToStr: genDollar(p, e, d, "#cstrToNimstr($1)")
  1687. of mStrToStr: expr(p, e.sons[1], d)
  1688. of mEnumToStr: genRepr(p, e, d)
  1689. of mOf: genOf(p, e, d)
  1690. of mNew: genNew(p, e)
  1691. of mNewFinalize: genNewFinalize(p, e)
  1692. of mNewSeq: genNewSeq(p, e)
  1693. of mNewSeqOfCap: genNewSeqOfCap(p, e, d)
  1694. of mSizeOf:
  1695. let t = e.sons[1].typ.skipTypes({tyTypeDesc})
  1696. putIntoDest(p, d, e, "((NI)sizeof($1))" % [getTypeDesc(p.module, t)])
  1697. of mChr: genSomeCast(p, e, d)
  1698. of mOrd: genOrd(p, e, d)
  1699. of mLengthArray, mHigh, mLengthStr, mLengthSeq, mLengthOpenArray:
  1700. genArrayLen(p, e, d, op)
  1701. of mXLenStr:
  1702. if not p.module.compileToCpp:
  1703. unaryExpr(p, e, d, "($1->Sup.len)")
  1704. else:
  1705. unaryExpr(p, e, d, "$1->len")
  1706. of mXLenSeq:
  1707. # see 'taddhigh.nim' for why we need to use a temporary here:
  1708. var a, tmp: TLoc
  1709. initLocExpr(p, e[1], a)
  1710. getIntTemp(p, tmp)
  1711. var frmt: FormatStr
  1712. if not p.module.compileToCpp:
  1713. frmt = "$1 = $2->Sup.len;$n"
  1714. else:
  1715. frmt = "$1 = $2->len;$n"
  1716. lineCg(p, cpsStmts, frmt, tmp.r, rdLoc(a))
  1717. putIntoDest(p, d, e, tmp.r)
  1718. of mGCref: unaryStmt(p, e, d, "#nimGCref($1);$n")
  1719. of mGCunref: unaryStmt(p, e, d, "#nimGCunref($1);$n")
  1720. of mSetLengthStr: genSetLengthStr(p, e, d)
  1721. of mSetLengthSeq: genSetLengthSeq(p, e, d)
  1722. of mIncl, mExcl, mCard, mLtSet, mLeSet, mEqSet, mMulSet, mPlusSet, mMinusSet,
  1723. mInSet:
  1724. genSetOp(p, e, d, op)
  1725. of mNewString, mNewStringOfCap, mCopyStr, mCopyStrLast, mExit,
  1726. mParseBiggestFloat:
  1727. var opr = e.sons[0].sym
  1728. if lfNoDecl notin opr.loc.flags:
  1729. discard cgsym(p.module, $opr.loc.r)
  1730. genCall(p, e, d)
  1731. of mReset: genReset(p, e)
  1732. of mEcho: genEcho(p, e[1].skipConv)
  1733. of mArrToSeq: genArrToSeq(p, e, d)
  1734. of mNLen..mNError, mSlurp..mQuoteAst:
  1735. localError(e.info, errXMustBeCompileTime, e.sons[0].sym.name.s)
  1736. of mSpawn:
  1737. let n = lowerings.wrapProcForSpawn(p.module.module, e, e.typ, nil, nil)
  1738. expr(p, n, d)
  1739. of mParallel:
  1740. let n = semparallel.liftParallel(p.module.module, e)
  1741. expr(p, n, d)
  1742. of mDeepCopy:
  1743. var a, b: TLoc
  1744. let x = if e[1].kind in {nkAddr, nkHiddenAddr}: e[1][0] else: e[1]
  1745. initLocExpr(p, x, a)
  1746. initLocExpr(p, e.sons[2], b)
  1747. genDeepCopy(p, a, b)
  1748. of mDotDot, mEqCString: genCall(p, e, d)
  1749. else: internalError(e.info, "genMagicExpr: " & $op)
  1750. proc genSetConstr(p: BProc, e: PNode, d: var TLoc) =
  1751. # example: { a..b, c, d, e, f..g }
  1752. # we have to emit an expression of the form:
  1753. # memset(tmp, 0, sizeof(tmp)); inclRange(tmp, a, b); incl(tmp, c);
  1754. # incl(tmp, d); incl(tmp, e); inclRange(tmp, f, g);
  1755. var
  1756. a, b, idx: TLoc
  1757. if nfAllConst in e.flags:
  1758. putIntoDest(p, d, e, genSetNode(p, e))
  1759. else:
  1760. if d.k == locNone: getTemp(p, e.typ, d)
  1761. if getSize(e.typ) > 8:
  1762. # big set:
  1763. useStringh(p.module)
  1764. lineF(p, cpsStmts, "memset($1, 0, sizeof($1));$n", [rdLoc(d)])
  1765. for i in countup(0, sonsLen(e) - 1):
  1766. if e.sons[i].kind == nkRange:
  1767. getTemp(p, getSysType(tyInt), idx) # our counter
  1768. initLocExpr(p, e.sons[i].sons[0], a)
  1769. initLocExpr(p, e.sons[i].sons[1], b)
  1770. lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
  1771. "$2[(NU)($1)>>3] |=(1U<<((NU)($1)&7U));$n", [rdLoc(idx), rdLoc(d),
  1772. rdSetElemLoc(a, e.typ), rdSetElemLoc(b, e.typ)])
  1773. else:
  1774. initLocExpr(p, e.sons[i], a)
  1775. lineF(p, cpsStmts, "$1[(NU)($2)>>3] |=(1U<<((NU)($2)&7U));$n",
  1776. [rdLoc(d), rdSetElemLoc(a, e.typ)])
  1777. else:
  1778. # small set
  1779. var ts = "NU" & $(getSize(e.typ) * 8)
  1780. lineF(p, cpsStmts, "$1 = 0;$n", [rdLoc(d)])
  1781. for i in countup(0, sonsLen(e) - 1):
  1782. if e.sons[i].kind == nkRange:
  1783. getTemp(p, getSysType(tyInt), idx) # our counter
  1784. initLocExpr(p, e.sons[i].sons[0], a)
  1785. initLocExpr(p, e.sons[i].sons[1], b)
  1786. lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
  1787. "$2 |=((" & ts & ")(1)<<(($1)%(sizeof(" & ts & ")*8)));$n", [
  1788. rdLoc(idx), rdLoc(d), rdSetElemLoc(a, e.typ),
  1789. rdSetElemLoc(b, e.typ)])
  1790. else:
  1791. initLocExpr(p, e.sons[i], a)
  1792. lineF(p, cpsStmts,
  1793. "$1 |=((" & ts & ")(1)<<(($2)%(sizeof(" & ts & ")*8)));$n",
  1794. [rdLoc(d), rdSetElemLoc(a, e.typ)])
  1795. proc genTupleConstr(p: BProc, n: PNode, d: var TLoc) =
  1796. var rec: TLoc
  1797. if not handleConstExpr(p, n, d):
  1798. let t = n.typ
  1799. discard getTypeDesc(p.module, t) # so that any fields are initialized
  1800. if d.k == locNone: getTemp(p, t, d)
  1801. for i in countup(0, sonsLen(n) - 1):
  1802. var it = n.sons[i]
  1803. if it.kind == nkExprColonExpr: it = it.sons[1]
  1804. initLoc(rec, locExpr, it, d.storage)
  1805. rec.r = "$1.Field$2" % [rdLoc(d), rope(i)]
  1806. expr(p, it, rec)
  1807. proc isConstClosure(n: PNode): bool {.inline.} =
  1808. result = n.sons[0].kind == nkSym and isRoutine(n.sons[0].sym) and
  1809. n.sons[1].kind == nkNilLit
  1810. proc genClosure(p: BProc, n: PNode, d: var TLoc) =
  1811. assert n.kind == nkClosure
  1812. if isConstClosure(n):
  1813. inc(p.module.labels)
  1814. var tmp = "CNSTCLOSURE" & rope(p.module.labels)
  1815. addf(p.module.s[cfsData], "static NIM_CONST $1 $2 = $3;$n",
  1816. [getTypeDesc(p.module, n.typ), tmp, genConstExpr(p, n)])
  1817. putIntoDest(p, d, n, tmp, OnStatic)
  1818. else:
  1819. var tmp, a, b: TLoc
  1820. initLocExpr(p, n.sons[0], a)
  1821. initLocExpr(p, n.sons[1], b)
  1822. if n.sons[0].skipConv.kind == nkClosure:
  1823. internalError(n.info, "closure to closure created")
  1824. # tasyncawait.nim breaks with this optimization:
  1825. when false:
  1826. if d.k != locNone:
  1827. linefmt(p, cpsStmts, "$1.ClP_0 = $2; $1.ClE_0 = $3;$n",
  1828. d.rdLoc, a.rdLoc, b.rdLoc)
  1829. else:
  1830. getTemp(p, n.typ, tmp)
  1831. linefmt(p, cpsStmts, "$1.ClP_0 = $2; $1.ClE_0 = $3;$n",
  1832. tmp.rdLoc, a.rdLoc, b.rdLoc)
  1833. putLocIntoDest(p, d, tmp)
  1834. proc genArrayConstr(p: BProc, n: PNode, d: var TLoc) =
  1835. var arr: TLoc
  1836. if not handleConstExpr(p, n, d):
  1837. if d.k == locNone: getTemp(p, n.typ, d)
  1838. for i in countup(0, sonsLen(n) - 1):
  1839. initLoc(arr, locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), d.storage)
  1840. arr.r = "$1[$2]" % [rdLoc(d), intLiteral(i)]
  1841. expr(p, n.sons[i], arr)
  1842. proc genComplexConst(p: BProc, sym: PSym, d: var TLoc) =
  1843. requestConstImpl(p, sym)
  1844. assert((sym.loc.r != nil) and (sym.loc.t != nil))
  1845. putLocIntoDest(p, d, sym.loc)
  1846. proc genStmtListExpr(p: BProc, n: PNode, d: var TLoc) =
  1847. var length = sonsLen(n)
  1848. for i in countup(0, length - 2): genStmts(p, n.sons[i])
  1849. if length > 0: expr(p, n.sons[length - 1], d)
  1850. proc upConv(p: BProc, n: PNode, d: var TLoc) =
  1851. var a: TLoc
  1852. initLocExpr(p, n.sons[0], a)
  1853. let dest = skipTypes(n.typ, abstractPtrs)
  1854. if optObjCheck in p.options and not isObjLackingTypeField(dest):
  1855. var r = rdLoc(a)
  1856. var nilCheck: Rope = nil
  1857. var t = skipTypes(a.t, abstractInst)
  1858. while t.kind in {tyVar, tyPtr, tyRef}:
  1859. if t.kind != tyVar: nilCheck = r
  1860. if t.kind != tyVar or not p.module.compileToCpp:
  1861. r = "(*$1)" % [r]
  1862. t = skipTypes(t.lastSon, abstractInst)
  1863. if not p.module.compileToCpp:
  1864. while t.kind == tyObject and t.sons[0] != nil:
  1865. add(r, ".Sup")
  1866. t = skipTypes(t.sons[0], skipPtrs)
  1867. if nilCheck != nil:
  1868. linefmt(p, cpsStmts, "if ($1) #chckObj($2.m_type, $3);$n",
  1869. nilCheck, r, genTypeInfo(p.module, dest))
  1870. else:
  1871. linefmt(p, cpsStmts, "#chckObj($1.m_type, $2);$n",
  1872. r, genTypeInfo(p.module, dest))
  1873. if n.sons[0].typ.kind != tyObject:
  1874. putIntoDest(p, d, n,
  1875. "(($1) ($2))" % [getTypeDesc(p.module, n.typ), rdLoc(a)], a.storage)
  1876. else:
  1877. putIntoDest(p, d, n, "(*($1*) ($2))" %
  1878. [getTypeDesc(p.module, dest), addrLoc(a)], a.storage)
  1879. proc downConv(p: BProc, n: PNode, d: var TLoc) =
  1880. if p.module.compileToCpp:
  1881. expr(p, n.sons[0], d) # downcast does C++ for us
  1882. else:
  1883. var dest = skipTypes(n.typ, abstractPtrs)
  1884. var arg = n.sons[0]
  1885. while arg.kind == nkObjDownConv: arg = arg.sons[0]
  1886. var src = skipTypes(arg.typ, abstractPtrs)
  1887. var a: TLoc
  1888. initLocExpr(p, arg, a)
  1889. var r = rdLoc(a)
  1890. let isRef = skipTypes(arg.typ, abstractInst).kind in {tyRef, tyPtr, tyVar}
  1891. if isRef:
  1892. add(r, "->Sup")
  1893. else:
  1894. add(r, ".Sup")
  1895. for i in countup(2, abs(inheritanceDiff(dest, src))): add(r, ".Sup")
  1896. if isRef:
  1897. # it can happen that we end up generating '&&x->Sup' here, so we pack
  1898. # the '&x->Sup' into a temporary and then those address is taken
  1899. # (see bug #837). However sometimes using a temporary is not correct:
  1900. # init(TFigure(my)) # where it is passed to a 'var TFigure'. We test
  1901. # this by ensuring the destination is also a pointer:
  1902. if d.k == locNone and skipTypes(n.typ, abstractInst).kind in {tyRef, tyPtr, tyVar}:
  1903. getTemp(p, n.typ, d)
  1904. linefmt(p, cpsStmts, "$1 = &$2;$n", rdLoc(d), r)
  1905. else:
  1906. r = "&" & r
  1907. putIntoDest(p, d, n, r, a.storage)
  1908. else:
  1909. putIntoDest(p, d, n, r, a.storage)
  1910. proc exprComplexConst(p: BProc, n: PNode, d: var TLoc) =
  1911. let t = n.typ
  1912. discard getTypeDesc(p.module, t) # so that any fields are initialized
  1913. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  1914. let tmp = p.module.tmpBase & rope(id)
  1915. if id == p.module.labels:
  1916. # expression not found in the cache:
  1917. inc(p.module.labels)
  1918. addf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
  1919. [getTypeDesc(p.module, t), tmp, genConstExpr(p, n)])
  1920. if d.k == locNone:
  1921. fillLoc(d, locData, n, tmp, OnStatic)
  1922. else:
  1923. putDataIntoDest(p, d, n, tmp)
  1924. # This fixes bug #4551, but we really need better dataflow
  1925. # analysis to make this 100% safe.
  1926. if t.kind notin {tySequence, tyString}:
  1927. d.storage = OnStatic
  1928. proc expr(p: BProc, n: PNode, d: var TLoc) =
  1929. p.currLineInfo = n.info
  1930. case n.kind
  1931. of nkSym:
  1932. var sym = n.sym
  1933. case sym.kind
  1934. of skMethod:
  1935. if {sfDispatcher, sfForward} * sym.flags != {}:
  1936. # we cannot produce code for the dispatcher yet:
  1937. fillProcLoc(p.module, n)
  1938. genProcPrototype(p.module, sym)
  1939. else:
  1940. genProc(p.module, sym)
  1941. putLocIntoDest(p, d, sym.loc)
  1942. of skProc, skConverter, skIterator, skFunc:
  1943. #if sym.kind == skIterator:
  1944. # echo renderTree(sym.getBody, {renderIds})
  1945. if sfCompileTime in sym.flags:
  1946. localError(n.info, "request to generate code for .compileTime proc: " &
  1947. sym.name.s)
  1948. genProc(p.module, sym)
  1949. if sym.loc.r == nil or sym.loc.lode == nil:
  1950. internalError(n.info, "expr: proc not init " & sym.name.s)
  1951. putLocIntoDest(p, d, sym.loc)
  1952. of skConst:
  1953. if isSimpleConst(sym.typ):
  1954. putIntoDest(p, d, n, genLiteral(p, sym.ast, sym.typ), OnStatic)
  1955. else:
  1956. genComplexConst(p, sym, d)
  1957. of skEnumField:
  1958. putIntoDest(p, d, n, rope(sym.position))
  1959. of skVar, skForVar, skResult, skLet:
  1960. if {sfGlobal, sfThread} * sym.flags != {}:
  1961. genVarPrototype(p.module, n)
  1962. if sym.loc.r == nil or sym.loc.t == nil:
  1963. #echo "FAILED FOR PRCO ", p.prc.name.s
  1964. #echo renderTree(p.prc.ast, {renderIds})
  1965. internalError n.info, "expr: var not init " & sym.name.s & "_" & $sym.id
  1966. if sfThread in sym.flags:
  1967. accessThreadLocalVar(p, sym)
  1968. if emulatedThreadVars():
  1969. putIntoDest(p, d, sym.loc.lode, "NimTV_->" & sym.loc.r)
  1970. else:
  1971. putLocIntoDest(p, d, sym.loc)
  1972. else:
  1973. putLocIntoDest(p, d, sym.loc)
  1974. of skTemp:
  1975. if sym.loc.r == nil or sym.loc.t == nil:
  1976. #echo "FAILED FOR PRCO ", p.prc.name.s
  1977. #echo renderTree(p.prc.ast, {renderIds})
  1978. internalError(n.info, "expr: temp not init " & sym.name.s & "_" & $sym.id)
  1979. putLocIntoDest(p, d, sym.loc)
  1980. of skParam:
  1981. if sym.loc.r == nil or sym.loc.t == nil:
  1982. # echo "FAILED FOR PRCO ", p.prc.name.s
  1983. # debug p.prc.typ.n
  1984. # echo renderTree(p.prc.ast, {renderIds})
  1985. internalError(n.info, "expr: param not init " & sym.name.s & "_" & $sym.id)
  1986. putLocIntoDest(p, d, sym.loc)
  1987. else: internalError(n.info, "expr(" & $sym.kind & "); unknown symbol")
  1988. of nkNilLit:
  1989. if not isEmptyType(n.typ):
  1990. putIntoDest(p, d, n, genLiteral(p, n))
  1991. of nkStrLit..nkTripleStrLit:
  1992. putDataIntoDest(p, d, n, genLiteral(p, n))
  1993. of nkIntLit..nkUInt64Lit,
  1994. nkFloatLit..nkFloat128Lit, nkCharLit:
  1995. putIntoDest(p, d, n, genLiteral(p, n))
  1996. of nkCall, nkHiddenCallConv, nkInfix, nkPrefix, nkPostfix, nkCommand,
  1997. nkCallStrLit:
  1998. genLineDir(p, n)
  1999. let op = n.sons[0]
  2000. if n.typ.isNil:
  2001. # discard the value:
  2002. var a: TLoc
  2003. if op.kind == nkSym and op.sym.magic != mNone:
  2004. genMagicExpr(p, n, a, op.sym.magic)
  2005. else:
  2006. genCall(p, n, a)
  2007. else:
  2008. # load it into 'd':
  2009. if op.kind == nkSym and op.sym.magic != mNone:
  2010. genMagicExpr(p, n, d, op.sym.magic)
  2011. else:
  2012. genCall(p, n, d)
  2013. of nkCurly:
  2014. if isDeepConstExpr(n) and n.len != 0:
  2015. putIntoDest(p, d, n, genSetNode(p, n))
  2016. else:
  2017. genSetConstr(p, n, d)
  2018. of nkBracket:
  2019. if isDeepConstExpr(n) and n.len != 0:
  2020. exprComplexConst(p, n, d)
  2021. elif skipTypes(n.typ, abstractVarRange).kind == tySequence:
  2022. genSeqConstr(p, n, d)
  2023. else:
  2024. genArrayConstr(p, n, d)
  2025. of nkPar:
  2026. if isDeepConstExpr(n) and n.len != 0:
  2027. exprComplexConst(p, n, d)
  2028. else:
  2029. genTupleConstr(p, n, d)
  2030. of nkObjConstr: genObjConstr(p, n, d)
  2031. of nkCast: genCast(p, n, d)
  2032. of nkHiddenStdConv, nkHiddenSubConv, nkConv: genConv(p, n, d)
  2033. of nkHiddenAddr, nkAddr: genAddr(p, n, d)
  2034. of nkBracketExpr: genBracketExpr(p, n, d)
  2035. of nkDerefExpr, nkHiddenDeref: genDeref(p, n, d)
  2036. of nkDotExpr: genRecordField(p, n, d)
  2037. of nkCheckedFieldExpr: genCheckedRecordField(p, n, d)
  2038. of nkBlockExpr, nkBlockStmt: genBlock(p, n, d)
  2039. of nkStmtListExpr: genStmtListExpr(p, n, d)
  2040. of nkStmtList:
  2041. for i in countup(0, sonsLen(n) - 1): genStmts(p, n.sons[i])
  2042. of nkIfExpr, nkIfStmt: genIf(p, n, d)
  2043. of nkWhen:
  2044. # This should be a "when nimvm" node.
  2045. expr(p, n.sons[1].sons[0], d)
  2046. of nkObjDownConv: downConv(p, n, d)
  2047. of nkObjUpConv: upConv(p, n, d)
  2048. of nkChckRangeF: genRangeChck(p, n, d, "chckRangeF")
  2049. of nkChckRange64: genRangeChck(p, n, d, "chckRange64")
  2050. of nkChckRange: genRangeChck(p, n, d, "chckRange")
  2051. of nkStringToCString: convStrToCStr(p, n, d)
  2052. of nkCStringToString: convCStrToStr(p, n, d)
  2053. of nkLambdaKinds:
  2054. var sym = n.sons[namePos].sym
  2055. genProc(p.module, sym)
  2056. if sym.loc.r == nil or sym.loc.lode == nil:
  2057. internalError(n.info, "expr: proc not init " & sym.name.s)
  2058. putLocIntoDest(p, d, sym.loc)
  2059. of nkClosure: genClosure(p, n, d)
  2060. of nkEmpty: discard
  2061. of nkWhileStmt: genWhileStmt(p, n)
  2062. of nkVarSection, nkLetSection: genVarStmt(p, n)
  2063. of nkConstSection: genConstStmt(p, n)
  2064. of nkForStmt: internalError(n.info, "for statement not eliminated")
  2065. of nkCaseStmt: genCase(p, n, d)
  2066. of nkReturnStmt: genReturnStmt(p, n)
  2067. of nkBreakStmt: genBreakStmt(p, n)
  2068. of nkAsgn:
  2069. if nfPreventCg notin n.flags:
  2070. genAsgn(p, n, fastAsgn=false)
  2071. of nkFastAsgn:
  2072. if nfPreventCg notin n.flags:
  2073. # transf is overly aggressive with 'nkFastAsgn', so we work around here.
  2074. # See tests/run/tcnstseq3 for an example that would fail otherwise.
  2075. genAsgn(p, n, fastAsgn=p.prc != nil)
  2076. of nkDiscardStmt:
  2077. let ex = n[0]
  2078. if ex.kind != nkEmpty:
  2079. genLineDir(p, n)
  2080. var a: TLoc
  2081. if ex.kind in nkCallKinds and (ex[0].kind != nkSym or
  2082. ex[0].sym.magic == mNone):
  2083. # bug #6037: do not assign to a temp in C++ mode:
  2084. incl a.flags, lfSingleUse
  2085. genCall(p, ex, a)
  2086. if lfSingleUse notin a.flags:
  2087. line(p, cpsStmts, a.r & ";" & tnl)
  2088. else:
  2089. initLocExpr(p, ex, a)
  2090. of nkAsmStmt: genAsmStmt(p, n)
  2091. of nkTryStmt:
  2092. if p.module.compileToCpp and optNoCppExceptions notin gGlobalOptions:
  2093. genTryCpp(p, n, d)
  2094. else:
  2095. genTry(p, n, d)
  2096. of nkRaiseStmt: genRaiseStmt(p, n)
  2097. of nkTypeSection:
  2098. # we have to emit the type information for object types here to support
  2099. # separate compilation:
  2100. genTypeSection(p.module, n)
  2101. of nkCommentStmt, nkIteratorDef, nkIncludeStmt,
  2102. nkImportStmt, nkImportExceptStmt, nkExportStmt, nkExportExceptStmt,
  2103. nkFromStmt, nkTemplateDef, nkMacroDef:
  2104. discard
  2105. of nkPragma: genPragma(p, n)
  2106. of nkPragmaBlock: expr(p, n.lastSon, d)
  2107. of nkProcDef, nkFuncDef, nkMethodDef, nkConverterDef:
  2108. if n.sons[genericParamsPos].kind == nkEmpty:
  2109. var prc = n.sons[namePos].sym
  2110. # due to a bug/limitation in the lambda lifting, unused inner procs
  2111. # are not transformed correctly. We work around this issue (#411) here
  2112. # by ensuring it's no inner proc (owner is a module):
  2113. if prc.skipGenericOwner.kind == skModule and sfCompileTime notin prc.flags:
  2114. if (not emitLazily(prc)) or
  2115. ({sfExportc, sfCompilerProc} * prc.flags == {sfExportc}) or
  2116. (sfExportc in prc.flags and lfExportLib in prc.loc.flags) or
  2117. (prc.kind == skMethod):
  2118. # we have not only the header:
  2119. if prc.getBody.kind != nkEmpty or lfDynamicLib in prc.loc.flags:
  2120. genProc(p.module, prc)
  2121. of nkParForStmt: genParForStmt(p, n)
  2122. of nkState: genState(p, n)
  2123. of nkGotoState: genGotoState(p, n)
  2124. of nkBreakState: genBreakState(p, n)
  2125. else: internalError(n.info, "expr(" & $n.kind & "); unknown node kind")
  2126. proc genNamedConstExpr(p: BProc, n: PNode): Rope =
  2127. if n.kind == nkExprColonExpr: result = genConstExpr(p, n.sons[1])
  2128. else: result = genConstExpr(p, n)
  2129. proc getDefaultValue(p: BProc; typ: PType; info: TLineInfo): Rope =
  2130. var t = skipTypes(typ, abstractRange-{tyTypeDesc})
  2131. case t.kind
  2132. of tyBool: result = rope"NIM_FALSE"
  2133. of tyEnum, tyChar, tyInt..tyInt64, tyUInt..tyUInt64: result = rope"0"
  2134. of tyFloat..tyFloat128: result = rope"0.0"
  2135. of tyCString, tyString, tyVar, tyPointer, tyPtr, tySequence, tyExpr,
  2136. tyStmt, tyTypeDesc, tyStatic, tyRef, tyNil:
  2137. result = rope"NIM_NIL"
  2138. of tyProc:
  2139. if t.callConv != ccClosure:
  2140. result = rope"NIM_NIL"
  2141. else:
  2142. result = rope"{NIM_NIL, NIM_NIL}"
  2143. of tyObject:
  2144. if not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2145. result = "{{$1}}" % [genTypeInfo(p.module, t)]
  2146. else:
  2147. result = rope"{}"
  2148. of tyArray, tyTuple: result = rope"{}"
  2149. of tySet:
  2150. if mapType(t) == ctArray: result = rope"{}"
  2151. else: result = rope"0"
  2152. else:
  2153. globalError(info, "cannot create null element for: " & $t.kind)
  2154. proc getNullValueAux(p: BProc; t: PType; obj, cons: PNode, result: var Rope; count: var int) =
  2155. case obj.kind
  2156. of nkRecList:
  2157. for i in countup(0, sonsLen(obj) - 1):
  2158. getNullValueAux(p, t, obj.sons[i], cons, result, count)
  2159. of nkRecCase:
  2160. getNullValueAux(p, t, obj.sons[0], cons, result, count)
  2161. for i in countup(1, sonsLen(obj) - 1):
  2162. getNullValueAux(p, t, lastSon(obj.sons[i]), cons, result, count)
  2163. of nkSym:
  2164. if count > 0: result.add ", "
  2165. inc count
  2166. let field = obj.sym
  2167. for i in 1..<cons.len:
  2168. if cons[i].kind == nkExprColonExpr:
  2169. if cons[i][0].sym.name.id == field.name.id:
  2170. result.add genConstExpr(p, cons[i][1])
  2171. return
  2172. elif i == field.position:
  2173. result.add genConstExpr(p, cons[i])
  2174. return
  2175. # not found, produce default value:
  2176. result.add getDefaultValue(p, field.typ, cons.info)
  2177. else:
  2178. localError(cons.info, "cannot create null element for: " & $obj)
  2179. proc getNullValueAuxT(p: BProc; orig, t: PType; obj, cons: PNode, result: var Rope; count: var int) =
  2180. var base = t.sons[0]
  2181. let oldRes = result
  2182. if not p.module.compileToCpp: result.add "{"
  2183. let oldcount = count
  2184. if base != nil:
  2185. base = skipTypes(base, skipPtrs)
  2186. getNullValueAuxT(p, orig, base, base.n, cons, result, count)
  2187. elif not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2188. addf(result, "$1", [genTypeInfo(p.module, orig)])
  2189. inc count
  2190. getNullValueAux(p, t, obj, cons, result, count)
  2191. # do not emit '{}' as that is not valid C:
  2192. if oldcount == count: result = oldres
  2193. elif not p.module.compileToCpp: result.add "}"
  2194. proc genConstObjConstr(p: BProc; n: PNode): Rope =
  2195. result = nil
  2196. let t = n.typ.skipTypes(abstractInst)
  2197. var count = 0
  2198. #if not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2199. # addf(result, "{$1}", [genTypeInfo(p.module, t)])
  2200. # inc count
  2201. getNullValueAuxT(p, t, t, t.n, n, result, count)
  2202. if p.module.compileToCpp:
  2203. result = "{$1}$n" % [result]
  2204. proc genConstSimpleList(p: BProc, n: PNode): Rope =
  2205. var length = sonsLen(n)
  2206. result = rope("{")
  2207. let t = n.typ.skipTypes(abstractInst)
  2208. for i in countup(0, length - 2):
  2209. addf(result, "$1,$n", [genNamedConstExpr(p, n.sons[i])])
  2210. if length > 0:
  2211. add(result, genNamedConstExpr(p, n.sons[length - 1]))
  2212. addf(result, "}$n", [])
  2213. proc genConstSeq(p: BProc, n: PNode, t: PType): Rope =
  2214. var data = "{{$1, $1}" % [n.len.rope]
  2215. if n.len > 0:
  2216. # array part needs extra curlies:
  2217. data.add(", {")
  2218. for i in countup(0, n.len - 1):
  2219. if i > 0: data.addf(",$n", [])
  2220. data.add genConstExpr(p, n.sons[i])
  2221. data.add("}")
  2222. data.add("}")
  2223. result = getTempName(p.module)
  2224. let base = t.skipTypes(abstractInst).sons[0]
  2225. appcg(p.module, cfsData,
  2226. "NIM_CONST struct {$n" &
  2227. " #TGenericSeq Sup;$n" &
  2228. " $1 data[$2];$n" &
  2229. "} $3 = $4;$n", [
  2230. getTypeDesc(p.module, base), n.len.rope, result, data])
  2231. result = "(($1)&$2)" % [getTypeDesc(p.module, t), result]
  2232. proc genConstExpr(p: BProc, n: PNode): Rope =
  2233. case n.kind
  2234. of nkHiddenStdConv, nkHiddenSubConv:
  2235. result = genConstExpr(p, n.sons[1])
  2236. of nkCurly:
  2237. var cs: TBitSet
  2238. toBitSet(n, cs)
  2239. result = genRawSetData(cs, int(getSize(n.typ)))
  2240. of nkBracket, nkPar, nkClosure:
  2241. var t = skipTypes(n.typ, abstractInst)
  2242. if t.kind == tySequence:
  2243. result = genConstSeq(p, n, n.typ)
  2244. elif t.kind == tyProc and t.callConv == ccClosure and not n.sons.isNil and
  2245. n.sons[0].kind == nkNilLit and n.sons[1].kind == nkNilLit:
  2246. # this hack fixes issue that nkNilLit is expanded to {NIM_NIL,NIM_NIL}
  2247. # this behaviour is needed since closure_var = nil must be
  2248. # expanded to {NIM_NIL,NIM_NIL}
  2249. # in VM closures are initialized with nkPar(nkNilLit, nkNilLit)
  2250. # leading to duplicate code like this:
  2251. # "{NIM_NIL,NIM_NIL}, {NIM_NIL,NIM_NIL}"
  2252. result = ~"{NIM_NIL,NIM_NIL}"
  2253. else:
  2254. result = genConstSimpleList(p, n)
  2255. of nkObjConstr:
  2256. result = genConstObjConstr(p, n)
  2257. else:
  2258. var d: TLoc
  2259. initLocExpr(p, n, d)
  2260. result = rdLoc(d)