ccgtypes.nim 76 KB

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