ccgtypes.nim 58 KB

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