ccgtypes.nim 77 KB

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