ccgtypes.nim 77 KB

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