ccgtypes.nim 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2017 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. # ------------------------- Name Mangling --------------------------------
  11. import sighashes, modulegraphs
  12. import std/md5
  13. proc isKeyword(w: PIdent): bool =
  14. # Nim and C++ share some keywords
  15. # it's more efficient to test the whole Nim keywords range
  16. case w.id
  17. of ccgKeywordsLow..ccgKeywordsHigh,
  18. nimKeywordsLow..nimKeywordsHigh,
  19. ord(wInline): return true
  20. else: return false
  21. proc mangleField(m: BModule; name: PIdent): string =
  22. result = mangle(name.s)
  23. # fields are tricky to get right and thanks to generic types producing
  24. # duplicates we can end up mangling the same field multiple times. However
  25. # if we do so, the 'cppDefines' table might be modified in the meantime
  26. # meaning we produce inconsistent field names (see bug #5404).
  27. # Hence we do not check for ``m.g.config.cppDefines.contains(result)`` here
  28. # anymore:
  29. if isKeyword(name):
  30. result.add "_0"
  31. proc fillBackendName(m: BModule; s: PSym) =
  32. if s.loc.r == "":
  33. var result = s.name.s.mangle.rope
  34. result.add "__"
  35. result.add m.g.graph.ifaces[s.itemId.module].uniqueName
  36. result.add "_"
  37. result.add rope s.itemId.item
  38. if m.hcrOn:
  39. result.add "_"
  40. result.add(idOrSig(s, m.module.name.s.mangle, m.sigConflicts))
  41. s.loc.r = result
  42. writeMangledName(m.ndi, s, m.config)
  43. proc fillParamName(m: BModule; s: PSym) =
  44. ## we cannot use 'sigConflicts' here since we have a BModule, not a BProc.
  45. ## Fortunately C's scoping rules are sane enough so that that doesn't
  46. ## cause any trouble.
  47. if s.loc.r == "":
  48. var res = s.name.s.mangle
  49. # Take into account if HCR is on because of the following scenario:
  50. # if a module gets imported and it has some more importc symbols in it,
  51. # some param names might receive the "_0" suffix to distinguish from what
  52. # is newly available. That might lead to changes in the C code in nimcache
  53. # that contain only a parameter name change, but that is enough to mandate
  54. # recompilation of that source file and thus a new shared object will be
  55. # relinked. That may lead to a module getting reloaded which wasn't intended
  56. # and that may be fatal when parts of the current active callstack when
  57. # performCodeReload() was called are from the module being reloaded
  58. # unintentionally - example (3 modules which import one another):
  59. # main => proxy => reloadable
  60. # we call performCodeReload() in proxy to reload only changes in reloadable
  61. # but there is a new import which introduces an importc symbol `socket`
  62. # and a function called in main or proxy uses `socket` as a parameter name.
  63. # That would lead to either needing to reload `proxy` or to overwrite the
  64. # executable file for the main module, which is running (or both!) -> error.
  65. if m.hcrOn or isKeyword(s.name) or m.g.config.cppDefines.contains(res):
  66. res.add "_0"
  67. s.loc.r = res.rope
  68. writeMangledName(m.ndi, s, m.config)
  69. proc fillLocalName(p: BProc; s: PSym) =
  70. assert s.kind in skLocalVars+{skTemp}
  71. #assert sfGlobal notin s.flags
  72. if s.loc.r == "":
  73. var key = s.name.s.mangle
  74. let counter = p.sigConflicts.getOrDefault(key)
  75. var result = key.rope
  76. if s.kind == skTemp:
  77. # speed up conflict search for temps (these are quite common):
  78. if counter != 0: result.add "_" & rope(counter+1)
  79. elif counter != 0 or isKeyword(s.name) or p.module.g.config.cppDefines.contains(key):
  80. result.add "_" & rope(counter+1)
  81. p.sigConflicts.inc(key)
  82. s.loc.r = result
  83. if s.kind != skTemp: writeMangledName(p.module.ndi, s, p.config)
  84. proc scopeMangledParam(p: BProc; param: PSym) =
  85. ## parameter generation only takes BModule, not a BProc, so we have to
  86. ## remember these parameter names are already in scope to be able to
  87. ## generate unique identifiers reliably (consider that ``var a = a`` is
  88. ## even an idiom in Nim).
  89. var key = param.name.s.mangle
  90. p.sigConflicts.inc(key)
  91. const
  92. irrelevantForBackend = {tyGenericBody, tyGenericInst, tyGenericInvocation,
  93. tyDistinct, tyRange, tyStatic, tyAlias, tySink,
  94. tyInferred, tyOwned}
  95. proc typeName(typ: PType; result: var Rope) =
  96. let typ = typ.skipTypes(irrelevantForBackend)
  97. result.add $typ.kind
  98. if typ.sym != nil and typ.kind in {tyObject, tyEnum}:
  99. result.add "_"
  100. result.add typ.sym.name.s.mangle
  101. proc getTypeName(m: BModule; typ: PType; sig: SigHash): Rope =
  102. var t = typ
  103. while true:
  104. if t.sym != nil and {sfImportc, sfExportc} * t.sym.flags != {}:
  105. return t.sym.loc.r
  106. if t.kind in irrelevantForBackend:
  107. t = t.lastSon
  108. else:
  109. break
  110. let typ = if typ.kind in {tyAlias, tySink, tyOwned}: typ.lastSon else: typ
  111. if typ.loc.r == "":
  112. typ.typeName(typ.loc.r)
  113. typ.loc.r.add $sig
  114. else:
  115. when defined(debugSigHashes):
  116. # check consistency:
  117. var tn = newRopeAppender()
  118. typ.typeName(tn)
  119. assert($typ.loc.r == $(tn & $sig))
  120. result = typ.loc.r
  121. if result == "": internalError(m.config, "getTypeName: " & $typ.kind)
  122. proc mapSetType(conf: ConfigRef; typ: PType): TCTypeKind =
  123. case int(getSize(conf, typ))
  124. of 1: result = ctInt8
  125. of 2: result = ctInt16
  126. of 4: result = ctInt32
  127. of 8: result = ctInt64
  128. else: result = ctArray
  129. proc mapType(conf: ConfigRef; typ: PType; kind: TSymKind): TCTypeKind =
  130. ## Maps a Nim type to a C type
  131. case typ.kind
  132. of tyNone, tyTyped: result = ctVoid
  133. of tyBool: result = ctBool
  134. of tyChar: result = ctChar
  135. of tyNil: result = ctPtr
  136. of tySet: result = mapSetType(conf, typ)
  137. of tyOpenArray, tyVarargs:
  138. if kind == skParam: result = ctArray
  139. else: result = ctStruct
  140. of tyArray, tyUncheckedArray: result = ctArray
  141. of tyObject, tyTuple: result = ctStruct
  142. of tyUserTypeClasses:
  143. doAssert typ.isResolvedUserTypeClass
  144. return mapType(conf, typ.lastSon, kind)
  145. of tyGenericBody, tyGenericInst, tyGenericParam, tyDistinct, tyOrdinal,
  146. tyTypeDesc, tyAlias, tySink, tyInferred, tyOwned:
  147. result = mapType(conf, lastSon(typ), kind)
  148. of tyEnum:
  149. if firstOrd(conf, typ) < 0:
  150. result = ctInt32
  151. else:
  152. case int(getSize(conf, typ))
  153. of 1: result = ctUInt8
  154. of 2: result = ctUInt16
  155. of 4: result = ctInt32
  156. of 8: result = ctInt64
  157. else: result = ctInt32
  158. of tyRange: result = mapType(conf, typ[0], kind)
  159. of tyPtr, tyVar, tyLent, tyRef:
  160. var base = skipTypes(typ.lastSon, typedescInst)
  161. case base.kind
  162. of tyOpenArray, tyArray, tyVarargs, tyUncheckedArray: result = ctPtrToArray
  163. of tySet:
  164. if mapSetType(conf, base) == ctArray: result = ctPtrToArray
  165. else: result = ctPtr
  166. else: result = ctPtr
  167. of tyPointer: result = ctPtr
  168. of tySequence: result = ctNimSeq
  169. of tyProc: result = if typ.callConv != ccClosure: ctProc else: ctStruct
  170. of tyString: result = ctNimStr
  171. of tyCstring: result = ctCString
  172. of tyInt..tyUInt64:
  173. result = TCTypeKind(ord(typ.kind) - ord(tyInt) + ord(ctInt))
  174. of tyStatic:
  175. if typ.n != nil: result = mapType(conf, lastSon typ, kind)
  176. else: doAssert(false, "mapType: " & $typ.kind)
  177. else: doAssert(false, "mapType: " & $typ.kind)
  178. proc mapReturnType(conf: ConfigRef; typ: PType): TCTypeKind =
  179. #if skipTypes(typ, typedescInst).kind == tyArray: result = ctPtr
  180. #else:
  181. result = mapType(conf, typ, skResult)
  182. proc isImportedType(t: PType): bool =
  183. result = t.sym != nil and sfImportc in t.sym.flags
  184. proc isImportedCppType(t: PType): bool =
  185. let x = t.skipTypes(irrelevantForBackend)
  186. result = (t.sym != nil and sfInfixCall in t.sym.flags) or
  187. (x.sym != nil and sfInfixCall in x.sym.flags)
  188. proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKind): Rope
  189. proc isObjLackingTypeField(typ: PType): bool {.inline.} =
  190. result = (typ.kind == tyObject) and ((tfFinal in typ.flags) and
  191. (typ[0] == nil) or isPureObject(typ))
  192. proc isInvalidReturnType(conf: ConfigRef; typ: PType, isProc = true): bool =
  193. # Arrays and sets cannot be returned by a C procedure, because C is
  194. # such a poor programming language.
  195. # We exclude records with refs too. This enhances efficiency and
  196. # is necessary for proper code generation of assignments.
  197. var rettype = typ
  198. var isAllowedCall = true
  199. if isProc:
  200. rettype = rettype[0]
  201. isAllowedCall = typ.callConv in {ccClosure, ccInline, ccNimCall}
  202. if rettype == nil or (isAllowedCall and
  203. getSize(conf, rettype) > conf.target.floatSize*3):
  204. result = true
  205. else:
  206. case mapType(conf, rettype, skResult)
  207. of ctArray:
  208. result = not (skipTypes(rettype, typedescInst).kind in
  209. {tyVar, tyLent, tyRef, tyPtr})
  210. of ctStruct:
  211. let t = skipTypes(rettype, typedescInst)
  212. if rettype.isImportedCppType or t.isImportedCppType: return false
  213. result = containsGarbageCollectedRef(t) or
  214. (t.kind == tyObject and not isObjLackingTypeField(t))
  215. else: result = false
  216. const
  217. CallingConvToStr: array[TCallingConvention, string] = ["N_NIMCALL",
  218. "N_STDCALL", "N_CDECL", "N_SAFECALL",
  219. "N_SYSCALL", # this is probably not correct for all platforms,
  220. # but one can #define it to what one wants
  221. "N_INLINE", "N_NOINLINE", "N_FASTCALL", "N_THISCALL", "N_CLOSURE", "N_NOCONV"]
  222. proc cacheGetType(tab: TypeCache; sig: SigHash): Rope =
  223. # returns nil if we need to declare this type
  224. # since types are now unique via the ``getUniqueType`` mechanism, this slow
  225. # linear search is not necessary anymore:
  226. result = tab.getOrDefault(sig)
  227. proc addAbiCheck(m: BModule, t: PType, name: Rope) =
  228. if isDefined(m.config, "checkAbi") and (let size = getSize(m.config, t); size != szUnknownSize):
  229. var msg = "backend & Nim disagree on size for: "
  230. msg.addTypeHeader(m.config, t)
  231. var msg2 = ""
  232. msg2.addQuoted msg # not a hostspot so extra allocation doesn't matter
  233. m.s[cfsTypeInfo].addf("NIM_STATIC_ASSERT(sizeof($1) == $2, $3);$n", [name, rope(size), msg2.rope])
  234. # see `testCodegenABICheck` for example error message it generates
  235. proc fillResult(conf: ConfigRef; param: PNode, proctype: PType) =
  236. fillLoc(param.sym.loc, locParam, param, "Result",
  237. OnStack)
  238. let t = param.sym.typ
  239. if mapReturnType(conf, t) != ctArray and isInvalidReturnType(conf, proctype):
  240. incl(param.sym.loc.flags, lfIndirect)
  241. param.sym.loc.storage = OnUnknown
  242. proc typeNameOrLiteral(m: BModule; t: PType, literal: string): Rope =
  243. if t.sym != nil and sfImportc in t.sym.flags and t.sym.magic == mNone:
  244. useHeader(m, t.sym)
  245. result = t.sym.loc.r
  246. else:
  247. result = rope(literal)
  248. proc getSimpleTypeDesc(m: BModule, typ: PType): Rope =
  249. const
  250. NumericalTypeToStr: array[tyInt..tyUInt64, string] = [
  251. "NI", "NI8", "NI16", "NI32", "NI64",
  252. "NF", "NF32", "NF64", "NF128",
  253. "NU", "NU8", "NU16", "NU32", "NU64"]
  254. case typ.kind
  255. of tyPointer:
  256. result = typeNameOrLiteral(m, typ, "void*")
  257. of tyString:
  258. case detectStrVersion(m)
  259. of 2:
  260. cgsym(m, "NimStrPayload")
  261. cgsym(m, "NimStringV2")
  262. result = typeNameOrLiteral(m, typ, "NimStringV2")
  263. else:
  264. cgsym(m, "NimStringDesc")
  265. result = typeNameOrLiteral(m, typ, "NimStringDesc*")
  266. of tyCstring: result = typeNameOrLiteral(m, typ, "NCSTRING")
  267. of tyBool: result = typeNameOrLiteral(m, typ, "NIM_BOOL")
  268. of tyChar: result = typeNameOrLiteral(m, typ, "NIM_CHAR")
  269. of tyNil: result = typeNameOrLiteral(m, typ, "void*")
  270. of tyInt..tyUInt64:
  271. result = typeNameOrLiteral(m, typ, NumericalTypeToStr[typ.kind])
  272. of tyDistinct, tyRange, tyOrdinal: result = getSimpleTypeDesc(m, typ[0])
  273. of tyStatic:
  274. if typ.n != nil: result = getSimpleTypeDesc(m, lastSon typ)
  275. else: internalError(m.config, "tyStatic for getSimpleTypeDesc")
  276. of tyGenericInst, tyAlias, tySink, tyOwned:
  277. result = getSimpleTypeDesc(m, lastSon typ)
  278. else: result = ""
  279. if result != "" and typ.isImportedType():
  280. let sig = hashType typ
  281. if cacheGetType(m.typeCache, sig) == "":
  282. m.typeCache[sig] = result
  283. proc pushType(m: BModule, typ: PType) =
  284. for i in 0..high(m.typeStack):
  285. # pointer equality is good enough here:
  286. if m.typeStack[i] == typ: return
  287. m.typeStack.add(typ)
  288. proc getTypePre(m: BModule, typ: PType; sig: SigHash): Rope =
  289. if typ == nil: result = rope("void")
  290. else:
  291. result = getSimpleTypeDesc(m, typ)
  292. if result == "": result = cacheGetType(m.typeCache, sig)
  293. proc structOrUnion(t: PType): Rope =
  294. let cachedUnion = rope("union")
  295. let cachedStruct = rope("struct")
  296. let t = t.skipTypes({tyAlias, tySink})
  297. if tfUnion in t.flags: cachedUnion
  298. else: cachedStruct
  299. proc addForwardStructFormat(m: BModule, structOrUnion: Rope, typename: Rope) =
  300. if m.compileToCpp:
  301. m.s[cfsForwardTypes].addf "$1 $2;$n", [structOrUnion, typename]
  302. else:
  303. m.s[cfsForwardTypes].addf "typedef $1 $2 $2;$n", [structOrUnion, typename]
  304. proc seqStar(m: BModule): string =
  305. if optSeqDestructors in m.config.globalOptions: result = ""
  306. else: result = "*"
  307. proc getTypeForward(m: BModule, typ: PType; sig: SigHash): Rope =
  308. result = cacheGetType(m.forwTypeCache, sig)
  309. if result != "": return
  310. result = getTypePre(m, typ, sig)
  311. if result != "": return
  312. let concrete = typ.skipTypes(abstractInst)
  313. case concrete.kind
  314. of tySequence, tyTuple, tyObject:
  315. result = getTypeName(m, typ, sig)
  316. m.forwTypeCache[sig] = result
  317. if not isImportedType(concrete):
  318. addForwardStructFormat(m, structOrUnion(typ), result)
  319. else:
  320. pushType(m, concrete)
  321. doAssert m.forwTypeCache[sig] == result
  322. else: internalError(m.config, "getTypeForward(" & $typ.kind & ')')
  323. proc getTypeDescWeak(m: BModule; t: PType; check: var IntSet; kind: TSymKind): Rope =
  324. ## like getTypeDescAux but creates only a *weak* dependency. In other words
  325. ## we know we only need a pointer to it so we only generate a struct forward
  326. ## declaration:
  327. let etB = t.skipTypes(abstractInst)
  328. case etB.kind
  329. of tyObject, tyTuple:
  330. if isImportedCppType(etB) and t.kind == tyGenericInst:
  331. result = getTypeDescAux(m, t, check, kind)
  332. else:
  333. result = getTypeForward(m, t, hashType(t))
  334. pushType(m, t)
  335. of tySequence:
  336. let sig = hashType(t)
  337. if optSeqDestructors in m.config.globalOptions:
  338. if skipTypes(etB[0], typedescInst).kind == tyEmpty:
  339. internalError(m.config, "cannot map the empty seq type to a C type")
  340. result = cacheGetType(m.forwTypeCache, sig)
  341. if result == "":
  342. result = getTypeName(m, t, sig)
  343. if not isImportedType(t):
  344. m.forwTypeCache[sig] = result
  345. addForwardStructFormat(m, rope"struct", result)
  346. let payload = result & "_Content"
  347. addForwardStructFormat(m, rope"struct", payload)
  348. if cacheGetType(m.typeCache, sig) == "":
  349. m.typeCache[sig] = result
  350. #echo "adding ", sig, " ", typeToString(t), " ", m.module.name.s
  351. appcg(m, m.s[cfsTypes],
  352. "struct $1 {$N" &
  353. " NI len; $1_Content* p;$N" &
  354. "};$N", [result])
  355. else:
  356. result = getTypeForward(m, t, sig) & seqStar(m)
  357. pushType(m, t)
  358. else:
  359. result = getTypeDescAux(m, t, check, kind)
  360. proc getSeqPayloadType(m: BModule; t: PType): Rope =
  361. var check = initIntSet()
  362. result = getTypeDescWeak(m, t, check, skParam) & "_Content"
  363. #result = getTypeForward(m, t, hashType(t)) & "_Content"
  364. proc seqV2ContentType(m: BModule; t: PType; check: var IntSet) =
  365. let sig = hashType(t)
  366. let result = cacheGetType(m.typeCache, sig)
  367. if result == "":
  368. discard getTypeDescAux(m, t, check, skVar)
  369. else:
  370. # little hack for now to prevent multiple definitions of the same
  371. # Seq_Content:
  372. appcg(m, m.s[cfsTypes], """$N
  373. $3ifndef $2_Content_PP
  374. $3define $2_Content_PP
  375. struct $2_Content { NI cap; $1 data[SEQ_DECL_SIZE];};
  376. $3endif$N
  377. """, [getTypeDescAux(m, t.skipTypes(abstractInst)[0], check, skVar), result, rope"#"])
  378. proc paramStorageLoc(param: PSym): TStorageLoc =
  379. if param.typ.skipTypes({tyVar, tyLent, tyTypeDesc}).kind notin {
  380. tyArray, tyOpenArray, tyVarargs}:
  381. result = OnStack
  382. else:
  383. result = OnUnknown
  384. proc genProcParams(m: BModule, t: PType, rettype, params: var Rope,
  385. check: var IntSet, declareEnvironment=true;
  386. weakDep=false) =
  387. params = "("
  388. if t[0] == nil or isInvalidReturnType(m.config, t):
  389. rettype = "void"
  390. else:
  391. rettype = getTypeDescAux(m, t[0], check, skResult)
  392. for i in 1..<t.n.len:
  393. if t.n[i].kind != nkSym: internalError(m.config, t.n.info, "genProcParams")
  394. var param = t.n[i].sym
  395. if isCompileTimeOnly(param.typ): continue
  396. if params != "(": params.add(", ")
  397. fillParamName(m, param)
  398. fillLoc(param.loc, locParam, t.n[i],
  399. param.paramStorageLoc)
  400. if ccgIntroducedPtr(m.config, param, t[0]):
  401. params.add(getTypeDescWeak(m, param.typ, check, skParam))
  402. params.add("*")
  403. incl(param.loc.flags, lfIndirect)
  404. param.loc.storage = OnUnknown
  405. elif weakDep:
  406. params.add(getTypeDescWeak(m, param.typ, check, skParam))
  407. else:
  408. params.add(getTypeDescAux(m, param.typ, check, skParam))
  409. params.add(" ")
  410. if sfNoalias in param.flags:
  411. params.add("NIM_NOALIAS ")
  412. params.add(param.loc.r)
  413. # declare the len field for open arrays:
  414. var arr = param.typ.skipTypes({tyGenericInst})
  415. if arr.kind in {tyVar, tyLent, tySink}: arr = arr.lastSon
  416. var j = 0
  417. while arr.kind in {tyOpenArray, tyVarargs}:
  418. # this fixes the 'sort' bug:
  419. if param.typ.kind in {tyVar, tyLent}: param.loc.storage = OnUnknown
  420. # need to pass hidden parameter:
  421. params.addf(", NI $1Len_$2", [param.loc.r, j.rope])
  422. inc(j)
  423. arr = arr[0].skipTypes({tySink})
  424. if t[0] != nil and isInvalidReturnType(m.config, t):
  425. var arr = t[0]
  426. if params != "(": params.add(", ")
  427. if mapReturnType(m.config, t[0]) != ctArray:
  428. if isHeaderFile in m.flags:
  429. # still generates types for `--header`
  430. params.add(getTypeDescAux(m, arr, check, skResult))
  431. params.add("*")
  432. else:
  433. params.add(getTypeDescWeak(m, arr, check, skResult))
  434. params.add("*")
  435. else:
  436. params.add(getTypeDescAux(m, arr, check, skResult))
  437. params.addf(" Result", [])
  438. if t.callConv == ccClosure and declareEnvironment:
  439. if params != "(": params.add(", ")
  440. params.add("void* ClE_0")
  441. if tfVarargs in t.flags:
  442. if params != "(": params.add(", ")
  443. params.add("...")
  444. if params == "(": params.add("void)")
  445. else: params.add(")")
  446. proc mangleRecFieldName(m: BModule; field: PSym): Rope =
  447. if {sfImportc, sfExportc} * field.flags != {}:
  448. result = field.loc.r
  449. else:
  450. result = rope(mangleField(m, field.name))
  451. if result == "": internalError(m.config, field.info, "mangleRecFieldName")
  452. proc genRecordFieldsAux(m: BModule, n: PNode,
  453. rectype: PType,
  454. check: var IntSet; result: var Rope; unionPrefix = "") =
  455. case n.kind
  456. of nkRecList:
  457. for i in 0..<n.len:
  458. genRecordFieldsAux(m, n[i], rectype, check, result, unionPrefix)
  459. of nkRecCase:
  460. if n[0].kind != nkSym: internalError(m.config, n.info, "genRecordFieldsAux")
  461. genRecordFieldsAux(m, n[0], rectype, check, result, unionPrefix)
  462. # prefix mangled name with "_U" to avoid clashes with other field names,
  463. # since identifiers are not allowed to start with '_'
  464. var unionBody: Rope = ""
  465. for i in 1..<n.len:
  466. case n[i].kind
  467. of nkOfBranch, nkElse:
  468. let k = lastSon(n[i])
  469. if k.kind != nkSym:
  470. let structName = "_" & mangleRecFieldName(m, n[0].sym) & "_" & $i
  471. var a = newRopeAppender()
  472. genRecordFieldsAux(m, k, rectype, check, a, unionPrefix & $structName & ".")
  473. if a != "":
  474. if tfPacked notin rectype.flags:
  475. unionBody.add("struct {")
  476. else:
  477. if hasAttribute in CC[m.config.cCompiler].props:
  478. unionBody.add("struct __attribute__((__packed__)){")
  479. else:
  480. unionBody.addf("#pragma pack(push, 1)$nstruct{", [])
  481. unionBody.add(a)
  482. unionBody.addf("} $1;$n", [structName])
  483. if tfPacked in rectype.flags and hasAttribute notin CC[m.config.cCompiler].props:
  484. unionBody.addf("#pragma pack(pop)$n", [])
  485. else:
  486. genRecordFieldsAux(m, k, rectype, check, unionBody, unionPrefix)
  487. else: internalError(m.config, "genRecordFieldsAux(record case branch)")
  488. if unionBody != "":
  489. result.addf("union{$n$1};$n", [unionBody])
  490. of nkSym:
  491. let field = n.sym
  492. if field.typ.kind == tyVoid: return
  493. #assert(field.ast == nil)
  494. let sname = mangleRecFieldName(m, field)
  495. fillLoc(field.loc, locField, n, unionPrefix & sname, OnUnknown)
  496. if field.alignment > 0:
  497. result.addf "NIM_ALIGN($1) ", [rope(field.alignment)]
  498. # for importcpp'ed objects, we only need to set field.loc, but don't
  499. # have to recurse via 'getTypeDescAux'. And not doing so prevents problems
  500. # with heavily templatized C++ code:
  501. if not isImportedCppType(rectype):
  502. let noAlias = if sfNoalias in field.flags: " NIM_NOALIAS" else: ""
  503. let fieldType = field.loc.lode.typ.skipTypes(abstractInst)
  504. if fieldType.kind == tyUncheckedArray:
  505. result.addf("$1 $2[SEQ_DECL_SIZE];$n",
  506. [getTypeDescAux(m, fieldType.elemType, check, skField), sname])
  507. elif fieldType.kind == tySequence:
  508. # we need to use a weak dependency here for trecursive_table.
  509. result.addf("$1$3 $2;$n", [getTypeDescWeak(m, field.loc.t, check, skField), sname, noAlias])
  510. elif field.bitsize != 0:
  511. result.addf("$1$4 $2:$3;$n", [getTypeDescAux(m, field.loc.t, check, skField), sname, rope($field.bitsize), noAlias])
  512. else:
  513. # don't use fieldType here because we need the
  514. # tyGenericInst for C++ template support
  515. result.addf("$1$3 $2;$n", [getTypeDescAux(m, field.loc.t, check, skField), sname, noAlias])
  516. else: internalError(m.config, n.info, "genRecordFieldsAux()")
  517. proc getRecordFields(m: BModule, typ: PType, check: var IntSet): Rope =
  518. result = newRopeAppender()
  519. genRecordFieldsAux(m, typ.n, typ, check, result)
  520. proc fillObjectFields*(m: BModule; typ: PType) =
  521. # sometimes generic objects are not consistently merged. We patch over
  522. # this fact here.
  523. var check = initIntSet()
  524. discard getRecordFields(m, typ, check)
  525. proc mangleDynLibProc(sym: PSym): Rope
  526. proc getRecordDesc(m: BModule, typ: PType, name: Rope,
  527. check: var IntSet): Rope =
  528. # declare the record:
  529. var hasField = false
  530. if tfPacked in typ.flags:
  531. if hasAttribute in CC[m.config.cCompiler].props:
  532. result = structOrUnion(typ) & " __attribute__((__packed__))"
  533. else:
  534. result = "#pragma pack(push, 1)\L" & structOrUnion(typ)
  535. else:
  536. result = structOrUnion(typ)
  537. result.add " "
  538. result.add name
  539. if typ.kind == tyObject:
  540. if typ[0] == nil:
  541. if lacksMTypeField(typ):
  542. appcg(m, result, " {$n", [])
  543. else:
  544. if optTinyRtti in m.config.globalOptions:
  545. appcg(m, result, " {$n#TNimTypeV2* m_type;$n", [])
  546. else:
  547. appcg(m, result, " {$n#TNimType* m_type;$n", [])
  548. hasField = true
  549. elif m.compileToCpp:
  550. appcg(m, result, " : public $1 {$n",
  551. [getTypeDescAux(m, typ[0].skipTypes(skipPtrs), check, skField)])
  552. if typ.isException and m.config.exc == excCpp:
  553. when false:
  554. appcg(m, result, "virtual void raise() { throw *this; }$n", []) # required for polymorphic exceptions
  555. if typ.sym.magic == mException:
  556. # Add cleanup destructor to Exception base class
  557. appcg(m, result, "~$1();$n", [name])
  558. # define it out of the class body and into the procs section so we don't have to
  559. # artificially forward-declare popCurrentExceptionEx (very VERY troublesome for HCR)
  560. appcg(m, cfsProcs, "inline $1::~$1() {if(this->raiseId) #popCurrentExceptionEx(this->raiseId);}$n", [name])
  561. hasField = true
  562. else:
  563. appcg(m, result, " {$n $1 Sup;$n",
  564. [getTypeDescAux(m, typ[0].skipTypes(skipPtrs), check, skField)])
  565. hasField = true
  566. else:
  567. result.addf(" {$n", [name])
  568. let desc = getRecordFields(m, typ, check)
  569. if desc == "" and not hasField:
  570. result.addf("char dummy;$n", [])
  571. else:
  572. result.add(desc)
  573. result.add("};\L")
  574. if tfPacked in typ.flags and hasAttribute notin CC[m.config.cCompiler].props:
  575. result.add "#pragma pack(pop)\L"
  576. proc getTupleDesc(m: BModule, typ: PType, name: Rope,
  577. check: var IntSet): Rope =
  578. result = "$1 $2 {$n" % [structOrUnion(typ), name]
  579. var desc: Rope = ""
  580. for i in 0..<typ.len:
  581. desc.addf("$1 Field$2;$n",
  582. [getTypeDescAux(m, typ[i], check, skField), rope(i)])
  583. if desc == "": result.add("char dummy;\L")
  584. else: result.add(desc)
  585. result.add("};\L")
  586. proc scanCppGenericSlot(pat: string, cursor, outIdx, outStars: var int): bool =
  587. # A helper proc for handling cppimport patterns, involving numeric
  588. # placeholders for generic types (e.g. '0, '**2, etc).
  589. # pre: the cursor must be placed at the ' symbol
  590. # post: the cursor will be placed after the final digit
  591. # false will returned if the input is not recognized as a placeholder
  592. inc cursor
  593. let begin = cursor
  594. while pat[cursor] == '*': inc cursor
  595. if pat[cursor] in Digits:
  596. outIdx = pat[cursor].ord - '0'.ord
  597. outStars = cursor - begin
  598. inc cursor
  599. return true
  600. else:
  601. return false
  602. proc resolveStarsInCppType(typ: PType, idx, stars: int): PType =
  603. # Make sure the index refers to one of the generic params of the type.
  604. # XXX: we should catch this earlier and report it as a semantic error.
  605. if idx >= typ.len:
  606. doAssert false, "invalid apostrophe type parameter index"
  607. result = typ[idx]
  608. for i in 1..stars:
  609. if result != nil and result.len > 0:
  610. result = if result.kind == tyGenericInst: result[1]
  611. else: result.elemType
  612. proc getOpenArrayDesc(m: BModule, t: PType, check: var IntSet; kind: TSymKind): Rope =
  613. let sig = hashType(t)
  614. if kind == skParam:
  615. result = getTypeDescWeak(m, t[0], check, kind) & "*"
  616. else:
  617. result = cacheGetType(m.typeCache, sig)
  618. if result == "":
  619. result = getTypeName(m, t, sig)
  620. m.typeCache[sig] = result
  621. let elemType = getTypeDescWeak(m, t[0], check, kind)
  622. m.s[cfsTypes].addf("typedef struct {$n$2* Field0;$nNI Field1;$n} $1;$n",
  623. [result, elemType])
  624. proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKind): Rope =
  625. # returns only the type's name
  626. var t = origTyp.skipTypes(irrelevantForBackend-{tyOwned})
  627. if containsOrIncl(check, t.id):
  628. if not (isImportedCppType(origTyp) or isImportedCppType(t)):
  629. internalError(m.config, "cannot generate C type for: " & typeToString(origTyp))
  630. # XXX: this BUG is hard to fix -> we need to introduce helper structs,
  631. # but determining when this needs to be done is hard. We should split
  632. # C type generation into an analysis and a code generation phase somehow.
  633. if t.sym != nil: useHeader(m, t.sym)
  634. if t != origTyp and origTyp.sym != nil: useHeader(m, origTyp.sym)
  635. let sig = hashType(origTyp)
  636. defer: # defer is the simplest in this case
  637. if isImportedType(t) and not m.typeABICache.containsOrIncl(sig):
  638. addAbiCheck(m, t, result)
  639. result = getTypePre(m, t, sig)
  640. if result != "" and t.kind != tyOpenArray:
  641. excl(check, t.id)
  642. return
  643. case t.kind
  644. of tyRef, tyPtr, tyVar, tyLent:
  645. var star = if t.kind in {tyVar} and tfVarIsPtr notin origTyp.flags and
  646. compileToCpp(m): "&" else: "*"
  647. var et = origTyp.skipTypes(abstractInst).lastSon
  648. var etB = et.skipTypes(abstractInst)
  649. if mapType(m.config, t, kind) == ctPtrToArray and (etB.kind != tyOpenArray or kind == skParam):
  650. if etB.kind == tySet:
  651. et = getSysType(m.g.graph, unknownLineInfo, tyUInt8)
  652. else:
  653. et = elemType(etB)
  654. etB = et.skipTypes(abstractInst)
  655. star[0] = '*'
  656. case etB.kind
  657. of tyObject, tyTuple:
  658. if isImportedCppType(etB) and et.kind == tyGenericInst:
  659. result = getTypeDescAux(m, et, check, kind) & star
  660. else:
  661. # no restriction! We have a forward declaration for structs
  662. let name = getTypeForward(m, et, hashType et)
  663. result = name & star
  664. m.typeCache[sig] = result
  665. of tySequence:
  666. if optSeqDestructors in m.config.globalOptions:
  667. result = getTypeDescWeak(m, et, check, kind) & star
  668. m.typeCache[sig] = result
  669. else:
  670. # no restriction! We have a forward declaration for structs
  671. let name = getTypeForward(m, et, hashType et)
  672. result = name & seqStar(m) & star
  673. m.typeCache[sig] = result
  674. pushType(m, et)
  675. else:
  676. # else we have a strong dependency :-(
  677. result = getTypeDescAux(m, et, check, kind) & star
  678. m.typeCache[sig] = result
  679. of tyOpenArray, tyVarargs:
  680. result = getOpenArrayDesc(m, t, check, kind)
  681. of tyEnum:
  682. result = cacheGetType(m.typeCache, sig)
  683. if result == "":
  684. result = getTypeName(m, origTyp, sig)
  685. if not (isImportedCppType(t) or
  686. (sfImportc in t.sym.flags and t.sym.magic == mNone)):
  687. m.typeCache[sig] = result
  688. var size: int
  689. if firstOrd(m.config, t) < 0:
  690. m.s[cfsTypes].addf("typedef NI32 $1;$n", [result])
  691. size = 4
  692. else:
  693. size = int(getSize(m.config, t))
  694. case size
  695. of 1: m.s[cfsTypes].addf("typedef NU8 $1;$n", [result])
  696. of 2: m.s[cfsTypes].addf("typedef NU16 $1;$n", [result])
  697. of 4: m.s[cfsTypes].addf("typedef NI32 $1;$n", [result])
  698. of 8: m.s[cfsTypes].addf("typedef NI64 $1;$n", [result])
  699. else: internalError(m.config, t.sym.info, "getTypeDescAux: enum")
  700. when false:
  701. let owner = hashOwner(t.sym)
  702. if not gDebugInfo.hasEnum(t.sym.name.s, t.sym.info.line, owner):
  703. var vals: seq[(string, int)] = @[]
  704. for i in 0..<t.n.len:
  705. assert(t.n[i].kind == nkSym)
  706. let field = t.n[i].sym
  707. vals.add((field.name.s, field.position.int))
  708. gDebugInfo.registerEnum(EnumDesc(size: size, owner: owner, id: t.sym.id,
  709. name: t.sym.name.s, values: vals))
  710. of tyProc:
  711. result = getTypeName(m, origTyp, sig)
  712. m.typeCache[sig] = result
  713. var rettype, desc: Rope
  714. genProcParams(m, t, rettype, desc, check, true, true)
  715. if not isImportedType(t):
  716. if t.callConv != ccClosure: # procedure vars may need a closure!
  717. m.s[cfsTypes].addf("typedef $1_PTR($2, $3) $4;$n",
  718. [rope(CallingConvToStr[t.callConv]), rettype, result, desc])
  719. else:
  720. m.s[cfsTypes].addf("typedef struct {$n" &
  721. "N_NIMCALL_PTR($2, ClP_0) $3;$n" &
  722. "void* ClE_0;$n} $1;$n",
  723. [result, rettype, desc])
  724. of tySequence:
  725. if optSeqDestructors in m.config.globalOptions:
  726. result = getTypeDescWeak(m, t, check, kind)
  727. else:
  728. # we cannot use getTypeForward here because then t would be associated
  729. # with the name of the struct, not with the pointer to the struct:
  730. result = cacheGetType(m.forwTypeCache, sig)
  731. if result == "":
  732. result = getTypeName(m, origTyp, sig)
  733. if not isImportedType(t):
  734. addForwardStructFormat(m, structOrUnion(t), result)
  735. m.forwTypeCache[sig] = result
  736. assert(cacheGetType(m.typeCache, sig) == "")
  737. m.typeCache[sig] = result & seqStar(m)
  738. if not isImportedType(t):
  739. if skipTypes(t[0], typedescInst).kind != tyEmpty:
  740. const
  741. cppSeq = "struct $2 : #TGenericSeq {$n"
  742. cSeq = "struct $2 {$n" &
  743. " #TGenericSeq Sup;$n"
  744. if m.compileToCpp:
  745. appcg(m, m.s[cfsSeqTypes],
  746. cppSeq & " $1 data[SEQ_DECL_SIZE];$n" &
  747. "};$n", [getTypeDescAux(m, t[0], check, kind), result])
  748. else:
  749. appcg(m, m.s[cfsSeqTypes],
  750. cSeq & " $1 data[SEQ_DECL_SIZE];$n" &
  751. "};$n", [getTypeDescAux(m, t[0], check, kind), result])
  752. else:
  753. result = rope("TGenericSeq")
  754. result.add(seqStar(m))
  755. of tyUncheckedArray:
  756. result = getTypeName(m, origTyp, sig)
  757. m.typeCache[sig] = result
  758. if not isImportedType(t):
  759. let foo = getTypeDescAux(m, t[0], check, kind)
  760. m.s[cfsTypes].addf("typedef $1 $2[1];$n", [foo, result])
  761. of tyArray:
  762. var n: BiggestInt = toInt64(lengthOrd(m.config, t))
  763. if n <= 0: n = 1 # make an array of at least one element
  764. result = getTypeName(m, origTyp, sig)
  765. m.typeCache[sig] = result
  766. if not isImportedType(t):
  767. let foo = getTypeDescAux(m, t[1], check, kind)
  768. m.s[cfsTypes].addf("typedef $1 $2[$3];$n",
  769. [foo, result, rope(n)])
  770. of tyObject, tyTuple:
  771. if isImportedCppType(t) and origTyp.kind == tyGenericInst:
  772. let cppNameAsRope = getTypeName(m, t, sig)
  773. let cppName = $cppNameAsRope
  774. var i = 0
  775. var chunkStart = 0
  776. template addResultType(ty: untyped) =
  777. if ty == nil or ty.kind == tyVoid:
  778. result.add("void")
  779. elif ty.kind == tyStatic:
  780. internalAssert m.config, ty.n != nil
  781. result.add ty.n.renderTree
  782. else:
  783. result.add getTypeDescAux(m, ty, check, kind)
  784. while i < cppName.len:
  785. if cppName[i] == '\'':
  786. var chunkEnd = i-1
  787. var idx, stars: int
  788. if scanCppGenericSlot(cppName, i, idx, stars):
  789. result.add cppName.substr(chunkStart, chunkEnd)
  790. chunkStart = i
  791. let typeInSlot = resolveStarsInCppType(origTyp, idx + 1, stars)
  792. addResultType(typeInSlot)
  793. else:
  794. inc i
  795. if chunkStart != 0:
  796. result.add cppName.substr(chunkStart)
  797. else:
  798. result = cppNameAsRope & "<"
  799. for i in 1..<origTyp.len-1:
  800. if i > 1: result.add(" COMMA ")
  801. addResultType(origTyp[i])
  802. result.add("> ")
  803. # always call for sideeffects:
  804. assert t.kind != tyTuple
  805. discard getRecordDesc(m, t, result, check)
  806. # The resulting type will include commas and these won't play well
  807. # with the C macros for defining procs such as N_NIMCALL. We must
  808. # create a typedef for the type and use it in the proc signature:
  809. let typedefName = "TY" & $sig
  810. m.s[cfsTypes].addf("typedef $1 $2;$n", [result, typedefName])
  811. m.typeCache[sig] = typedefName
  812. result = typedefName
  813. else:
  814. result = cacheGetType(m.forwTypeCache, sig)
  815. if result == "":
  816. result = getTypeName(m, origTyp, sig)
  817. m.forwTypeCache[sig] = result
  818. if not isImportedType(t):
  819. addForwardStructFormat(m, structOrUnion(t), result)
  820. assert m.forwTypeCache[sig] == result
  821. m.typeCache[sig] = result # always call for sideeffects:
  822. if not incompleteType(t):
  823. let recdesc = if t.kind != tyTuple: getRecordDesc(m, t, result, check)
  824. else: getTupleDesc(m, t, result, check)
  825. if not isImportedType(t):
  826. m.s[cfsTypes].add(recdesc)
  827. elif tfIncompleteStruct notin t.flags:
  828. discard # addAbiCheck(m, t, result) # already handled elsewhere
  829. of tySet:
  830. # Don't use the imported name as it may be scoped: 'Foo::SomeKind'
  831. result = rope("tySet_")
  832. t.lastSon.typeName(result)
  833. result.add $t.lastSon.hashType
  834. m.typeCache[sig] = result
  835. if not isImportedType(t):
  836. let s = int(getSize(m.config, t))
  837. case s
  838. of 1, 2, 4, 8: m.s[cfsTypes].addf("typedef NU$2 $1;$n", [result, rope(s*8)])
  839. else: m.s[cfsTypes].addf("typedef NU8 $1[$2];$n",
  840. [result, rope(getSize(m.config, t))])
  841. of tyGenericInst, tyDistinct, tyOrdinal, tyTypeDesc, tyAlias, tySink, tyOwned,
  842. tyUserTypeClass, tyUserTypeClassInst, tyInferred:
  843. result = getTypeDescAux(m, lastSon(t), check, kind)
  844. else:
  845. internalError(m.config, "getTypeDescAux(" & $t.kind & ')')
  846. result = ""
  847. # fixes bug #145:
  848. excl(check, t.id)
  849. proc getTypeDesc(m: BModule, typ: PType; kind = skParam): Rope =
  850. var check = initIntSet()
  851. result = getTypeDescAux(m, typ, check, kind)
  852. type
  853. TClosureTypeKind = enum ## In C closures are mapped to 3 different things.
  854. clHalf, ## fn(args) type without the trailing 'void* env' parameter
  855. clHalfWithEnv, ## fn(args, void* env) type with trailing 'void* env' parameter
  856. clFull ## struct {fn(args, void* env), env}
  857. proc getClosureType(m: BModule, t: PType, kind: TClosureTypeKind): Rope =
  858. assert t.kind == tyProc
  859. var check = initIntSet()
  860. result = getTempName(m)
  861. var rettype, desc: Rope
  862. genProcParams(m, t, rettype, desc, check, declareEnvironment=kind != clHalf)
  863. if not isImportedType(t):
  864. if t.callConv != ccClosure or kind != clFull:
  865. m.s[cfsTypes].addf("typedef $1_PTR($2, $3) $4;$n",
  866. [rope(CallingConvToStr[t.callConv]), rettype, result, desc])
  867. else:
  868. m.s[cfsTypes].addf("typedef struct {$n" &
  869. "N_NIMCALL_PTR($2, ClP_0) $3;$n" &
  870. "void* ClE_0;$n} $1;$n",
  871. [result, rettype, desc])
  872. proc finishTypeDescriptions(m: BModule) =
  873. var i = 0
  874. var check = initIntSet()
  875. while i < m.typeStack.len:
  876. let t = m.typeStack[i]
  877. if optSeqDestructors in m.config.globalOptions and t.skipTypes(abstractInst).kind == tySequence:
  878. seqV2ContentType(m, t, check)
  879. else:
  880. discard getTypeDescAux(m, t, check, skParam)
  881. inc(i)
  882. m.typeStack.setLen 0
  883. template cgDeclFrmt*(s: PSym): string =
  884. s.constraint.strVal
  885. proc isReloadable(m: BModule, prc: PSym): bool =
  886. return m.hcrOn and sfNonReloadable notin prc.flags
  887. proc isNonReloadable(m: BModule, prc: PSym): bool =
  888. return m.hcrOn and sfNonReloadable in prc.flags
  889. proc genProcHeader(m: BModule, prc: PSym; result: var Rope; asPtr: bool = false) =
  890. # using static is needed for inline procs
  891. var check = initIntSet()
  892. fillBackendName(m, prc)
  893. fillLoc(prc.loc, locProc, prc.ast[namePos], OnUnknown)
  894. var rettype, params: Rope
  895. genProcParams(m, prc.typ, rettype, params, check)
  896. # handle the 2 options for hotcodereloading codegen - function pointer
  897. # (instead of forward declaration) or header for function body with "_actual" postfix
  898. let asPtrStr = rope(if asPtr: "_PTR" else: "")
  899. var name = prc.loc.r
  900. if isReloadable(m, prc) and not asPtr:
  901. name.add("_actual")
  902. # careful here! don't access ``prc.ast`` as that could reload large parts of
  903. # the object graph!
  904. if prc.constraint.isNil:
  905. if lfExportLib in prc.loc.flags:
  906. if isHeaderFile in m.flags:
  907. result.add "N_LIB_IMPORT "
  908. else:
  909. result.add "N_LIB_EXPORT "
  910. elif prc.typ.callConv == ccInline or asPtr or isNonReloadable(m, prc):
  911. result.add "static "
  912. elif sfImportc notin prc.flags:
  913. result.add "N_LIB_PRIVATE "
  914. result.addf("$1$2($3, $4)$5",
  915. [rope(CallingConvToStr[prc.typ.callConv]), asPtrStr, rettype, name,
  916. params])
  917. else:
  918. let asPtrStr = if asPtr: (rope("(*") & name & ")") else: name
  919. result.add runtimeFormat(prc.cgDeclFrmt, [rettype, asPtrStr, params])
  920. # ------------------ type info generation -------------------------------------
  921. proc genTypeInfoV1(m: BModule, t: PType; info: TLineInfo): Rope
  922. proc getNimNode(m: BModule): Rope =
  923. result = "$1[$2]" % [m.typeNodesName, rope(m.typeNodes)]
  924. inc(m.typeNodes)
  925. proc tiNameForHcr(m: BModule, name: Rope): Rope =
  926. return if m.hcrOn: "(*".rope & name & ")" else: name
  927. proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
  928. name, base: Rope; info: TLineInfo) =
  929. var nimtypeKind: int
  930. #allocMemTI(m, typ, name)
  931. if isObjLackingTypeField(typ):
  932. nimtypeKind = ord(tyPureObject)
  933. else:
  934. nimtypeKind = ord(typ.kind)
  935. let nameHcr = tiNameForHcr(m, name)
  936. var size: Rope
  937. if tfIncompleteStruct in typ.flags:
  938. size = rope"void*"
  939. else:
  940. size = getTypeDesc(m, origType, skVar)
  941. m.s[cfsTypeInit3].addf(
  942. "$1.size = sizeof($2);$n$1.align = NIM_ALIGNOF($2);$n$1.kind = $3;$n$1.base = $4;$n",
  943. [nameHcr, size, rope(nimtypeKind), base]
  944. )
  945. # compute type flags for GC optimization
  946. var flags = 0
  947. if not containsGarbageCollectedRef(typ): flags = flags or 1
  948. if not canFormAcycle(typ): flags = flags or 2
  949. #else echo("can contain a cycle: " & typeToString(typ))
  950. if flags != 0:
  951. m.s[cfsTypeInit3].addf("$1.flags = $2;$n", [nameHcr, rope(flags)])
  952. cgsym(m, "TNimType")
  953. if isDefined(m.config, "nimTypeNames"):
  954. var typename = typeToString(if origType.typeInst != nil: origType.typeInst
  955. else: origType, preferName)
  956. if typename == "ref object" and origType.skipTypes(skipPtrs).sym != nil:
  957. typename = "anon ref object from " & m.config$origType.skipTypes(skipPtrs).sym.info
  958. m.s[cfsTypeInit3].addf("$1.name = $2;$n",
  959. [nameHcr, makeCString typename])
  960. cgsym(m, "nimTypeRoot")
  961. m.s[cfsTypeInit3].addf("$1.nextType = nimTypeRoot; nimTypeRoot=&$1;$n",
  962. [nameHcr])
  963. if m.hcrOn:
  964. m.s[cfsStrData].addf("static TNimType* $1;$n", [name])
  965. m.hcrCreateTypeInfosProc.addf("\thcrRegisterGlobal($2, \"$1\", sizeof(TNimType), NULL, (void**)&$1);$n",
  966. [name, getModuleDllPath(m, m.module)])
  967. else:
  968. m.s[cfsStrData].addf("N_LIB_PRIVATE TNimType $1;$n", [name])
  969. proc genTypeInfoAux(m: BModule, typ, origType: PType, name: Rope;
  970. info: TLineInfo) =
  971. var base: Rope
  972. if typ.len > 0 and typ.lastSon != nil:
  973. var x = typ.lastSon
  974. if typ.kind == tyObject: x = x.skipTypes(skipPtrs)
  975. if typ.kind == tyPtr and x.kind == tyObject and incompleteType(x):
  976. base = rope("0")
  977. else:
  978. base = genTypeInfoV1(m, x, info)
  979. else:
  980. base = rope("0")
  981. genTypeInfoAuxBase(m, typ, origType, name, base, info)
  982. proc discriminatorTableName(m: BModule, objtype: PType, d: PSym): Rope =
  983. # bugfix: we need to search the type that contains the discriminator:
  984. var objtype = objtype.skipTypes(abstractPtrs)
  985. while lookupInRecord(objtype.n, d.name) == nil:
  986. objtype = objtype[0].skipTypes(abstractPtrs)
  987. if objtype.sym == nil:
  988. internalError(m.config, d.info, "anonymous obj with discriminator")
  989. result = "NimDT_$1_$2" % [rope($hashType(objtype)), rope(d.name.s.mangle)]
  990. proc rope(arg: Int128): Rope = rope($arg)
  991. proc discriminatorTableDecl(m: BModule, objtype: PType, d: PSym): Rope =
  992. cgsym(m, "TNimNode")
  993. var tmp = discriminatorTableName(m, objtype, d)
  994. result = "TNimNode* $1[$2];$n" % [tmp, rope(lengthOrd(m.config, d.typ)+1)]
  995. proc genTNimNodeArray(m: BModule, name: Rope, size: Rope) =
  996. if m.hcrOn:
  997. m.s[cfsData].addf("static TNimNode** $1;$n", [name])
  998. m.hcrCreateTypeInfosProc.addf("\thcrRegisterGlobal($3, \"$1\", sizeof(TNimNode*) * $2, NULL, (void**)&$1);$n",
  999. [name, size, getModuleDllPath(m, m.module)])
  1000. else:
  1001. m.s[cfsTypeInit1].addf("static TNimNode* $1[$2];$n", [name, size])
  1002. proc genObjectFields(m: BModule, typ, origType: PType, n: PNode, expr: Rope;
  1003. info: TLineInfo) =
  1004. case n.kind
  1005. of nkRecList:
  1006. if n.len == 1:
  1007. genObjectFields(m, typ, origType, n[0], expr, info)
  1008. elif n.len > 0:
  1009. var tmp = getTempName(m) & "_" & $n.len
  1010. genTNimNodeArray(m, tmp, rope(n.len))
  1011. for i in 0..<n.len:
  1012. var tmp2 = getNimNode(m)
  1013. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(i), tmp2])
  1014. genObjectFields(m, typ, origType, n[i], tmp2, info)
  1015. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n",
  1016. [expr, rope(n.len), tmp])
  1017. else:
  1018. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2;$n", [expr, rope(n.len)])
  1019. of nkRecCase:
  1020. assert(n[0].kind == nkSym)
  1021. var field = n[0].sym
  1022. var tmp = discriminatorTableName(m, typ, field)
  1023. var L = lengthOrd(m.config, field.typ)
  1024. assert L > 0
  1025. if field.loc.r == "": fillObjectFields(m, typ)
  1026. if field.loc.t == nil:
  1027. internalError(m.config, n.info, "genObjectFields")
  1028. m.s[cfsTypeInit3].addf("$1.kind = 3;$n" &
  1029. "$1.offset = offsetof($2, $3);$n" & "$1.typ = $4;$n" &
  1030. "$1.name = $5;$n" & "$1.sons = &$6[0];$n" &
  1031. "$1.len = $7;$n", [expr, getTypeDesc(m, origType, skVar), field.loc.r,
  1032. genTypeInfoV1(m, field.typ, info),
  1033. makeCString(field.name.s),
  1034. tmp, rope(L)])
  1035. m.s[cfsData].addf("TNimNode* $1[$2];$n", [tmp, rope(L+1)])
  1036. for i in 1..<n.len:
  1037. var b = n[i] # branch
  1038. var tmp2 = getNimNode(m)
  1039. genObjectFields(m, typ, origType, lastSon(b), tmp2, info)
  1040. case b.kind
  1041. of nkOfBranch:
  1042. if b.len < 2:
  1043. internalError(m.config, b.info, "genObjectFields; nkOfBranch broken")
  1044. for j in 0..<b.len - 1:
  1045. if b[j].kind == nkRange:
  1046. var x = toInt(getOrdValue(b[j][0]))
  1047. var y = toInt(getOrdValue(b[j][1]))
  1048. while x <= y:
  1049. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(x), tmp2])
  1050. inc(x)
  1051. else:
  1052. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n",
  1053. [tmp, rope(getOrdValue(b[j])), tmp2])
  1054. of nkElse:
  1055. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n",
  1056. [tmp, rope(L), tmp2])
  1057. else: internalError(m.config, n.info, "genObjectFields(nkRecCase)")
  1058. of nkSym:
  1059. var field = n.sym
  1060. # Do not produce code for void types
  1061. if isEmptyType(field.typ): return
  1062. if field.bitsize == 0:
  1063. if field.loc.r == "": fillObjectFields(m, typ)
  1064. if field.loc.t == nil:
  1065. internalError(m.config, n.info, "genObjectFields")
  1066. m.s[cfsTypeInit3].addf("$1.kind = 1;$n" &
  1067. "$1.offset = offsetof($2, $3);$n" & "$1.typ = $4;$n" &
  1068. "$1.name = $5;$n", [expr, getTypeDesc(m, origType, skVar),
  1069. field.loc.r, genTypeInfoV1(m, field.typ, info), makeCString(field.name.s)])
  1070. else: internalError(m.config, n.info, "genObjectFields")
  1071. proc genObjectInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo) =
  1072. if typ.kind == tyObject:
  1073. if incompleteType(typ):
  1074. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1075. typeToString(typ))
  1076. genTypeInfoAux(m, typ, origType, name, info)
  1077. else:
  1078. genTypeInfoAuxBase(m, typ, origType, name, rope("0"), info)
  1079. var tmp = getNimNode(m)
  1080. if not isImportedType(typ):
  1081. genObjectFields(m, typ, origType, typ.n, tmp, info)
  1082. m.s[cfsTypeInit3].addf("$1.node = &$2;$n", [tiNameForHcr(m, name), tmp])
  1083. var t = typ[0]
  1084. while t != nil:
  1085. t = t.skipTypes(skipPtrs)
  1086. t.flags.incl tfObjHasKids
  1087. t = t[0]
  1088. proc genTupleInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo) =
  1089. genTypeInfoAuxBase(m, typ, typ, name, rope("0"), info)
  1090. var expr = getNimNode(m)
  1091. if typ.len > 0:
  1092. var tmp = getTempName(m) & "_" & $typ.len
  1093. genTNimNodeArray(m, tmp, rope(typ.len))
  1094. for i in 0..<typ.len:
  1095. var a = typ[i]
  1096. var tmp2 = getNimNode(m)
  1097. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(i), tmp2])
  1098. m.s[cfsTypeInit3].addf("$1.kind = 1;$n" &
  1099. "$1.offset = offsetof($2, Field$3);$n" &
  1100. "$1.typ = $4;$n" &
  1101. "$1.name = \"Field$3\";$n",
  1102. [tmp2, getTypeDesc(m, origType, skVar), rope(i), genTypeInfoV1(m, a, info)])
  1103. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n",
  1104. [expr, rope(typ.len), tmp])
  1105. else:
  1106. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2;$n",
  1107. [expr, rope(typ.len)])
  1108. m.s[cfsTypeInit3].addf("$1.node = &$2;$n", [tiNameForHcr(m, name), expr])
  1109. proc genEnumInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1110. # Type information for enumerations is quite heavy, so we do some
  1111. # optimizations here: The ``typ`` field is never set, as it is redundant
  1112. # anyway. We generate a cstring array and a loop over it. Exceptional
  1113. # positions will be reset after the loop.
  1114. genTypeInfoAux(m, typ, typ, name, info)
  1115. var nodePtrs = getTempName(m) & "_" & $typ.n.len
  1116. genTNimNodeArray(m, nodePtrs, rope(typ.n.len))
  1117. var enumNames, specialCases: Rope
  1118. var firstNimNode = m.typeNodes
  1119. var hasHoles = false
  1120. for i in 0..<typ.n.len:
  1121. assert(typ.n[i].kind == nkSym)
  1122. var field = typ.n[i].sym
  1123. var elemNode = getNimNode(m)
  1124. if field.ast == nil:
  1125. # no explicit string literal for the enum field, so use field.name:
  1126. enumNames.add(makeCString(field.name.s))
  1127. else:
  1128. enumNames.add(makeCString(field.ast.strVal))
  1129. if i < typ.n.len - 1: enumNames.add(", \L")
  1130. if field.position != i or tfEnumHasHoles in typ.flags:
  1131. specialCases.addf("$1.offset = $2;$n", [elemNode, rope(field.position)])
  1132. hasHoles = true
  1133. var enumArray = getTempName(m)
  1134. var counter = getTempName(m)
  1135. m.s[cfsTypeInit1].addf("NI $1;$n", [counter])
  1136. m.s[cfsTypeInit1].addf("static char* NIM_CONST $1[$2] = {$n$3};$n",
  1137. [enumArray, rope(typ.n.len), enumNames])
  1138. m.s[cfsTypeInit3].addf("for ($1 = 0; $1 < $2; $1++) {$n" &
  1139. "$3[$1+$4].kind = 1;$n" & "$3[$1+$4].offset = $1;$n" &
  1140. "$3[$1+$4].name = $5[$1];$n" & "$6[$1] = &$3[$1+$4];$n" & "}$n", [counter,
  1141. rope(typ.n.len), m.typeNodesName, rope(firstNimNode), enumArray, nodePtrs])
  1142. m.s[cfsTypeInit3].add(specialCases)
  1143. m.s[cfsTypeInit3].addf(
  1144. "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n",
  1145. [getNimNode(m), rope(typ.n.len), nodePtrs, tiNameForHcr(m, name)])
  1146. if hasHoles:
  1147. # 1 << 2 is {ntfEnumHole}
  1148. m.s[cfsTypeInit3].addf("$1.flags = 1<<2;$n", [tiNameForHcr(m, name)])
  1149. proc genSetInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1150. assert(typ[0] != nil)
  1151. genTypeInfoAux(m, typ, typ, name, info)
  1152. var tmp = getNimNode(m)
  1153. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 0;$n$3.node = &$1;$n",
  1154. [tmp, rope(firstOrd(m.config, typ)), tiNameForHcr(m, name)])
  1155. proc genArrayInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1156. genTypeInfoAuxBase(m, typ, typ, name, genTypeInfoV1(m, typ[1], info), info)
  1157. proc fakeClosureType(m: BModule; owner: PSym): PType =
  1158. # we generate the same RTTI as for a tuple[pointer, ref tuple[]]
  1159. result = newType(tyTuple, nextTypeId m.idgen, owner)
  1160. result.rawAddSon(newType(tyPointer, nextTypeId m.idgen, owner))
  1161. var r = newType(tyRef, nextTypeId m.idgen, owner)
  1162. let obj = createObj(m.g.graph, m.idgen, owner, owner.info, final=false)
  1163. r.rawAddSon(obj)
  1164. result.rawAddSon(r)
  1165. include ccgtrav
  1166. proc genDeepCopyProc(m: BModule; s: PSym; result: Rope) =
  1167. genProc(m, s)
  1168. m.s[cfsTypeInit3].addf("$1.deepcopy =(void* (N_RAW_NIMCALL*)(void*))$2;$n",
  1169. [result, s.loc.r])
  1170. proc declareNimType(m: BModule, name: string; str: Rope, module: int) =
  1171. let nr = rope(name)
  1172. if m.hcrOn:
  1173. m.s[cfsStrData].addf("static $2* $1;$n", [str, nr])
  1174. m.s[cfsTypeInit1].addf("\t$1 = ($3*)hcrGetGlobal($2, \"$1\");$n",
  1175. [str, getModuleDllPath(m, module), nr])
  1176. else:
  1177. m.s[cfsStrData].addf("extern $2 $1;$n", [str, nr])
  1178. proc genTypeInfo2Name(m: BModule; t: PType): Rope =
  1179. var it = t
  1180. it = it.skipTypes(skipPtrs)
  1181. if it.sym != nil and tfFromGeneric notin it.flags:
  1182. var m = it.sym.owner
  1183. while m != nil and m.kind != skModule: m = m.owner
  1184. if m == nil or sfSystemModule in m.flags:
  1185. # produce short names for system types:
  1186. result = it.sym.name.s
  1187. else:
  1188. var p = m.owner
  1189. if p != nil and p.kind == skPackage:
  1190. result.add p.name.s & "."
  1191. result.add m.name.s & "."
  1192. result.add it.sym.name.s
  1193. else:
  1194. result = $hashType(it)
  1195. result = makeCString(result)
  1196. proc isTrivialProc(g: ModuleGraph; s: PSym): bool {.inline.} = getBody(g, s).len == 0
  1197. proc genHook(m: BModule; t: PType; info: TLineInfo; op: TTypeAttachedOp; result: var Rope) =
  1198. let theProc = getAttachedOp(m.g.graph, t, op)
  1199. if theProc != nil and not isTrivialProc(m.g.graph, theProc):
  1200. # the prototype of a destructor is ``=destroy(x: var T)`` and that of a
  1201. # finalizer is: ``proc (x: ref T) {.nimcall.}``. We need to check the calling
  1202. # convention at least:
  1203. if theProc.typ == nil or theProc.typ.callConv != ccNimCall:
  1204. localError(m.config, info,
  1205. theProc.name.s & " needs to have the 'nimcall' calling convention")
  1206. genProc(m, theProc)
  1207. result.add theProc.loc.r
  1208. when false:
  1209. if not canFormAcycle(t) and op == attachedTrace:
  1210. echo "ayclic but has this =trace ", t, " ", theProc.ast
  1211. else:
  1212. when false:
  1213. if op == attachedTrace and m.config.selectedGC == gcOrc and
  1214. containsGarbageCollectedRef(t):
  1215. # unfortunately this check is wrong for an object type that only contains
  1216. # .cursor fields like 'Node' inside 'cycleleak'.
  1217. internalError(m.config, info, "no attached trace proc found")
  1218. result.add rope("NIM_NIL")
  1219. proc getObjDepth(t: PType): int16 =
  1220. var x = t
  1221. result = -1
  1222. while x != nil:
  1223. x = skipTypes(x, skipPtrs)
  1224. x = x[0]
  1225. inc(result)
  1226. proc genDisplayElem(d: MD5Digest): uint32 =
  1227. result = 0
  1228. for i in 0..3:
  1229. result += uint32(d[i])
  1230. result = result shl 8
  1231. proc genDisplay(t: PType, depth: int): Rope =
  1232. result = Rope"{"
  1233. var x = t
  1234. var seqs = newSeq[string](depth+1)
  1235. var i = 0
  1236. while x != nil:
  1237. x = skipTypes(x, skipPtrs)
  1238. seqs[i] = $genDisplayElem(MD5Digest(hashType(x)))
  1239. x = x[0]
  1240. inc i
  1241. for i in countdown(depth, 1):
  1242. result.add seqs[i] & ", "
  1243. result.add seqs[0]
  1244. result.add "}"
  1245. proc genTypeInfoV2Impl(m: BModule; t, origType: PType, name: Rope; info: TLineInfo) =
  1246. cgsym(m, "TNimTypeV2")
  1247. m.s[cfsStrData].addf("N_LIB_PRIVATE TNimTypeV2 $1;$n", [name])
  1248. var flags = 0
  1249. if not canFormAcycle(t): flags = flags or 1
  1250. var typeEntry = newRopeAppender()
  1251. addf(typeEntry, "$1.destructor = (void*)", [name])
  1252. genHook(m, t, info, attachedDestructor, typeEntry)
  1253. addf(typeEntry, "; $1.traceImpl = (void*)", [name])
  1254. genHook(m, t, info, attachedTrace, typeEntry)
  1255. let objDepth = if t.kind == tyObject: getObjDepth(t) else: -1
  1256. if t.kind in {tyObject, tyDistinct} and incompleteType(t):
  1257. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1258. typeToString(t))
  1259. if isDefined(m.config, "nimTypeNames"):
  1260. var typeName: Rope
  1261. if t.kind in {tyObject, tyDistinct}:
  1262. typeName = genTypeInfo2Name(m, t)
  1263. else:
  1264. typeName = rope("NIM_NIL")
  1265. addf(typeEntry, "; $1.name = $2", [name, typeName])
  1266. addf(typeEntry, "; $1.size = sizeof($2); $1.align = (NI16) NIM_ALIGNOF($2); $1.depth = $3; $1.flags = $4;",
  1267. [name, getTypeDesc(m, t), rope(objDepth), rope(flags)])
  1268. if objDepth >= 0:
  1269. let objDisplay = genDisplay(t, objDepth)
  1270. let objDisplayStore = getTempName(m)
  1271. m.s[cfsVars].addf("static $1 $2[$3] = $4;$n", [getTypeDesc(m, getSysType(m.g.graph, unknownLineInfo, tyUInt32), skVar), objDisplayStore, rope(objDepth+1), objDisplay])
  1272. addf(typeEntry, "$1.display = $2;$n", [name, rope(objDisplayStore)])
  1273. m.s[cfsTypeInit3].add typeEntry
  1274. if t.kind == tyObject and t.len > 0 and t[0] != nil and optEnableDeepCopy in m.config.globalOptions:
  1275. discard genTypeInfoV1(m, t, info)
  1276. proc genTypeInfoV2(m: BModule, t: PType; info: TLineInfo): Rope =
  1277. let origType = t
  1278. # distinct types can have their own destructors
  1279. var t = skipTypes(origType, irrelevantForBackend + tyUserTypeClasses - {tyDistinct})
  1280. let prefixTI = if m.hcrOn: "(" else: "(&"
  1281. let sig = hashType(origType)
  1282. result = m.typeInfoMarkerV2.getOrDefault(sig)
  1283. if result != "":
  1284. return prefixTI.rope & result & ")".rope
  1285. let marker = m.g.typeInfoMarkerV2.getOrDefault(sig)
  1286. if marker.str != "":
  1287. cgsym(m, "TNimTypeV2")
  1288. declareNimType(m, "TNimTypeV2", marker.str, marker.owner)
  1289. # also store in local type section:
  1290. m.typeInfoMarkerV2[sig] = marker.str
  1291. return prefixTI.rope & marker.str & ")".rope
  1292. result = "NTIv2$1_" % [rope($sig)]
  1293. m.typeInfoMarkerV2[sig] = result
  1294. let owner = t.skipTypes(typedescPtrs).itemId.module
  1295. if owner != m.module.position and moduleOpenForCodegen(m.g.graph, FileIndex owner):
  1296. # make sure the type info is created in the owner module
  1297. discard genTypeInfoV2(m.g.modules[owner], origType, info)
  1298. # reference the type info as extern here
  1299. cgsym(m, "TNimTypeV2")
  1300. declareNimType(m, "TNimTypeV2", result, owner)
  1301. return prefixTI.rope & result & ")".rope
  1302. m.g.typeInfoMarkerV2[sig] = (str: result, owner: owner)
  1303. genTypeInfoV2Impl(m, t, origType, result, info)
  1304. result = prefixTI.rope & result & ")".rope
  1305. proc openArrayToTuple(m: BModule; t: PType): PType =
  1306. result = newType(tyTuple, nextTypeId m.idgen, t.owner)
  1307. let p = newType(tyPtr, nextTypeId m.idgen, t.owner)
  1308. let a = newType(tyUncheckedArray, nextTypeId m.idgen, t.owner)
  1309. a.add t.lastSon
  1310. p.add a
  1311. result.add p
  1312. result.add getSysType(m.g.graph, t.owner.info, tyInt)
  1313. proc typeToC(t: PType): string =
  1314. ## Just for more readable names, the result doesn't have
  1315. ## to be unique.
  1316. let s = typeToString(t)
  1317. result = newStringOfCap(s.len)
  1318. for i in 0..<s.len:
  1319. let c = s[i]
  1320. case c
  1321. of 'a'..'z':
  1322. result.add c
  1323. of 'A'..'Z':
  1324. result.add toLowerAscii(c)
  1325. of ' ':
  1326. discard
  1327. of ',':
  1328. result.add '_'
  1329. of '.':
  1330. result.add 'O'
  1331. of '[', '(', '{':
  1332. result.add 'L'
  1333. of ']', ')', '}':
  1334. result.add 'T'
  1335. else:
  1336. # We mangle upper letters and digits too so that there cannot
  1337. # be clashes with our special meanings
  1338. result.addInt ord(c)
  1339. proc genTypeInfoV1(m: BModule, t: PType; info: TLineInfo): Rope =
  1340. let origType = t
  1341. var t = skipTypes(origType, irrelevantForBackend + tyUserTypeClasses)
  1342. let prefixTI = if m.hcrOn: "(" else: "(&"
  1343. let sig = hashType(origType)
  1344. result = m.typeInfoMarker.getOrDefault(sig)
  1345. if result != "":
  1346. return prefixTI.rope & result & ")".rope
  1347. let marker = m.g.typeInfoMarker.getOrDefault(sig)
  1348. if marker.str != "":
  1349. cgsym(m, "TNimType")
  1350. cgsym(m, "TNimNode")
  1351. declareNimType(m, "TNimType", marker.str, marker.owner)
  1352. # also store in local type section:
  1353. m.typeInfoMarker[sig] = marker.str
  1354. return prefixTI.rope & marker.str & ")".rope
  1355. result = "NTI$1$2_" % [rope(typeToC(t)), rope($sig)]
  1356. m.typeInfoMarker[sig] = result
  1357. let old = m.g.graph.emittedTypeInfo.getOrDefault($result)
  1358. if old != FileIndex(0):
  1359. cgsym(m, "TNimType")
  1360. cgsym(m, "TNimNode")
  1361. declareNimType(m, "TNimType", result, old.int)
  1362. return prefixTI.rope & result & ")".rope
  1363. var owner = t.skipTypes(typedescPtrs).itemId.module
  1364. if owner != m.module.position and moduleOpenForCodegen(m.g.graph, FileIndex owner):
  1365. # make sure the type info is created in the owner module
  1366. discard genTypeInfoV1(m.g.modules[owner], origType, info)
  1367. # reference the type info as extern here
  1368. cgsym(m, "TNimType")
  1369. cgsym(m, "TNimNode")
  1370. declareNimType(m, "TNimType", result, owner)
  1371. return prefixTI.rope & result & ")".rope
  1372. else:
  1373. owner = m.module.position.int32
  1374. m.g.typeInfoMarker[sig] = (str: result, owner: owner)
  1375. rememberEmittedTypeInfo(m.g.graph, FileIndex(owner), $result)
  1376. case t.kind
  1377. of tyEmpty, tyVoid: result = rope"0"
  1378. of tyPointer, tyBool, tyChar, tyCstring, tyString, tyInt..tyUInt64, tyVar, tyLent:
  1379. genTypeInfoAuxBase(m, t, t, result, rope"0", info)
  1380. of tyStatic:
  1381. if t.n != nil: result = genTypeInfoV1(m, lastSon t, info)
  1382. else: internalError(m.config, "genTypeInfoV1(" & $t.kind & ')')
  1383. of tyUserTypeClasses:
  1384. internalAssert m.config, t.isResolvedUserTypeClass
  1385. return genTypeInfoV1(m, t.lastSon, info)
  1386. of tyProc:
  1387. if t.callConv != ccClosure:
  1388. genTypeInfoAuxBase(m, t, t, result, rope"0", info)
  1389. else:
  1390. let x = fakeClosureType(m, t.owner)
  1391. genTupleInfo(m, x, x, result, info)
  1392. of tySequence:
  1393. genTypeInfoAux(m, t, t, result, info)
  1394. if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcGo}:
  1395. let markerProc = genTraverseProc(m, origType, sig)
  1396. m.s[cfsTypeInit3].addf("$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
  1397. of tyRef:
  1398. genTypeInfoAux(m, t, t, result, info)
  1399. if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcGo}:
  1400. let markerProc = genTraverseProc(m, origType, sig)
  1401. m.s[cfsTypeInit3].addf("$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
  1402. of tyPtr, tyRange, tyUncheckedArray: genTypeInfoAux(m, t, t, result, info)
  1403. of tyArray: genArrayInfo(m, t, result, info)
  1404. of tySet: genSetInfo(m, t, result, info)
  1405. of tyEnum: genEnumInfo(m, t, result, info)
  1406. of tyObject:
  1407. genObjectInfo(m, t, origType, result, info)
  1408. of tyTuple:
  1409. # if t.n != nil: genObjectInfo(m, t, result)
  1410. # else:
  1411. # BUGFIX: use consistently RTTI without proper field names; otherwise
  1412. # results are not deterministic!
  1413. genTupleInfo(m, t, origType, result, info)
  1414. of tyOpenArray:
  1415. let x = openArrayToTuple(m, t)
  1416. genTupleInfo(m, x, origType, result, info)
  1417. else: internalError(m.config, "genTypeInfoV1(" & $t.kind & ')')
  1418. var op = getAttachedOp(m.g.graph, t, attachedDeepCopy)
  1419. if op == nil:
  1420. op = getAttachedOp(m.g.graph, origType, attachedDeepCopy)
  1421. if op != nil:
  1422. genDeepCopyProc(m, op, result)
  1423. if optTinyRtti in m.config.globalOptions and t.kind == tyObject and sfImportc notin t.sym.flags:
  1424. let v2info = genTypeInfoV2(m, origType, info)
  1425. addf(m.s[cfsTypeInit3], "$1->typeInfoV1 = (void*)&$2; $2.typeInfoV2 = (void*)$1;$n", [
  1426. v2info, result])
  1427. result = prefixTI.rope & result & ")".rope
  1428. proc genTypeSection(m: BModule, n: PNode) =
  1429. discard
  1430. proc genTypeInfo*(config: ConfigRef, m: BModule, t: PType; info: TLineInfo): Rope =
  1431. if optTinyRtti in config.globalOptions:
  1432. result = genTypeInfoV2(m, t, info)
  1433. else:
  1434. result = genTypeInfoV1(m, t, info)