ccgtypes.nim 80 KB

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