ccgtypes.nim 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945
  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.snippet == "":
  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.snippet = result
  74. writeMangledName(m.ndi, s, m.config)
  75. proc fillParamName(m: BModule; s: PSym) =
  76. if s.loc.snippet == "":
  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.snippet = 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.snippet == "":
  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.snippet = 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.snippet
  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.snippet == "":
  141. typ.typeName(typ.loc.snippet)
  142. typ.loc.snippet.add $sig
  143. else:
  144. when defined(debugSigHashes):
  145. # check consistency:
  146. var tn = newRopeAppender()
  147. typ.typeName(tn)
  148. assert($typ.loc.snippet == $(tn & $sig))
  149. result = typ.loc.snippet
  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. result = false
  253. else:
  254. result = containsGarbageCollectedRef(t) or
  255. (t.kind == tyObject and not isObjLackingTypeField(t)) or
  256. (getSize(conf, rettype) == szUnknownSize and (t.sym == nil or sfImportc notin t.sym.flags))
  257. else: result = false
  258. proc cacheGetType(tab: TypeCache; sig: SigHash): Rope =
  259. # returns nil if we need to declare this type
  260. # since types are now unique via the ``getUniqueType`` mechanism, this slow
  261. # linear search is not necessary anymore:
  262. result = tab.getOrDefault(sig)
  263. proc addAbiCheck(m: BModule; t: PType, name: Rope) =
  264. if isDefined(m.config, "checkAbi") and (let size = getSize(m.config, t); size != szUnknownSize):
  265. var msg = "backend & Nim disagree on size for: "
  266. msg.addTypeHeader(m.config, t)
  267. var msg2 = ""
  268. msg2.addQuoted msg # not a hostspot so extra allocation doesn't matter
  269. m.s[cfsTypeInfo].addf("NIM_STATIC_ASSERT(sizeof($1) == $2, $3);$n", [name, rope(size), msg2.rope])
  270. # see `testCodegenABICheck` for example error message it generates
  271. proc fillResult(conf: ConfigRef; param: PNode, proctype: PType) =
  272. fillLoc(param.sym.loc, locParam, param, "Result",
  273. OnStack)
  274. let t = param.sym.typ
  275. if mapReturnType(conf, t) != ctArray and isInvalidReturnType(conf, proctype):
  276. incl(param.sym.loc.flags, lfIndirect)
  277. param.sym.loc.storage = OnUnknown
  278. proc typeNameOrLiteral(m: BModule; t: PType, literal: string): Rope =
  279. if t.sym != nil and sfImportc in t.sym.flags and t.sym.magic == mNone:
  280. useHeader(m, t.sym)
  281. result = t.sym.loc.snippet
  282. else:
  283. result = rope(literal)
  284. proc getSimpleTypeDesc(m: BModule; typ: PType): Rope =
  285. const
  286. NumericalTypeToStr: array[tyInt..tyUInt64, string] = [
  287. "NI", "NI8", "NI16", "NI32", "NI64",
  288. "NF", "NF32", "NF64", "NF128",
  289. "NU", "NU8", "NU16", "NU32", "NU64"]
  290. case typ.kind
  291. of tyPointer:
  292. result = typeNameOrLiteral(m, typ, "void*")
  293. of tyString:
  294. case detectStrVersion(m)
  295. of 2:
  296. cgsym(m, "NimStrPayload")
  297. cgsym(m, "NimStringV2")
  298. result = typeNameOrLiteral(m, typ, "NimStringV2")
  299. else:
  300. cgsym(m, "NimStringDesc")
  301. result = typeNameOrLiteral(m, typ, "NimStringDesc*")
  302. of tyCstring: result = typeNameOrLiteral(m, typ, "NCSTRING")
  303. of tyBool: result = typeNameOrLiteral(m, typ, "NIM_BOOL")
  304. of tyChar: result = typeNameOrLiteral(m, typ, "NIM_CHAR")
  305. of tyNil: result = typeNameOrLiteral(m, typ, "void*")
  306. of tyInt..tyUInt64:
  307. result = typeNameOrLiteral(m, typ, NumericalTypeToStr[typ.kind])
  308. of tyRange, tyOrdinal: result = getSimpleTypeDesc(m, typ.skipModifier)
  309. of tyDistinct:
  310. result = getSimpleTypeDesc(m, typ.skipModifier)
  311. if isImportedType(typ) and result != "":
  312. useHeader(m, typ.sym)
  313. result = typ.sym.loc.snippet
  314. of tyStatic:
  315. if typ.n != nil: result = getSimpleTypeDesc(m, skipModifier typ)
  316. else:
  317. result = ""
  318. internalError(m.config, "tyStatic for getSimpleTypeDesc")
  319. of tyGenericInst, tyAlias, tySink, tyOwned:
  320. result = getSimpleTypeDesc(m, skipModifier typ)
  321. else: result = ""
  322. if result != "" and typ.isImportedType():
  323. let sig = hashType(typ, m.config)
  324. if cacheGetType(m.typeCache, sig) == "":
  325. m.typeCache[sig] = result
  326. proc pushType(m: BModule; typ: PType) =
  327. for i in 0..high(m.typeStack):
  328. # pointer equality is good enough here:
  329. if m.typeStack[i] == typ: return
  330. m.typeStack.add(typ)
  331. proc getTypePre(m: BModule; typ: PType; sig: SigHash): Rope =
  332. if typ == nil: result = rope("void")
  333. else:
  334. result = getSimpleTypeDesc(m, typ)
  335. if result == "": result = cacheGetType(m.typeCache, sig)
  336. proc addForwardStructFormat(m: BModule; structOrUnion: Rope, typename: Rope) =
  337. if m.compileToCpp:
  338. m.s[cfsForwardTypes].addf "$1 $2;$n", [structOrUnion, typename]
  339. else:
  340. m.s[cfsForwardTypes].addf "typedef $1 $2 $2;$n", [structOrUnion, typename]
  341. proc seqStar(m: BModule): string =
  342. if optSeqDestructors in m.config.globalOptions: result = ""
  343. else: result = "*"
  344. proc getTypeForward(m: BModule; typ: PType; sig: SigHash): Rope =
  345. result = cacheGetType(m.forwTypeCache, sig)
  346. if result != "": return
  347. result = getTypePre(m, typ, sig)
  348. if result != "": return
  349. let concrete = typ.skipTypes(abstractInst)
  350. case concrete.kind
  351. of tySequence, tyTuple, tyObject:
  352. result = getTypeName(m, typ, sig)
  353. m.forwTypeCache[sig] = result
  354. if not isImportedType(concrete):
  355. addForwardStructFormat(m, structOrUnion(typ), result)
  356. else:
  357. pushType(m, concrete)
  358. doAssert m.forwTypeCache[sig] == result
  359. else: internalError(m.config, "getTypeForward(" & $typ.kind & ')')
  360. proc getTypeDescWeak(m: BModule; t: PType; check: var IntSet; kind: TypeDescKind): Rope =
  361. ## like getTypeDescAux but creates only a *weak* dependency. In other words
  362. ## we know we only need a pointer to it so we only generate a struct forward
  363. ## declaration:
  364. let etB = t.skipTypes(abstractInst)
  365. case etB.kind
  366. of tyObject, tyTuple:
  367. if isImportedCppType(etB) and t.kind == tyGenericInst:
  368. result = getTypeDescAux(m, t, check, kind)
  369. else:
  370. result = getTypeForward(m, t, hashType(t, m.config))
  371. pushType(m, t)
  372. of tySequence:
  373. let sig = hashType(t, m.config)
  374. if optSeqDestructors in m.config.globalOptions:
  375. if skipTypes(etB[0], typedescInst).kind == tyEmpty:
  376. internalError(m.config, "cannot map the empty seq type to a C type")
  377. result = cacheGetType(m.forwTypeCache, sig)
  378. if result == "":
  379. result = getTypeName(m, t, sig)
  380. if not isImportedType(t):
  381. m.forwTypeCache[sig] = result
  382. addForwardStructFormat(m, rope"struct", result)
  383. let payload = result & "_Content"
  384. addForwardStructFormat(m, rope"struct", payload)
  385. if cacheGetType(m.typeCache, sig) == "":
  386. m.typeCache[sig] = result
  387. #echo "adding ", sig, " ", typeToString(t), " ", m.module.name.s
  388. var struct = newBuilder("")
  389. struct.addSimpleStruct(m, name = result, baseType = ""):
  390. struct.addField(name = "len", typ = "NI")
  391. struct.addField(name = "p", typ = ptrType(result & "_Content"))
  392. m.s[cfsTypes].add(struct)
  393. pushType(m, t)
  394. else:
  395. result = getTypeForward(m, t, sig) & seqStar(m)
  396. pushType(m, t)
  397. else:
  398. result = getTypeDescAux(m, t, check, kind)
  399. proc getSeqPayloadType(m: BModule; t: PType): Rope =
  400. var check = initIntSet()
  401. result = getTypeDescWeak(m, t, check, dkParam) & "_Content"
  402. #result = getTypeForward(m, t, hashType(t)) & "_Content"
  403. proc seqV2ContentType(m: BModule; t: PType; check: var IntSet) =
  404. let sig = hashType(t, m.config)
  405. let result = cacheGetType(m.typeCache, sig)
  406. if result == "":
  407. discard getTypeDescAux(m, t, check, dkVar)
  408. else:
  409. var struct = newBuilder("")
  410. struct.addSimpleStruct(m, name = result & "_Content", baseType = ""):
  411. struct.addField(name = "cap", typ = "NI")
  412. struct.addField(name = "data",
  413. typ = getTypeDescAux(m, t.skipTypes(abstractInst)[0], check, dkVar),
  414. isFlexArray = true)
  415. m.s[cfsTypes].add(struct)
  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.snippet = "this"
  488. else:
  489. this.loc.snippet = "(*this)"
  490. names.add this.loc.snippet
  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.snippet
  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.snippet)
  575. else:
  576. params.add runtimeFormat(param.cgDeclFrmt, [typ, param.loc.snippet])
  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.snippet, 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.snippet
  613. else:
  614. result = rope(mangleField(m, field.name))
  615. if result == "": internalError(m.config, field.info, "mangleRecFieldName")
  616. proc hasCppCtor(m: BModule; typ: PType): bool =
  617. result = false
  618. if m.compileToCpp and typ != nil and typ.itemId in m.g.graph.memberProcsPerType:
  619. for prc in m.g.graph.memberProcsPerType[typ.itemId]:
  620. if sfConstructor in prc.flags:
  621. return true
  622. proc genCppParamsForCtor(p: BProc; call: PNode; didGenTemp: var bool): string
  623. proc genCppInitializer(m: BModule, prc: BProc; typ: PType; didGenTemp: var bool): string =
  624. #To avoid creating a BProc per test when called inside a struct nil BProc is allowed
  625. result = "{}"
  626. if typ.itemId in m.g.graph.initializersPerType:
  627. let call = m.g.graph.initializersPerType[typ.itemId]
  628. if call != nil:
  629. var p = prc
  630. if p == nil:
  631. p = BProc(module: m)
  632. result = "{" & genCppParamsForCtor(p, call, didGenTemp) & "}"
  633. if prc == nil:
  634. assert p.blocks.len == 0, "BProc belongs to a struct doesnt have blocks"
  635. proc genRecordFieldsAux(m: BModule; n: PNode,
  636. rectype: PType,
  637. check: var IntSet; result: var Builder; 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 = newBuilder("")
  655. genRecordFieldsAux(m, k, rectype, check, a, unionPrefix & $structName & ".")
  656. if a.len != 0:
  657. unionBody.addFieldWithStructType(m, rectype, structName):
  658. unionBody.add(a)
  659. else:
  660. genRecordFieldsAux(m, k, rectype, check, unionBody, unionPrefix)
  661. else: internalError(m.config, "genRecordFieldsAux(record case branch)")
  662. if unionBody.len != 0:
  663. result.addAnonUnion:
  664. # XXX this has to be a named field for NIFC
  665. result.add(unionBody)
  666. of nkSym:
  667. let field = n.sym
  668. if field.typ.kind == tyVoid: return
  669. #assert(field.ast == nil)
  670. let sname = mangleRecFieldName(m, field)
  671. fillLoc(field.loc, locField, n, unionPrefix & sname, OnUnknown)
  672. # for importcpp'ed objects, we only need to set field.loc, but don't
  673. # have to recurse via 'getTypeDescAux'. And not doing so prevents problems
  674. # with heavily templatized C++ code:
  675. if not isImportedCppType(rectype):
  676. let fieldType = field.loc.lode.typ.skipTypes(abstractInst)
  677. var typ: Rope = ""
  678. var isFlexArray = false
  679. var initializer = ""
  680. if fieldType.kind == tyUncheckedArray:
  681. typ = getTypeDescAux(m, fieldType.elemType, check, dkField)
  682. isFlexArray = true
  683. elif fieldType.kind == tySequence:
  684. # we need to use a weak dependency here for trecursive_table.
  685. typ = getTypeDescWeak(m, field.loc.t, check, dkField)
  686. else:
  687. typ = getTypeDescAux(m, field.loc.t, check, dkField)
  688. # don't use fieldType here because we need the
  689. # tyGenericInst for C++ template support
  690. let noInit = sfNoInit in field.flags or (field.typ.sym != nil and sfNoInit in field.typ.sym.flags)
  691. if not noInit and (fieldType.isOrHasImportedCppType() or hasCppCtor(m, field.owner.typ)):
  692. var didGenTemp = false
  693. initializer = genCppInitializer(m, nil, fieldType, didGenTemp)
  694. result.addField(field, sname, typ, isFlexArray, initializer)
  695. else: internalError(m.config, n.info, "genRecordFieldsAux()")
  696. proc genMemberProcHeader(m: BModule; prc: PSym; result: var Rope; asPtr: bool = false, isFwdDecl:bool = false)
  697. proc addRecordFields(result: var Builder; m: BModule; typ: PType, check: var IntSet) =
  698. genRecordFieldsAux(m, typ.n, typ, check, result)
  699. if typ.itemId in m.g.graph.memberProcsPerType:
  700. let procs = m.g.graph.memberProcsPerType[typ.itemId]
  701. var isDefaultCtorGen, isCtorGen: bool = false
  702. for prc in procs:
  703. var header: Rope = ""
  704. if sfConstructor in prc.flags:
  705. isCtorGen = true
  706. if prc.typ.n.len == 1:
  707. isDefaultCtorGen = true
  708. if lfNoDecl in prc.loc.flags: continue
  709. genMemberProcHeader(m, prc, header, false, true)
  710. result.addf "$1;$n", [header]
  711. if isCtorGen and not isDefaultCtorGen:
  712. var ch: IntSet = default(IntSet)
  713. result.addf "$1() = default;$n", [getTypeDescAux(m, typ, ch, dkOther)]
  714. proc fillObjectFields*(m: BModule; typ: PType) =
  715. # sometimes generic objects are not consistently merged. We patch over
  716. # this fact here.
  717. var check = initIntSet()
  718. var ignored = newBuilder("")
  719. addRecordFields(ignored, m, typ, check)
  720. proc mangleDynLibProc(sym: PSym): Rope
  721. proc getRecordDesc(m: BModule; typ: PType, name: Rope,
  722. check: var IntSet): Rope =
  723. # declare the record:
  724. var baseType: string = ""
  725. if typ.baseClass != nil:
  726. baseType = getTypeDescAux(m, typ.baseClass.skipTypes(skipPtrs), check, dkField)
  727. if typ.sym == nil or sfCodegenDecl notin typ.sym.flags:
  728. result = newBuilder("")
  729. result.addStruct(m, typ, name, baseType):
  730. result.addRecordFields(m, typ, check)
  731. else:
  732. var desc = newBuilder("")
  733. desc.addRecordFields(m, typ, check)
  734. result = runtimeFormat(typ.sym.cgDeclFrmt, [name, desc, baseType])
  735. proc getTupleDesc(m: BModule; typ: PType, name: Rope,
  736. check: var IntSet): Rope =
  737. result = newBuilder("")
  738. result.addStruct(m, typ, name, ""):
  739. for i, a in typ.ikids:
  740. result.addField(
  741. name = "Field" & $i,
  742. typ = getTypeDescAux(m, a, check, dkField))
  743. proc scanCppGenericSlot(pat: string, cursor, outIdx, outStars: var int): bool =
  744. # A helper proc for handling cppimport patterns, involving numeric
  745. # placeholders for generic types (e.g. '0, '**2, etc).
  746. # pre: the cursor must be placed at the ' symbol
  747. # post: the cursor will be placed after the final digit
  748. # false will returned if the input is not recognized as a placeholder
  749. inc cursor
  750. let begin = cursor
  751. while pat[cursor] == '*': inc cursor
  752. if pat[cursor] in Digits:
  753. outIdx = pat[cursor].ord - '0'.ord
  754. outStars = cursor - begin
  755. inc cursor
  756. return true
  757. else:
  758. return false
  759. proc resolveStarsInCppType(typ: PType, idx, stars: int): PType =
  760. # Make sure the index refers to one of the generic params of the type.
  761. # XXX: we should catch this earlier and report it as a semantic error.
  762. if idx >= typ.kidsLen:
  763. raiseAssert "invalid apostrophe type parameter index"
  764. result = typ[idx]
  765. for i in 1..stars:
  766. if result != nil and result.kidsLen > 0:
  767. result = if result.kind == tyGenericInst: result[FirstGenericParamAt]
  768. else: result.elemType
  769. proc getOpenArrayDesc(m: BModule; t: PType, check: var IntSet; kind: TypeDescKind): Rope =
  770. let sig = hashType(t, m.config)
  771. if kind == dkParam:
  772. result = getTypeDescWeak(m, t.elementType, check, kind) & "*"
  773. else:
  774. result = cacheGetType(m.typeCache, sig)
  775. if result == "":
  776. result = getTypeName(m, t, sig)
  777. m.typeCache[sig] = result
  778. let elemType = getTypeDescWeak(m, t.elementType, check, kind)
  779. var typedef = newBuilder("")
  780. typedef.addTypedef(name = result):
  781. typedef.addSimpleStruct(m, name = "", baseType = ""):
  782. typedef.addField(name = "Field0", typ = ptrType(elemType))
  783. typedef.addField(name = "Field1", typ = "NI")
  784. m.s[cfsTypes].add(typedef)
  785. proc getTypeDescAux(m: BModule; origTyp: PType, check: var IntSet; kind: TypeDescKind): Rope =
  786. # returns only the type's name
  787. var t = origTyp.skipTypes(irrelevantForBackend-{tyOwned})
  788. if containsOrIncl(check, t.id):
  789. if not (isImportedCppType(origTyp) or isImportedCppType(t)):
  790. internalError(m.config, "cannot generate C type for: " & typeToString(origTyp))
  791. # XXX: this BUG is hard to fix -> we need to introduce helper structs,
  792. # but determining when this needs to be done is hard. We should split
  793. # C type generation into an analysis and a code generation phase somehow.
  794. if t.sym != nil: useHeader(m, t.sym)
  795. if t != origTyp and origTyp.sym != nil: useHeader(m, origTyp.sym)
  796. let sig = hashType(origTyp, m.config)
  797. # tyDistinct matters if it is an importc type
  798. result = getTypePre(m, origTyp.skipTypes(irrelevantForBackend-{tyOwned, tyDistinct}), sig)
  799. defer: # defer is the simplest in this case
  800. if isImportedType(t) and not m.typeABICache.containsOrIncl(sig):
  801. addAbiCheck(m, t, result)
  802. if result != "" and t.kind != tyOpenArray:
  803. excl(check, t.id)
  804. if kind == dkRefParam or kind == dkRefGenericParam and origTyp.kind == tyGenericInst:
  805. result.add("&")
  806. return
  807. case t.kind
  808. of tyRef, tyPtr, tyVar, tyLent:
  809. var star = if t.kind in {tyVar} and tfVarIsPtr notin origTyp.flags and
  810. compileToCpp(m): "&" else: "*"
  811. var et = origTyp.skipTypes(abstractInst).elementType
  812. var etB = et.skipTypes(abstractInst)
  813. if mapType(m.config, t, kind == dkParam) == ctPtrToArray and (etB.kind != tyOpenArray or kind == dkParam):
  814. if etB.kind == tySet:
  815. et = getSysType(m.g.graph, unknownLineInfo, tyUInt8)
  816. else:
  817. et = elemType(etB)
  818. etB = et.skipTypes(abstractInst)
  819. star[0] = '*'
  820. case etB.kind
  821. of tyObject, tyTuple:
  822. if isImportedCppType(etB) and et.kind == tyGenericInst:
  823. result = getTypeDescAux(m, et, check, kind) & star
  824. else:
  825. # no restriction! We have a forward declaration for structs
  826. let name = getTypeForward(m, et, hashType(et, m.config))
  827. result = name & star
  828. m.typeCache[sig] = result
  829. of tySequence:
  830. if optSeqDestructors in m.config.globalOptions:
  831. result = getTypeDescWeak(m, et, check, kind) & star
  832. m.typeCache[sig] = result
  833. else:
  834. # no restriction! We have a forward declaration for structs
  835. let name = getTypeForward(m, et, hashType(et, m.config))
  836. result = name & seqStar(m) & star
  837. m.typeCache[sig] = result
  838. pushType(m, et)
  839. else:
  840. # else we have a strong dependency :-(
  841. result = getTypeDescAux(m, et, check, kind) & star
  842. m.typeCache[sig] = result
  843. of tyOpenArray, tyVarargs:
  844. result = getOpenArrayDesc(m, t, check, kind)
  845. of tyEnum:
  846. result = cacheGetType(m.typeCache, sig)
  847. if result == "":
  848. result = getTypeName(m, origTyp, sig)
  849. if not (isImportedCppType(t) or
  850. (sfImportc in t.sym.flags and t.sym.magic == mNone)):
  851. m.typeCache[sig] = result
  852. var size: int
  853. if firstOrd(m.config, t) < 0:
  854. m.s[cfsTypes].addf("typedef NI32 $1;$n", [result])
  855. size = 4
  856. else:
  857. size = int(getSize(m.config, t))
  858. case size
  859. of 1: m.s[cfsTypes].addf("typedef NU8 $1;$n", [result])
  860. of 2: m.s[cfsTypes].addf("typedef NU16 $1;$n", [result])
  861. of 4: m.s[cfsTypes].addf("typedef NI32 $1;$n", [result])
  862. of 8: m.s[cfsTypes].addf("typedef NI64 $1;$n", [result])
  863. else: internalError(m.config, t.sym.info, "getTypeDescAux: enum")
  864. when false:
  865. let owner = hashOwner(t.sym)
  866. if not gDebugInfo.hasEnum(t.sym.name.s, t.sym.info.line, owner):
  867. var vals: seq[(string, int)] = @[]
  868. for i in 0..<t.n.len:
  869. assert(t.n[i].kind == nkSym)
  870. let field = t.n[i].sym
  871. vals.add((field.name.s, field.position.int))
  872. gDebugInfo.registerEnum(EnumDesc(size: size, owner: owner, id: t.sym.id,
  873. name: t.sym.name.s, values: vals))
  874. of tyProc:
  875. result = getTypeName(m, origTyp, sig)
  876. m.typeCache[sig] = result
  877. var rettype, desc: Rope = ""
  878. genProcParams(m, t, rettype, desc, check, true, true)
  879. if not isImportedType(t):
  880. var typedef = newBuilder("")
  881. if t.callConv != ccClosure: # procedure vars may need a closure!
  882. typedef.addTypedef(name = desc):
  883. typedef.add(procPtrType(t.callConv, rettype = rettype, name = result))
  884. else:
  885. typedef.addTypedef(name = result):
  886. typedef.addSimpleStruct(m, name = "", baseType = ""):
  887. typedef.addField(name = desc, typ =
  888. procPtrType(ccNimCall, rettype = rettype, name = "ClP_0"))
  889. typedef.addField(name = "ClE_0", typ = "void*")
  890. m.s[cfsTypes].add(typedef)
  891. of tySequence:
  892. if optSeqDestructors in m.config.globalOptions:
  893. result = getTypeDescWeak(m, t, check, kind)
  894. else:
  895. # we cannot use getTypeForward here because then t would be associated
  896. # with the name of the struct, not with the pointer to the struct:
  897. result = cacheGetType(m.forwTypeCache, sig)
  898. if result == "":
  899. result = getTypeName(m, origTyp, sig)
  900. if not isImportedType(t):
  901. addForwardStructFormat(m, structOrUnion(t), result)
  902. m.forwTypeCache[sig] = result
  903. assert(cacheGetType(m.typeCache, sig) == "")
  904. m.typeCache[sig] = result & seqStar(m)
  905. if not isImportedType(t):
  906. if skipTypes(t.elementType, typedescInst).kind != tyEmpty:
  907. var struct = newBuilder("")
  908. let baseType = cgsymValue(m, "TGenericSeq")
  909. struct.addSimpleStruct(m, name = result, baseType = baseType):
  910. struct.addField(
  911. name = "data",
  912. typ = getTypeDescAux(m, t.elementType, check, kind),
  913. isFlexArray = true)
  914. m.s[cfsSeqTypes].add struct
  915. else:
  916. result = rope("TGenericSeq")
  917. result.add(seqStar(m))
  918. of tyUncheckedArray:
  919. result = getTypeName(m, origTyp, sig)
  920. m.typeCache[sig] = result
  921. if not isImportedType(t):
  922. let foo = getTypeDescAux(m, t.elementType, check, kind)
  923. m.s[cfsTypes].addf("typedef $1 $2[1];$n", [foo, result])
  924. of tyArray:
  925. var n: BiggestInt = toInt64(lengthOrd(m.config, t))
  926. if n <= 0: n = 1 # make an array of at least one element
  927. result = getTypeName(m, origTyp, sig)
  928. m.typeCache[sig] = result
  929. if not isImportedType(t):
  930. let e = getTypeDescAux(m, t.elementType, check, kind)
  931. m.s[cfsTypes].addf("typedef $1 $2[$3];$n",
  932. [e, result, rope(n)])
  933. of tyObject, tyTuple:
  934. let tt = origTyp.skipTypes({tyDistinct})
  935. if isImportedCppType(t) and tt.kind == tyGenericInst:
  936. let cppNameAsRope = getTypeName(m, t, sig)
  937. let cppName = $cppNameAsRope
  938. var i = 0
  939. var chunkStart = 0
  940. template addResultType(ty: untyped) =
  941. if ty == nil or ty.kind == tyVoid:
  942. result.add("void")
  943. elif ty.kind == tyStatic:
  944. internalAssert m.config, ty.n != nil
  945. result.add ty.n.renderTree
  946. else:
  947. result.add getTypeDescAux(m, ty, check, kind)
  948. while i < cppName.len:
  949. if cppName[i] == '\'':
  950. var chunkEnd = i-1
  951. var idx, stars: int = 0
  952. if scanCppGenericSlot(cppName, i, idx, stars):
  953. result.add cppName.substr(chunkStart, chunkEnd)
  954. chunkStart = i
  955. let typeInSlot = resolveStarsInCppType(tt, idx + 1, stars)
  956. addResultType(typeInSlot)
  957. else:
  958. inc i
  959. if chunkStart != 0:
  960. result.add cppName.substr(chunkStart)
  961. else:
  962. result = cppNameAsRope & "<"
  963. for needsComma, a in tt.genericInstParams:
  964. if needsComma: result.add(" COMMA ")
  965. addResultType(a)
  966. result.add("> ")
  967. # always call for sideeffects:
  968. assert t.kind != tyTuple
  969. discard getRecordDesc(m, t, result, check)
  970. # The resulting type will include commas and these won't play well
  971. # with the C macros for defining procs such as N_NIMCALL. We must
  972. # create a typedef for the type and use it in the proc signature:
  973. let typedefName = "TY" & $sig
  974. m.s[cfsTypes].addf("typedef $1 $2;$n", [result, typedefName])
  975. m.typeCache[sig] = typedefName
  976. result = typedefName
  977. else:
  978. result = cacheGetType(m.forwTypeCache, sig)
  979. if result == "":
  980. result = getTypeName(m, origTyp, sig)
  981. m.forwTypeCache[sig] = result
  982. if not isImportedType(t):
  983. addForwardStructFormat(m, structOrUnion(t), result)
  984. assert m.forwTypeCache[sig] == result
  985. m.typeCache[sig] = result # always call for sideeffects:
  986. if not incompleteType(t):
  987. let recdesc = if t.kind != tyTuple: getRecordDesc(m, t, result, check)
  988. else: getTupleDesc(m, t, result, check)
  989. if not isImportedType(t):
  990. m.s[cfsTypes].add(recdesc)
  991. elif tfIncompleteStruct notin t.flags:
  992. discard # addAbiCheck(m, t, result) # already handled elsewhere
  993. of tySet:
  994. # Don't use the imported name as it may be scoped: 'Foo::SomeKind'
  995. result = rope("tySet_")
  996. t.elementType.typeName(result)
  997. result.add $t.elementType.hashType(m.config)
  998. m.typeCache[sig] = result
  999. if not isImportedType(t):
  1000. let s = int(getSize(m.config, t))
  1001. case s
  1002. of 1, 2, 4, 8: m.s[cfsTypes].addf("typedef NU$2 $1;$n", [result, rope(s*8)])
  1003. else: m.s[cfsTypes].addf("typedef NU8 $1[$2];$n",
  1004. [result, rope(getSize(m.config, t))])
  1005. of tyGenericInst, tyDistinct, tyOrdinal, tyTypeDesc, tyAlias, tySink, tyOwned,
  1006. tyUserTypeClass, tyUserTypeClassInst, tyInferred:
  1007. result = getTypeDescAux(m, skipModifier(t), check, kind)
  1008. else:
  1009. internalError(m.config, "getTypeDescAux(" & $t.kind & ')')
  1010. result = ""
  1011. # fixes bug #145:
  1012. excl(check, t.id)
  1013. proc getTypeDesc(m: BModule; typ: PType; kind = dkParam): Rope =
  1014. var check = initIntSet()
  1015. result = getTypeDescAux(m, typ, check, kind)
  1016. type
  1017. TClosureTypeKind = enum ## In C closures are mapped to 3 different things.
  1018. clHalf, ## fn(args) type without the trailing 'void* env' parameter
  1019. clHalfWithEnv, ## fn(args, void* env) type with trailing 'void* env' parameter
  1020. clFull ## struct {fn(args, void* env), env}
  1021. proc getClosureType(m: BModule; t: PType, kind: TClosureTypeKind): Rope =
  1022. assert t.kind == tyProc
  1023. var check = initIntSet()
  1024. result = getTempName(m)
  1025. var rettype, desc: Rope = ""
  1026. genProcParams(m, t, rettype, desc, check, declareEnvironment=kind != clHalf)
  1027. if not isImportedType(t):
  1028. var typedef = newBuilder("")
  1029. if t.callConv != ccClosure or kind != clFull:
  1030. typedef.addTypedef(name = desc):
  1031. typedef.add(procPtrType(t.callConv, rettype = rettype, name = result))
  1032. else:
  1033. typedef.addTypedef(name = result):
  1034. typedef.addSimpleStruct(m, name = "", baseType = ""):
  1035. typedef.addField(name = desc, typ =
  1036. procPtrType(ccNimCall, rettype = rettype, name = "ClP_0"))
  1037. typedef.addField(name = "ClE_0", typ = "void*")
  1038. m.s[cfsTypes].add(typedef)
  1039. proc finishTypeDescriptions(m: BModule) =
  1040. var i = 0
  1041. var check = initIntSet()
  1042. while i < m.typeStack.len:
  1043. let t = m.typeStack[i]
  1044. if optSeqDestructors in m.config.globalOptions and t.skipTypes(abstractInst).kind == tySequence:
  1045. seqV2ContentType(m, t, check)
  1046. else:
  1047. discard getTypeDescAux(m, t, check, dkParam)
  1048. inc(i)
  1049. m.typeStack.setLen 0
  1050. proc isReloadable(m: BModule; prc: PSym): bool =
  1051. return m.hcrOn and sfNonReloadable notin prc.flags
  1052. proc isNonReloadable(m: BModule; prc: PSym): bool =
  1053. return m.hcrOn and sfNonReloadable in prc.flags
  1054. proc parseVFunctionDecl(val: string; name, params, retType, superCall: var string; isFnConst, isOverride, isMemberVirtual, isStatic: var bool; isCtor: bool, isFunctor=false) =
  1055. var afterParams: string = ""
  1056. if scanf(val, "$*($*)$s$*", name, params, afterParams):
  1057. if name.strip() == "operator" and params == "": #isFunctor?
  1058. parseVFunctionDecl(afterParams, name, params, retType, superCall, isFnConst, isOverride, isMemberVirtual, isStatic, isCtor, true)
  1059. return
  1060. if name.find("static ") > -1:
  1061. isStatic = true
  1062. name = name.replace("static ", "")
  1063. isFnConst = afterParams.find("const") > -1
  1064. isOverride = afterParams.find("override") > -1
  1065. isMemberVirtual = name.find("virtual ") > -1
  1066. if isMemberVirtual:
  1067. name = name.replace("virtual ", "")
  1068. if isFunctor:
  1069. name = "operator ()"
  1070. if isCtor:
  1071. discard scanf(afterParams, ":$s$*", superCall)
  1072. else:
  1073. discard scanf(afterParams, "->$s$* ", retType)
  1074. params = "(" & params & ")"
  1075. proc genMemberProcHeader(m: BModule; prc: PSym; result: var Rope; asPtr: bool = false, isFwdDecl: bool = false) =
  1076. assert sfCppMember * prc.flags != {}
  1077. let isCtor = sfConstructor in prc.flags
  1078. var check = initIntSet()
  1079. fillBackendName(m, prc)
  1080. fillLoc(prc.loc, locProc, prc.ast[namePos], OnUnknown)
  1081. var memberOp = "#." #only virtual
  1082. var typ: PType
  1083. if isCtor:
  1084. typ = prc.typ.returnType
  1085. else:
  1086. typ = prc.typ.firstParamType
  1087. if typ.kind == tyPtr:
  1088. typ = typ.elementType
  1089. memberOp = "#->"
  1090. var typDesc = getTypeDescWeak(m, typ, check, dkParam)
  1091. let asPtrStr = rope(if asPtr: "_PTR" else: "")
  1092. var name, params, rettype, superCall: string = ""
  1093. var isFnConst, isOverride, isMemberVirtual, isStatic: bool = false
  1094. parseVFunctionDecl(prc.constraint.strVal, name, params, rettype, superCall, isFnConst, isOverride, isMemberVirtual, isStatic, isCtor)
  1095. genMemberProcParams(m, prc, superCall, rettype, name, params, check, true, false)
  1096. let isVirtual = sfVirtual in prc.flags or isMemberVirtual
  1097. var fnConst, override: string = ""
  1098. if isCtor:
  1099. name = typDesc
  1100. if isFnConst:
  1101. fnConst = " const"
  1102. if isFwdDecl:
  1103. if isStatic:
  1104. result.add "static "
  1105. if isVirtual:
  1106. rettype = "virtual " & rettype
  1107. if isOverride:
  1108. override = " override"
  1109. superCall = ""
  1110. else:
  1111. if not isCtor:
  1112. prc.loc.snippet = "$1$2(@)" % [memberOp, name]
  1113. elif superCall != "":
  1114. superCall = " : " & superCall
  1115. name = "$1::$2" % [typDesc, name]
  1116. result.add "N_LIB_PRIVATE "
  1117. result.addf("$1$2($3, $4)$5$6$7$8",
  1118. [rope(CallingConvToStr[prc.typ.callConv]), asPtrStr, rettype, name,
  1119. params, fnConst, override, superCall])
  1120. proc genProcHeader(m: BModule; prc: PSym; result: var Rope; asPtr: bool = false) =
  1121. # using static is needed for inline procs
  1122. var check = initIntSet()
  1123. fillBackendName(m, prc)
  1124. fillLoc(prc.loc, locProc, prc.ast[namePos], OnUnknown)
  1125. var rettype, params: Rope = ""
  1126. genProcParams(m, prc.typ, rettype, params, check, true, false)
  1127. # handle the 2 options for hotcodereloading codegen - function pointer
  1128. # (instead of forward declaration) or header for function body with "_actual" postfix
  1129. let asPtrStr = rope(if asPtr: "_PTR" else: "")
  1130. var name = prc.loc.snippet
  1131. if not asPtr and isReloadable(m, prc):
  1132. name.add("_actual")
  1133. # careful here! don't access ``prc.ast`` as that could reload large parts of
  1134. # the object graph!
  1135. if sfCodegenDecl notin prc.flags:
  1136. if lfExportLib in prc.loc.flags:
  1137. if isHeaderFile in m.flags:
  1138. result.add "N_LIB_IMPORT "
  1139. else:
  1140. result.add "N_LIB_EXPORT "
  1141. elif prc.typ.callConv == ccInline or asPtr or isNonReloadable(m, prc):
  1142. result.add "static "
  1143. elif sfImportc notin prc.flags:
  1144. result.add "N_LIB_PRIVATE "
  1145. result.addf("$1$2($3, $4)$5",
  1146. [rope(CallingConvToStr[prc.typ.callConv]), asPtrStr, rettype, name,
  1147. params])
  1148. else:
  1149. let asPtrStr = if asPtr: (rope("(*") & name & ")") else: name
  1150. result.add runtimeFormat(prc.cgDeclFrmt, [rettype, asPtrStr, params])
  1151. # ------------------ type info generation -------------------------------------
  1152. proc genTypeInfoV1(m: BModule; t: PType; info: TLineInfo): Rope
  1153. proc getNimNode(m: BModule): Rope =
  1154. result = "$1[$2]" % [m.typeNodesName, rope(m.typeNodes)]
  1155. inc(m.typeNodes)
  1156. proc tiNameForHcr(m: BModule; name: Rope): Rope =
  1157. return if m.hcrOn: "(*".rope & name & ")" else: name
  1158. proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
  1159. name, base: Rope; info: TLineInfo) =
  1160. var nimtypeKind: int
  1161. #allocMemTI(m, typ, name)
  1162. if isObjLackingTypeField(typ):
  1163. nimtypeKind = ord(tyPureObject)
  1164. else:
  1165. nimtypeKind = ord(typ.kind)
  1166. let nameHcr = tiNameForHcr(m, name)
  1167. var size: Rope
  1168. if tfIncompleteStruct in typ.flags:
  1169. size = rope"void*"
  1170. else:
  1171. size = getTypeDesc(m, origType, dkVar)
  1172. m.s[cfsTypeInit3].addf(
  1173. "$1.size = sizeof($2);$n$1.align = NIM_ALIGNOF($2);$n$1.kind = $3;$n$1.base = $4;$n",
  1174. [nameHcr, size, rope(nimtypeKind), base]
  1175. )
  1176. # compute type flags for GC optimization
  1177. var flags = 0
  1178. if not containsGarbageCollectedRef(typ): flags = flags or 1
  1179. if not canFormAcycle(m.g.graph, typ): flags = flags or 2
  1180. #else echo("can contain a cycle: " & typeToString(typ))
  1181. if flags != 0:
  1182. m.s[cfsTypeInit3].addf("$1.flags = $2;$n", [nameHcr, rope(flags)])
  1183. cgsym(m, "TNimType")
  1184. if isDefined(m.config, "nimTypeNames"):
  1185. var typename = typeToString(if origType.typeInst != nil: origType.typeInst
  1186. else: origType, preferName)
  1187. if typename == "ref object" and origType.skipTypes(skipPtrs).sym != nil:
  1188. typename = "anon ref object from " & m.config$origType.skipTypes(skipPtrs).sym.info
  1189. m.s[cfsTypeInit3].addf("$1.name = $2;$n",
  1190. [nameHcr, makeCString typename])
  1191. cgsym(m, "nimTypeRoot")
  1192. m.s[cfsTypeInit3].addf("$1.nextType = nimTypeRoot; nimTypeRoot=&$1;$n",
  1193. [nameHcr])
  1194. if m.hcrOn:
  1195. m.s[cfsStrData].addf("static TNimType* $1;$n", [name])
  1196. m.hcrCreateTypeInfosProc.addf("\thcrRegisterGlobal($2, \"$1\", sizeof(TNimType), NULL, (void**)&$1);$n",
  1197. [name, getModuleDllPath(m, m.module)])
  1198. else:
  1199. m.s[cfsStrData].addf("N_LIB_PRIVATE TNimType $1;$n", [name])
  1200. proc genTypeInfoAux(m: BModule; typ, origType: PType, name: Rope;
  1201. info: TLineInfo) =
  1202. var base: Rope
  1203. if typ.hasElementType and typ.last != nil:
  1204. var x = typ.last
  1205. if typ.kind == tyObject: x = x.skipTypes(skipPtrs)
  1206. if typ.kind == tyPtr and x.kind == tyObject and incompleteType(x):
  1207. base = rope("0")
  1208. else:
  1209. base = genTypeInfoV1(m, x, info)
  1210. else:
  1211. base = rope("0")
  1212. genTypeInfoAuxBase(m, typ, origType, name, base, info)
  1213. proc discriminatorTableName(m: BModule; objtype: PType, d: PSym): Rope =
  1214. # bugfix: we need to search the type that contains the discriminator:
  1215. var objtype = objtype.skipTypes(abstractPtrs)
  1216. while lookupInRecord(objtype.n, d.name) == nil:
  1217. objtype = objtype[0].skipTypes(abstractPtrs)
  1218. if objtype.sym == nil:
  1219. internalError(m.config, d.info, "anonymous obj with discriminator")
  1220. result = "NimDT_$1_$2" % [rope($hashType(objtype, m.config)), rope(d.name.s.mangle)]
  1221. proc rope(arg: Int128): Rope = rope($arg)
  1222. proc discriminatorTableDecl(m: BModule; objtype: PType, d: PSym): Rope =
  1223. cgsym(m, "TNimNode")
  1224. var tmp = discriminatorTableName(m, objtype, d)
  1225. result = "TNimNode* $1[$2];$n" % [tmp, rope(lengthOrd(m.config, d.typ)+1)]
  1226. proc genTNimNodeArray(m: BModule; name: Rope, size: Rope) =
  1227. if m.hcrOn:
  1228. m.s[cfsData].addf("static TNimNode** $1;$n", [name])
  1229. m.hcrCreateTypeInfosProc.addf("\thcrRegisterGlobal($3, \"$1\", sizeof(TNimNode*) * $2, NULL, (void**)&$1);$n",
  1230. [name, size, getModuleDllPath(m, m.module)])
  1231. else:
  1232. m.s[cfsTypeInit1].addf("static TNimNode* $1[$2];$n", [name, size])
  1233. proc genObjectFields(m: BModule; typ, origType: PType, n: PNode, expr: Rope;
  1234. info: TLineInfo) =
  1235. case n.kind
  1236. of nkRecList:
  1237. if n.len == 1:
  1238. genObjectFields(m, typ, origType, n[0], expr, info)
  1239. elif n.len > 0:
  1240. var tmp = getTempName(m) & "_" & $n.len
  1241. genTNimNodeArray(m, tmp, rope(n.len))
  1242. for i in 0..<n.len:
  1243. var tmp2 = getNimNode(m)
  1244. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(i), tmp2])
  1245. genObjectFields(m, typ, origType, n[i], tmp2, info)
  1246. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n",
  1247. [expr, rope(n.len), tmp])
  1248. else:
  1249. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2;$n", [expr, rope(n.len)])
  1250. of nkRecCase:
  1251. assert(n[0].kind == nkSym)
  1252. var field = n[0].sym
  1253. var tmp = discriminatorTableName(m, typ, field)
  1254. var L = lengthOrd(m.config, field.typ)
  1255. assert L > 0
  1256. if field.loc.snippet == "": fillObjectFields(m, typ)
  1257. if field.loc.t == nil:
  1258. internalError(m.config, n.info, "genObjectFields")
  1259. m.s[cfsTypeInit3].addf("$1.kind = 3;$n" &
  1260. "$1.offset = offsetof($2, $3);$n" & "$1.typ = $4;$n" &
  1261. "$1.name = $5;$n" & "$1.sons = &$6[0];$n" &
  1262. "$1.len = $7;$n", [expr, getTypeDesc(m, origType, dkVar), field.loc.snippet,
  1263. genTypeInfoV1(m, field.typ, info),
  1264. makeCString(field.name.s),
  1265. tmp, rope(L)])
  1266. m.s[cfsData].addf("TNimNode* $1[$2];$n", [tmp, rope(L+1)])
  1267. for i in 1..<n.len:
  1268. var b = n[i] # branch
  1269. var tmp2 = getNimNode(m)
  1270. genObjectFields(m, typ, origType, lastSon(b), tmp2, info)
  1271. case b.kind
  1272. of nkOfBranch:
  1273. if b.len < 2:
  1274. internalError(m.config, b.info, "genObjectFields; nkOfBranch broken")
  1275. for j in 0..<b.len - 1:
  1276. if b[j].kind == nkRange:
  1277. var x = toInt(getOrdValue(b[j][0]))
  1278. var y = toInt(getOrdValue(b[j][1]))
  1279. while x <= y:
  1280. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(x), tmp2])
  1281. inc(x)
  1282. else:
  1283. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n",
  1284. [tmp, rope(getOrdValue(b[j])), tmp2])
  1285. of nkElse:
  1286. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n",
  1287. [tmp, rope(L), tmp2])
  1288. else: internalError(m.config, n.info, "genObjectFields(nkRecCase)")
  1289. of nkSym:
  1290. var field = n.sym
  1291. # Do not produce code for void types
  1292. if isEmptyType(field.typ): return
  1293. if field.bitsize == 0:
  1294. if field.loc.snippet == "": fillObjectFields(m, typ)
  1295. if field.loc.t == nil:
  1296. internalError(m.config, n.info, "genObjectFields")
  1297. m.s[cfsTypeInit3].addf("$1.kind = 1;$n" &
  1298. "$1.offset = offsetof($2, $3);$n" & "$1.typ = $4;$n" &
  1299. "$1.name = $5;$n", [expr, getTypeDesc(m, origType, dkVar),
  1300. field.loc.snippet, genTypeInfoV1(m, field.typ, info), makeCString(field.name.s)])
  1301. else: internalError(m.config, n.info, "genObjectFields")
  1302. proc genObjectInfo(m: BModule; typ, origType: PType, name: Rope; info: TLineInfo) =
  1303. assert typ.kind == tyObject
  1304. if incompleteType(typ):
  1305. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1306. typeToString(typ))
  1307. genTypeInfoAux(m, typ, origType, name, info)
  1308. var tmp = getNimNode(m)
  1309. if (not isImportedType(typ)) or tfCompleteStruct in typ.flags:
  1310. genObjectFields(m, typ, origType, typ.n, tmp, info)
  1311. m.s[cfsTypeInit3].addf("$1.node = &$2;$n", [tiNameForHcr(m, name), tmp])
  1312. var t = typ.baseClass
  1313. while t != nil:
  1314. t = t.skipTypes(skipPtrs)
  1315. t.flags.incl tfObjHasKids
  1316. t = t.baseClass
  1317. proc genTupleInfo(m: BModule; typ, origType: PType, name: Rope; info: TLineInfo) =
  1318. genTypeInfoAuxBase(m, typ, typ, name, rope("0"), info)
  1319. var expr = getNimNode(m)
  1320. if not typ.isEmptyTupleType:
  1321. var tmp = getTempName(m) & "_" & $typ.kidsLen
  1322. genTNimNodeArray(m, tmp, rope(typ.kidsLen))
  1323. for i, a in typ.ikids:
  1324. var tmp2 = getNimNode(m)
  1325. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(i), tmp2])
  1326. m.s[cfsTypeInit3].addf("$1.kind = 1;$n" &
  1327. "$1.offset = offsetof($2, Field$3);$n" &
  1328. "$1.typ = $4;$n" &
  1329. "$1.name = \"Field$3\";$n",
  1330. [tmp2, getTypeDesc(m, origType, dkVar), rope(i), genTypeInfoV1(m, a, info)])
  1331. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n",
  1332. [expr, rope(typ.kidsLen), tmp])
  1333. else:
  1334. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2;$n",
  1335. [expr, rope(typ.kidsLen)])
  1336. m.s[cfsTypeInit3].addf("$1.node = &$2;$n", [tiNameForHcr(m, name), expr])
  1337. proc genEnumInfo(m: BModule; typ: PType, name: Rope; info: TLineInfo) =
  1338. # Type information for enumerations is quite heavy, so we do some
  1339. # optimizations here: The ``typ`` field is never set, as it is redundant
  1340. # anyway. We generate a cstring array and a loop over it. Exceptional
  1341. # positions will be reset after the loop.
  1342. genTypeInfoAux(m, typ, typ, name, info)
  1343. var nodePtrs = getTempName(m) & "_" & $typ.n.len
  1344. genTNimNodeArray(m, nodePtrs, rope(typ.n.len))
  1345. var enumNames, specialCases: Rope = ""
  1346. var firstNimNode = m.typeNodes
  1347. var hasHoles = false
  1348. for i in 0..<typ.n.len:
  1349. assert(typ.n[i].kind == nkSym)
  1350. var field = typ.n[i].sym
  1351. var elemNode = getNimNode(m)
  1352. if field.ast == nil:
  1353. # no explicit string literal for the enum field, so use field.name:
  1354. enumNames.add(makeCString(field.name.s))
  1355. else:
  1356. enumNames.add(makeCString(field.ast.strVal))
  1357. if i < typ.n.len - 1: enumNames.add(", \L")
  1358. if field.position != i or tfEnumHasHoles in typ.flags:
  1359. specialCases.addf("$1.offset = $2;$n", [elemNode, rope(field.position)])
  1360. hasHoles = true
  1361. var enumArray = getTempName(m)
  1362. var counter = getTempName(m)
  1363. m.s[cfsTypeInit1].addf("NI $1;$n", [counter])
  1364. m.s[cfsTypeInit1].addf("static char* NIM_CONST $1[$2] = {$n$3};$n",
  1365. [enumArray, rope(typ.n.len), enumNames])
  1366. m.s[cfsTypeInit3].addf("for ($1 = 0; $1 < $2; $1++) {$n" &
  1367. "$3[$1+$4].kind = 1;$n" & "$3[$1+$4].offset = $1;$n" &
  1368. "$3[$1+$4].name = $5[$1];$n" & "$6[$1] = &$3[$1+$4];$n" & "}$n", [counter,
  1369. rope(typ.n.len), m.typeNodesName, rope(firstNimNode), enumArray, nodePtrs])
  1370. m.s[cfsTypeInit3].add(specialCases)
  1371. m.s[cfsTypeInit3].addf(
  1372. "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n",
  1373. [getNimNode(m), rope(typ.n.len), nodePtrs, tiNameForHcr(m, name)])
  1374. if hasHoles:
  1375. # 1 << 2 is {ntfEnumHole}
  1376. m.s[cfsTypeInit3].addf("$1.flags = 1<<2;$n", [tiNameForHcr(m, name)])
  1377. proc genSetInfo(m: BModule; typ: PType, name: Rope; info: TLineInfo) =
  1378. assert(typ.elementType != nil)
  1379. genTypeInfoAux(m, typ, typ, name, info)
  1380. var tmp = getNimNode(m)
  1381. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 0;$n$3.node = &$1;$n",
  1382. [tmp, rope(firstOrd(m.config, typ)), tiNameForHcr(m, name)])
  1383. proc genArrayInfo(m: BModule; typ: PType, name: Rope; info: TLineInfo) =
  1384. genTypeInfoAuxBase(m, typ, typ, name, genTypeInfoV1(m, typ.elementType, info), info)
  1385. proc fakeClosureType(m: BModule; owner: PSym): PType =
  1386. # we generate the same RTTI as for a tuple[pointer, ref tuple[]]
  1387. result = newType(tyTuple, m.idgen, owner)
  1388. result.rawAddSon(newType(tyPointer, m.idgen, owner))
  1389. var r = newType(tyRef, m.idgen, owner)
  1390. let obj = createObj(m.g.graph, m.idgen, owner, owner.info, final=false)
  1391. r.rawAddSon(obj)
  1392. result.rawAddSon(r)
  1393. include ccgtrav
  1394. proc genDeepCopyProc(m: BModule; s: PSym; result: Rope) =
  1395. genProc(m, s)
  1396. m.s[cfsTypeInit3].addf("$1.deepcopy =(void* (N_RAW_NIMCALL*)(void*))$2;$n",
  1397. [result, s.loc.snippet])
  1398. proc declareNimType(m: BModule; name: string; str: Rope, module: int) =
  1399. let nr = rope(name)
  1400. if m.hcrOn:
  1401. m.s[cfsStrData].addf("static $2* $1;$n", [str, nr])
  1402. m.s[cfsTypeInit1].addf("\t$1 = ($3*)hcrGetGlobal($2, \"$1\");$n",
  1403. [str, getModuleDllPath(m, module), nr])
  1404. else:
  1405. m.s[cfsStrData].addf("extern $2 $1;$n", [str, nr])
  1406. proc genTypeInfo2Name(m: BModule; t: PType): Rope =
  1407. var it = t
  1408. it = it.skipTypes(skipPtrs)
  1409. if it.sym != nil and tfFromGeneric notin it.flags:
  1410. var m = it.sym.owner
  1411. while m != nil and m.kind != skModule: m = m.owner
  1412. if m == nil or sfSystemModule in m.flags:
  1413. # produce short names for system types:
  1414. result = it.sym.name.s
  1415. else:
  1416. var p = m.owner
  1417. result = ""
  1418. if p != nil and p.kind == skPackage:
  1419. result.add p.name.s & "."
  1420. result.add m.name.s & "."
  1421. result.add it.sym.name.s
  1422. else:
  1423. result = $hashType(it, m.config)
  1424. result = makeCString(result)
  1425. proc isTrivialProc(g: ModuleGraph; s: PSym): bool {.inline.} = getBody(g, s).len == 0
  1426. proc generateRttiDestructor(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp;
  1427. info: TLineInfo; idgen: IdGenerator; theProc: PSym): PSym =
  1428. # the wrapper is roughly like:
  1429. # proc rttiDestroy(x: pointer) =
  1430. # `=destroy`(cast[ptr T](x)[])
  1431. let procname = getIdent(g.cache, "rttiDestroy")
  1432. result = newSym(skProc, procname, idgen, owner, info)
  1433. let dest = newSym(skParam, getIdent(g.cache, "dest"), idgen, result, info)
  1434. dest.typ = getSysType(g, info, tyPointer)
  1435. result.typ = newProcType(info, idgen, owner)
  1436. result.typ.addParam dest
  1437. var n = newNodeI(nkProcDef, info, bodyPos+1)
  1438. for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
  1439. n[namePos] = newSymNode(result)
  1440. n[paramsPos] = result.typ.n
  1441. let body = newNodeI(nkStmtList, info)
  1442. let castType = makePtrType(typ, idgen)
  1443. if theProc.typ.firstParamType.kind != tyVar:
  1444. body.add newTreeI(nkCall, info, newSymNode(theProc), newDeref(newTreeIT(
  1445. nkCast, info, castType, newNodeIT(nkType, info, castType),
  1446. newSymNode(dest)
  1447. ))
  1448. )
  1449. else:
  1450. let addrOf = newNodeIT(nkHiddenAddr, info, theProc.typ.firstParamType)
  1451. addrOf.add newDeref(newTreeIT(
  1452. nkCast, info, castType, newNodeIT(nkType, info, castType),
  1453. newSymNode(dest)
  1454. ))
  1455. body.add newTreeI(nkCall, info, newSymNode(theProc),
  1456. addrOf
  1457. )
  1458. n[bodyPos] = body
  1459. result.ast = n
  1460. incl result.flags, sfFromGeneric
  1461. incl result.flags, sfGeneratedOp
  1462. proc genHook(m: BModule; t: PType; info: TLineInfo; op: TTypeAttachedOp; result: var Rope) =
  1463. let theProc = getAttachedOp(m.g.graph, t, op)
  1464. if theProc != nil and not isTrivialProc(m.g.graph, theProc):
  1465. # the prototype of a destructor is ``=destroy(x: var T)`` and that of a
  1466. # finalizer is: ``proc (x: ref T) {.nimcall.}``. We need to check the calling
  1467. # convention at least:
  1468. if theProc.typ == nil or theProc.typ.callConv != ccNimCall:
  1469. localError(m.config, info,
  1470. theProc.name.s & " needs to have the 'nimcall' calling convention")
  1471. if op == attachedDestructor:
  1472. let wrapper = generateRttiDestructor(m.g.graph, t, theProc.owner, attachedDestructor,
  1473. theProc.info, m.idgen, theProc)
  1474. genProc(m, wrapper)
  1475. result.add wrapper.loc.snippet
  1476. else:
  1477. genProc(m, theProc)
  1478. result.add theProc.loc.snippet
  1479. when false:
  1480. if not canFormAcycle(m.g.graph, t) and op == attachedTrace:
  1481. echo "ayclic but has this =trace ", t, " ", theProc.ast
  1482. else:
  1483. when false:
  1484. if op == attachedTrace and m.config.selectedGC == gcOrc and
  1485. containsGarbageCollectedRef(t):
  1486. # unfortunately this check is wrong for an object type that only contains
  1487. # .cursor fields like 'Node' inside 'cycleleak'.
  1488. internalError(m.config, info, "no attached trace proc found")
  1489. result.add rope("NIM_NIL")
  1490. proc getObjDepth(t: PType): int16 =
  1491. var x = t
  1492. result = -1
  1493. while x != nil:
  1494. x = skipTypes(x, skipPtrs)
  1495. x = x[0]
  1496. inc(result)
  1497. proc genDisplayElem(d: MD5Digest): uint32 =
  1498. result = 0
  1499. for i in 0..3:
  1500. result += uint32(d[i])
  1501. result = result shl 8
  1502. proc genDisplay(m: BModule; t: PType, depth: int): Rope =
  1503. result = Rope"{"
  1504. var x = t
  1505. var seqs = newSeq[string](depth+1)
  1506. var i = 0
  1507. while x != nil:
  1508. x = skipTypes(x, skipPtrs)
  1509. seqs[i] = $genDisplayElem(MD5Digest(hashType(x, m.config)))
  1510. x = x[0]
  1511. inc i
  1512. for i in countdown(depth, 1):
  1513. result.add seqs[i] & ", "
  1514. result.add seqs[0]
  1515. result.add "}"
  1516. proc genVTable(seqs: seq[PSym]): string =
  1517. result = "{"
  1518. for i in 0..<seqs.len:
  1519. if i > 0: result.add ", "
  1520. result.add "(void *) " & seqs[i].loc.snippet
  1521. result.add "}"
  1522. proc genTypeInfoV2OldImpl(m: BModule; t, origType: PType, name: Rope; info: TLineInfo) =
  1523. cgsym(m, "TNimTypeV2")
  1524. m.s[cfsStrData].addf("N_LIB_PRIVATE TNimTypeV2 $1;$n", [name])
  1525. var flags = 0
  1526. if not canFormAcycle(m.g.graph, t): flags = flags or 1
  1527. var typeEntry = newRopeAppender()
  1528. addf(typeEntry, "$1.destructor = (void*)", [name])
  1529. genHook(m, t, info, attachedDestructor, typeEntry)
  1530. addf(typeEntry, "; $1.traceImpl = (void*)", [name])
  1531. genHook(m, t, info, attachedTrace, typeEntry)
  1532. let objDepth = if t.kind == tyObject: getObjDepth(t) else: -1
  1533. if t.kind in {tyObject, tyDistinct} and incompleteType(t):
  1534. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1535. typeToString(t))
  1536. if isDefined(m.config, "nimTypeNames"):
  1537. var typeName: Rope
  1538. if t.kind in {tyObject, tyDistinct}:
  1539. typeName = genTypeInfo2Name(m, t)
  1540. else:
  1541. typeName = rope("NIM_NIL")
  1542. addf(typeEntry, "; $1.name = $2", [name, typeName])
  1543. addf(typeEntry, "; $1.size = sizeof($2); $1.align = (NI16) NIM_ALIGNOF($2); $1.depth = $3; $1.flags = $4;",
  1544. [name, getTypeDesc(m, t), rope(objDepth), rope(flags)])
  1545. if objDepth >= 0:
  1546. let objDisplay = genDisplay(m, t, objDepth)
  1547. let objDisplayStore = getTempName(m)
  1548. m.s[cfsVars].addf("static $1 $2[$3] = $4;$n", [getTypeDesc(m, getSysType(m.g.graph, unknownLineInfo, tyUInt32), dkVar), objDisplayStore, rope(objDepth+1), objDisplay])
  1549. addf(typeEntry, "$1.display = $2;$n", [name, rope(objDisplayStore)])
  1550. let dispatchMethods = toSeq(getMethodsPerType(m.g.graph, t))
  1551. if dispatchMethods.len > 0:
  1552. let vTablePointerName = getTempName(m)
  1553. m.s[cfsVars].addf("static void* $1[$2] = $3;$n", [vTablePointerName, rope(dispatchMethods.len), genVTable(dispatchMethods)])
  1554. for i in dispatchMethods:
  1555. genProcPrototype(m, i)
  1556. addf(typeEntry, "$1.vTable = $2;$n", [name, vTablePointerName])
  1557. m.s[cfsTypeInit3].add typeEntry
  1558. if t.kind == tyObject and t.baseClass != nil and optEnableDeepCopy in m.config.globalOptions:
  1559. discard genTypeInfoV1(m, t, info)
  1560. proc genTypeInfoV2Impl(m: BModule; t, origType: PType, name: Rope; info: TLineInfo) =
  1561. cgsym(m, "TNimTypeV2")
  1562. m.s[cfsStrData].addf("N_LIB_PRIVATE TNimTypeV2 $1;$n", [name])
  1563. var flags = 0
  1564. if not canFormAcycle(m.g.graph, t): flags = flags or 1
  1565. var typeEntry = newRopeAppender()
  1566. addf(typeEntry, "N_LIB_PRIVATE TNimTypeV2 $1 = {", [name])
  1567. add(typeEntry, ".destructor = (void*)")
  1568. genHook(m, t, info, attachedDestructor, typeEntry)
  1569. let objDepth = if t.kind == tyObject: getObjDepth(t) else: -1
  1570. if t.kind in {tyObject, tyDistinct} and incompleteType(t):
  1571. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1572. typeToString(t))
  1573. addf(typeEntry, ", .size = sizeof($1), .align = (NI16) NIM_ALIGNOF($1), .depth = $2",
  1574. [getTypeDesc(m, t), rope(objDepth)])
  1575. if objDepth >= 0:
  1576. let objDisplay = genDisplay(m, t, objDepth)
  1577. let objDisplayStore = getTempName(m)
  1578. 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])
  1579. addf(typeEntry, ", .display = $1", [rope(objDisplayStore)])
  1580. if isDefined(m.config, "nimTypeNames"):
  1581. var typeName: Rope
  1582. if t.kind in {tyObject, tyDistinct}:
  1583. typeName = genTypeInfo2Name(m, t)
  1584. else:
  1585. typeName = rope("NIM_NIL")
  1586. addf(typeEntry, ", .name = $1", [typeName])
  1587. add(typeEntry, ", .traceImpl = (void*)")
  1588. genHook(m, t, info, attachedTrace, typeEntry)
  1589. let dispatchMethods = toSeq(getMethodsPerType(m.g.graph, t))
  1590. if dispatchMethods.len > 0:
  1591. addf(typeEntry, ", .flags = $1", [rope(flags)])
  1592. for i in dispatchMethods:
  1593. genProcPrototype(m, i)
  1594. addf(typeEntry, ", .vTable = $1};$n", [genVTable(dispatchMethods)])
  1595. m.s[cfsVars].add typeEntry
  1596. else:
  1597. addf(typeEntry, ", .flags = $1};$n", [rope(flags)])
  1598. m.s[cfsVars].add typeEntry
  1599. if t.kind == tyObject and t.baseClass != nil and optEnableDeepCopy in m.config.globalOptions:
  1600. discard genTypeInfoV1(m, t, info)
  1601. proc genTypeInfoV2(m: BModule; t: PType; info: TLineInfo): Rope =
  1602. let origType = t
  1603. # distinct types can have their own destructors
  1604. var t = skipTypes(origType, irrelevantForBackend + tyUserTypeClasses - {tyDistinct})
  1605. let prefixTI = if m.hcrOn: "(" else: "(&"
  1606. let sig = hashType(origType, m.config)
  1607. result = m.typeInfoMarkerV2.getOrDefault(sig)
  1608. if result != "":
  1609. return prefixTI.rope & result & ")".rope
  1610. let marker = m.g.typeInfoMarkerV2.getOrDefault(sig)
  1611. if marker.str != "":
  1612. cgsym(m, "TNimTypeV2")
  1613. declareNimType(m, "TNimTypeV2", marker.str, marker.owner)
  1614. # also store in local type section:
  1615. m.typeInfoMarkerV2[sig] = marker.str
  1616. return prefixTI.rope & marker.str & ")".rope
  1617. result = "NTIv2$1_" % [rope($sig)]
  1618. m.typeInfoMarkerV2[sig] = result
  1619. let owner = t.skipTypes(typedescPtrs).itemId.module
  1620. if owner != m.module.position and moduleOpenForCodegen(m.g.graph, FileIndex owner):
  1621. # make sure the type info is created in the owner module
  1622. discard genTypeInfoV2(m.g.modules[owner], origType, info)
  1623. # reference the type info as extern here
  1624. cgsym(m, "TNimTypeV2")
  1625. declareNimType(m, "TNimTypeV2", result, owner)
  1626. return prefixTI.rope & result & ")".rope
  1627. m.g.typeInfoMarkerV2[sig] = (str: result, owner: owner)
  1628. if m.compileToCpp or m.hcrOn:
  1629. genTypeInfoV2OldImpl(m, t, origType, result, info)
  1630. else:
  1631. genTypeInfoV2Impl(m, t, origType, result, info)
  1632. result = prefixTI.rope & result & ")".rope
  1633. proc openArrayToTuple(m: BModule; t: PType): PType =
  1634. result = newType(tyTuple, m.idgen, t.owner)
  1635. let p = newType(tyPtr, m.idgen, t.owner)
  1636. let a = newType(tyUncheckedArray, m.idgen, t.owner)
  1637. a.add t.elementType
  1638. p.add a
  1639. result.add p
  1640. result.add getSysType(m.g.graph, t.owner.info, tyInt)
  1641. proc typeToC(t: PType): string =
  1642. ## Just for more readable names, the result doesn't have
  1643. ## to be unique.
  1644. let s = typeToString(t)
  1645. result = newStringOfCap(s.len)
  1646. for c in s:
  1647. case c
  1648. of 'a'..'z':
  1649. result.add c
  1650. of 'A'..'Z':
  1651. result.add toLowerAscii(c)
  1652. of ' ':
  1653. discard
  1654. of ',':
  1655. result.add '_'
  1656. of '.':
  1657. result.add 'O'
  1658. of '[', '(', '{':
  1659. result.add 'L'
  1660. of ']', ')', '}':
  1661. result.add 'T'
  1662. else:
  1663. # We mangle upper letters and digits too so that there cannot
  1664. # be clashes with our special meanings
  1665. result.addInt ord(c)
  1666. proc genTypeInfoV1(m: BModule; t: PType; info: TLineInfo): Rope =
  1667. let origType = t
  1668. var t = skipTypes(origType, irrelevantForBackend + tyUserTypeClasses)
  1669. let prefixTI = if m.hcrOn: "(" else: "(&"
  1670. let sig = hashType(origType, m.config)
  1671. result = m.typeInfoMarker.getOrDefault(sig)
  1672. if result != "":
  1673. return prefixTI.rope & result & ")".rope
  1674. let marker = m.g.typeInfoMarker.getOrDefault(sig)
  1675. if marker.str != "":
  1676. cgsym(m, "TNimType")
  1677. cgsym(m, "TNimNode")
  1678. declareNimType(m, "TNimType", marker.str, marker.owner)
  1679. # also store in local type section:
  1680. m.typeInfoMarker[sig] = marker.str
  1681. return prefixTI.rope & marker.str & ")".rope
  1682. result = "NTI$1$2_" % [rope(typeToC(t)), rope($sig)]
  1683. m.typeInfoMarker[sig] = result
  1684. let old = m.g.graph.emittedTypeInfo.getOrDefault($result)
  1685. if old != FileIndex(0):
  1686. cgsym(m, "TNimType")
  1687. cgsym(m, "TNimNode")
  1688. declareNimType(m, "TNimType", result, old.int)
  1689. return prefixTI.rope & result & ")".rope
  1690. var owner = t.skipTypes(typedescPtrs).itemId.module
  1691. if owner != m.module.position and moduleOpenForCodegen(m.g.graph, FileIndex owner):
  1692. # make sure the type info is created in the owner module
  1693. discard genTypeInfoV1(m.g.modules[owner], origType, info)
  1694. # reference the type info as extern here
  1695. cgsym(m, "TNimType")
  1696. cgsym(m, "TNimNode")
  1697. declareNimType(m, "TNimType", result, owner)
  1698. return prefixTI.rope & result & ")".rope
  1699. else:
  1700. owner = m.module.position.int32
  1701. m.g.typeInfoMarker[sig] = (str: result, owner: owner)
  1702. rememberEmittedTypeInfo(m.g.graph, FileIndex(owner), $result)
  1703. case t.kind
  1704. of tyEmpty, tyVoid: result = rope"0"
  1705. of tyPointer, tyBool, tyChar, tyCstring, tyString, tyInt..tyUInt64, tyVar, tyLent:
  1706. genTypeInfoAuxBase(m, t, t, result, rope"0", info)
  1707. of tyStatic:
  1708. if t.n != nil: result = genTypeInfoV1(m, skipModifier t, info)
  1709. else: internalError(m.config, "genTypeInfoV1(" & $t.kind & ')')
  1710. of tyUserTypeClasses:
  1711. internalAssert m.config, t.isResolvedUserTypeClass
  1712. return genTypeInfoV1(m, t.skipModifier, info)
  1713. of tyProc:
  1714. if t.callConv != ccClosure:
  1715. genTypeInfoAuxBase(m, t, t, result, rope"0", info)
  1716. else:
  1717. let x = fakeClosureType(m, t.owner)
  1718. genTupleInfo(m, x, x, result, info)
  1719. of tySequence:
  1720. genTypeInfoAux(m, t, t, result, info)
  1721. if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcGo}:
  1722. let markerProc = genTraverseProc(m, origType, sig)
  1723. m.s[cfsTypeInit3].addf("$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
  1724. of tyRef:
  1725. genTypeInfoAux(m, t, t, result, info)
  1726. if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcGo}:
  1727. let markerProc = genTraverseProc(m, origType, sig)
  1728. m.s[cfsTypeInit3].addf("$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
  1729. of tyPtr, tyRange, tyUncheckedArray: genTypeInfoAux(m, t, t, result, info)
  1730. of tyArray: genArrayInfo(m, t, result, info)
  1731. of tySet: genSetInfo(m, t, result, info)
  1732. of tyEnum: genEnumInfo(m, t, result, info)
  1733. of tyObject:
  1734. genObjectInfo(m, t, origType, result, info)
  1735. of tyTuple:
  1736. # if t.n != nil: genObjectInfo(m, t, result)
  1737. # else:
  1738. # BUGFIX: use consistently RTTI without proper field names; otherwise
  1739. # results are not deterministic!
  1740. genTupleInfo(m, t, origType, result, info)
  1741. of tyOpenArray:
  1742. let x = openArrayToTuple(m, t)
  1743. genTupleInfo(m, x, origType, result, info)
  1744. else: internalError(m.config, "genTypeInfoV1(" & $t.kind & ')')
  1745. var op = getAttachedOp(m.g.graph, t, attachedDeepCopy)
  1746. if op == nil:
  1747. op = getAttachedOp(m.g.graph, origType, attachedDeepCopy)
  1748. if op != nil:
  1749. genDeepCopyProc(m, op, result)
  1750. if optTinyRtti in m.config.globalOptions and t.kind == tyObject and sfImportc notin t.sym.flags:
  1751. let v2info = genTypeInfoV2(m, origType, info)
  1752. addf(m.s[cfsTypeInit3], "$1->typeInfoV1 = (void*)&$2; $2.typeInfoV2 = (void*)$1;$n", [
  1753. v2info, result])
  1754. result = prefixTI.rope & result & ")".rope
  1755. proc genTypeInfo*(config: ConfigRef, m: BModule; t: PType; info: TLineInfo): Rope =
  1756. if optTinyRtti in config.globalOptions:
  1757. result = genTypeInfoV2(m, t, info)
  1758. else:
  1759. result = genTypeInfoV1(m, t, info)
  1760. proc genTypeSection(m: BModule, n: PNode) =
  1761. var intSet = initIntSet()
  1762. for i in 0..<n.len:
  1763. if len(n[i]) == 0: continue
  1764. if n[i][0].kind != nkPragmaExpr: continue
  1765. for p in 0..<n[i][0].len:
  1766. if (n[i][0][p].kind notin {nkSym, nkPostfix}): continue
  1767. var s = n[i][0][p]
  1768. if s.kind == nkPostfix:
  1769. s = n[i][0][p][1]
  1770. if {sfExportc, sfCompilerProc} * s.sym.flags == {sfExportc}:
  1771. discard getTypeDescAux(m, s.typ, intSet, descKindFromSymKind(s.sym.kind))
  1772. if m.g.generatedHeader != nil:
  1773. discard getTypeDescAux(m.g.generatedHeader, s.typ, intSet, descKindFromSymKind(s.sym.kind))