ccgtypes.nim 74 KB

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