ccgtypes.nim 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054
  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. NimInt, NimInt8, NimInt16, NimInt32, NimInt64,
  285. NimFloat, NimFloat32, NimFloat64, NimFloat128,
  286. NimUint, NimUint8, NimUint16, NimUint32, NimUint64]
  287. case typ.kind
  288. of tyPointer:
  289. result = typeNameOrLiteral(m, typ, CPointer)
  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, NimCstring)
  300. of tyBool: result = typeNameOrLiteral(m, typ, NimBool)
  301. of tyChar: result = typeNameOrLiteral(m, typ, NimChar)
  302. of tyNil: result = typeNameOrLiteral(m, typ, CPointer)
  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 = CVoid
  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 = NimInt)
  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 = NimInt)
  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 = CVoid
  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 = CVoid
  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 = NimInt)
  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 = CPointer)
  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 = NimInt)
  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(NimInt32)
  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(NimUint8)
  843. of 2:
  844. m.s[cfsTypes].addTypedef(name = result):
  845. m.s[cfsTypes].add(NimUint16)
  846. of 4:
  847. m.s[cfsTypes].addTypedef(name = result):
  848. m.s[cfsTypes].add(NimInt32)
  849. of 8:
  850. m.s[cfsTypes].addTypedef(name = result):
  851. m.s[cfsTypes].add(NimInt64)
  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 = CPointer)
  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(CVoid)
  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(cUintType(s*8))
  993. else:
  994. m.s[cfsTypes].addArrayTypedef(name = result, len = s):
  995. m.s[cfsTypes].add(NimUint8)
  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 = CPointer)
  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 = CPointer
  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(CNil)
  1203. m.hcrCreateTypeInfosProc.addArgument(registerHcr):
  1204. m.hcrCreateTypeInfosProc.addCast(typ = ptrType(CPointer)):
  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, result: var Builder) =
  1232. cgsym(m, "TNimNode")
  1233. var tmp = discriminatorTableName(m, objtype, d)
  1234. result.addArrayVar(kind = Local,
  1235. name = tmp,
  1236. elementType = ptrType("TNimNode"),
  1237. len = toInt(lengthOrd(m.config, d.typ)) + 1)
  1238. proc genTNimNodeArray(m: BModule; name: Rope, size: int) =
  1239. if m.hcrOn:
  1240. m.s[cfsData].addVar(kind = Global, name = name, typ = ptrType(ptrType("TNimNode")))
  1241. var registerHcr: CallBuilder
  1242. m.hcrCreateTypeInfosProc.addStmt():
  1243. m.hcrCreateTypeInfosProc.addCall(registerHcr, callee = "hcrRegisterGlobal"):
  1244. m.hcrCreateTypeInfosProc.addArgument(registerHcr):
  1245. m.hcrCreateTypeInfosProc.add(getModuleDllPath(m, m.module))
  1246. m.hcrCreateTypeInfosProc.addArgument(registerHcr):
  1247. m.hcrCreateTypeInfosProc.add(makeCString(name))
  1248. m.hcrCreateTypeInfosProc.addArgument(registerHcr):
  1249. m.hcrCreateTypeInfosProc.addOp(Mul, NimInt, cSizeof(ptrType("TNimNode")), cIntValue(size))
  1250. m.hcrCreateTypeInfosProc.addArgument(registerHcr):
  1251. m.hcrCreateTypeInfosProc.add(CNil)
  1252. m.hcrCreateTypeInfosProc.addArgument(registerHcr):
  1253. m.hcrCreateTypeInfosProc.addCast(typ = ptrType(CPointer)):
  1254. m.hcrCreateTypeInfosProc.add(cAddr(name))
  1255. else:
  1256. m.s[cfsTypeInit1].addArrayVar(kind = Global, name = name,
  1257. elementType = ptrType("TNimNode"), len = size)
  1258. proc genObjectFields(m: BModule; typ, origType: PType, n: PNode, expr: Rope;
  1259. info: TLineInfo) =
  1260. case n.kind
  1261. of nkRecList:
  1262. if n.len == 1:
  1263. genObjectFields(m, typ, origType, n[0], expr, info)
  1264. elif n.len > 0:
  1265. var tmp = getTempName(m) & "_" & $n.len
  1266. genTNimNodeArray(m, tmp, n.len)
  1267. for i in 0..<n.len:
  1268. var tmp2 = getNimNode(m)
  1269. m.s[cfsTypeInit3].addSubscriptAssignment(tmp, cIntValue(i), cAddr(tmp2))
  1270. genObjectFields(m, typ, origType, n[i], tmp2, info)
  1271. m.s[cfsTypeInit3].addFieldAssignment(expr, "len", n.len)
  1272. m.s[cfsTypeInit3].addFieldAssignment(expr, "kind", 2)
  1273. m.s[cfsTypeInit3].addFieldAssignment(expr, "sons",
  1274. cAddr(subscript(tmp, cIntValue(0))))
  1275. else:
  1276. m.s[cfsTypeInit3].addFieldAssignment(expr, "len", n.len)
  1277. m.s[cfsTypeInit3].addFieldAssignment(expr, "kind", 2)
  1278. of nkRecCase:
  1279. assert(n[0].kind == nkSym)
  1280. var field = n[0].sym
  1281. var tmp = discriminatorTableName(m, typ, field)
  1282. var L = lengthOrd(m.config, field.typ)
  1283. assert L > 0
  1284. if field.loc.snippet == "": fillObjectFields(m, typ)
  1285. if field.loc.t == nil:
  1286. internalError(m.config, n.info, "genObjectFields")
  1287. let fieldTypInfo = genTypeInfoV1(m, field.typ, info)
  1288. m.s[cfsTypeInit3].addFieldAssignment(expr, "kind", 3)
  1289. m.s[cfsTypeInit3].addFieldAssignmentWithValue(expr, "offset"):
  1290. m.s[cfsTypeInit3].addOffsetof(getTypeDesc(m, origType, dkVar), field.loc.snippet)
  1291. m.s[cfsTypeInit3].addFieldAssignment(expr, "typ", fieldTypInfo)
  1292. m.s[cfsTypeInit3].addFieldAssignment(expr, "name", makeCString(field.name.s))
  1293. m.s[cfsTypeInit3].addFieldAssignment(expr, "sons", cAddr(subscript(tmp, cIntValue(0))))
  1294. m.s[cfsTypeInit3].addFieldAssignment(expr, "len", L)
  1295. m.s[cfsData].addArrayVar(kind = Local, name = tmp,
  1296. elementType = ptrType("TNimNode"), len = toInt(L)+1)
  1297. for i in 1..<n.len:
  1298. var b = n[i] # branch
  1299. var tmp2 = getNimNode(m)
  1300. genObjectFields(m, typ, origType, lastSon(b), tmp2, info)
  1301. case b.kind
  1302. of nkOfBranch:
  1303. if b.len < 2:
  1304. internalError(m.config, b.info, "genObjectFields; nkOfBranch broken")
  1305. for j in 0..<b.len - 1:
  1306. if b[j].kind == nkRange:
  1307. var x = toInt(getOrdValue(b[j][0]))
  1308. var y = toInt(getOrdValue(b[j][1]))
  1309. while x <= y:
  1310. m.s[cfsTypeInit3].addSubscriptAssignment(tmp, cIntValue(x), cAddr(tmp2))
  1311. inc(x)
  1312. else:
  1313. m.s[cfsTypeInit3].addSubscriptAssignment(tmp, cIntValue(getOrdValue(b[j])), cAddr(tmp2))
  1314. of nkElse:
  1315. m.s[cfsTypeInit3].addSubscriptAssignment(tmp, cIntValue(L), cAddr(tmp2))
  1316. else: internalError(m.config, n.info, "genObjectFields(nkRecCase)")
  1317. of nkSym:
  1318. var field = n.sym
  1319. # Do not produce code for void types
  1320. if isEmptyType(field.typ): return
  1321. if field.bitsize == 0:
  1322. if field.loc.snippet == "": fillObjectFields(m, typ)
  1323. if field.loc.t == nil:
  1324. internalError(m.config, n.info, "genObjectFields")
  1325. let fieldTypInfo = genTypeInfoV1(m, field.typ, info)
  1326. m.s[cfsTypeInit3].addFieldAssignment(expr, "kind", 1)
  1327. m.s[cfsTypeInit3].addFieldAssignmentWithValue(expr, "offset"):
  1328. m.s[cfsTypeInit3].addOffsetof(getTypeDesc(m, origType, dkVar), field.loc.snippet)
  1329. m.s[cfsTypeInit3].addFieldAssignment(expr, "typ", fieldTypInfo)
  1330. m.s[cfsTypeInit3].addFieldAssignment(expr, "name", makeCString(field.name.s))
  1331. else: internalError(m.config, n.info, "genObjectFields")
  1332. proc genObjectInfo(m: BModule; typ, origType: PType, name: Rope; info: TLineInfo) =
  1333. assert typ.kind == tyObject
  1334. if incompleteType(typ):
  1335. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1336. typeToString(typ))
  1337. genTypeInfoAux(m, typ, origType, name, info)
  1338. var tmp = getNimNode(m)
  1339. if (not isImportedType(typ)) or tfCompleteStruct in typ.flags:
  1340. genObjectFields(m, typ, origType, typ.n, tmp, info)
  1341. m.s[cfsTypeInit3].addFieldAssignment(tiNameForHcr(m, name), "node", cAddr(tmp))
  1342. var t = typ.baseClass
  1343. while t != nil:
  1344. t = t.skipTypes(skipPtrs)
  1345. t.flags.incl tfObjHasKids
  1346. t = t.baseClass
  1347. proc genTupleInfo(m: BModule; typ, origType: PType, name: Rope; info: TLineInfo) =
  1348. genTypeInfoAuxBase(m, typ, typ, name, cIntValue(0), info)
  1349. var expr = getNimNode(m)
  1350. if not typ.isEmptyTupleType:
  1351. var tmp = getTempName(m) & "_" & $typ.kidsLen
  1352. genTNimNodeArray(m, tmp, typ.kidsLen)
  1353. for i, a in typ.ikids:
  1354. var tmp2 = getNimNode(m)
  1355. let fieldTypInfo = genTypeInfoV1(m, a, info)
  1356. m.s[cfsTypeInit3].addSubscriptAssignment(tmp, cIntValue(i), cAddr(tmp2))
  1357. m.s[cfsTypeInit3].addFieldAssignment(tmp2, "kind", 1)
  1358. m.s[cfsTypeInit3].addFieldAssignmentWithValue(tmp2, "offset"):
  1359. m.s[cfsTypeInit3].addOffsetof(getTypeDesc(m, origType, dkVar), "Field" & $i)
  1360. m.s[cfsTypeInit3].addFieldAssignment(tmp2, "typ", fieldTypInfo)
  1361. m.s[cfsTypeInit3].addFieldAssignment(tmp2, "name", "\"Field" & $i & "\"")
  1362. m.s[cfsTypeInit3].addFieldAssignment(expr, "len", typ.kidsLen)
  1363. m.s[cfsTypeInit3].addFieldAssignment(expr, "kind", 2)
  1364. m.s[cfsTypeInit3].addFieldAssignment(expr, "sons",
  1365. cAddr(subscript(tmp, cIntValue(0))))
  1366. else:
  1367. m.s[cfsTypeInit3].addFieldAssignment(expr, "len", typ.kidsLen)
  1368. m.s[cfsTypeInit3].addFieldAssignment(expr, "kind", 2)
  1369. m.s[cfsTypeInit3].addFieldAssignment(tiNameForHcr(m, name), "node", cAddr(expr))
  1370. proc genEnumInfo(m: BModule; typ: PType, name: Rope; info: TLineInfo) =
  1371. # Type information for enumerations is quite heavy, so we do some
  1372. # optimizations here: The ``typ`` field is never set, as it is redundant
  1373. # anyway. We generate a cstring array and a loop over it. Exceptional
  1374. # positions will be reset after the loop.
  1375. genTypeInfoAux(m, typ, typ, name, info)
  1376. var nodePtrs = getTempName(m) & "_" & $typ.n.len
  1377. genTNimNodeArray(m, nodePtrs, typ.n.len)
  1378. var enumNames = newBuilder("")
  1379. var enumNamesInit: StructInitializer
  1380. var specialCases = newBuilder("")
  1381. var firstNimNode = m.typeNodes
  1382. var hasHoles = false
  1383. enumNames.addStructInitializer(enumNamesInit, kind = siArray):
  1384. for i in 0..<typ.n.len:
  1385. assert(typ.n[i].kind == nkSym)
  1386. var field = typ.n[i].sym
  1387. var elemNode = getNimNode(m)
  1388. enumNames.addField(enumNamesInit, name = ""):
  1389. if field.ast == nil:
  1390. # no explicit string literal for the enum field, so use field.name:
  1391. enumNames.add(makeCString(field.name.s))
  1392. else:
  1393. enumNames.add(makeCString(field.ast.strVal))
  1394. if field.position != i or tfEnumHasHoles in typ.flags:
  1395. specialCases.addFieldAssignment(elemNode, "offset", field.position)
  1396. hasHoles = true
  1397. var enumArray = getTempName(m)
  1398. var counter = getTempName(m)
  1399. m.s[cfsTypeInit1].addVar(kind = Local, name = counter, typ = NimInt)
  1400. m.s[cfsTypeInit1].addArrayVarWithInitializer(
  1401. kind = Global,
  1402. name = enumArray,
  1403. elementType = constPtrType(CChar),
  1404. len = typ.n.len):
  1405. m.s[cfsTypeInit1].add(extract(enumNames))
  1406. m.s[cfsTypeInit3].addForRangeExclusive(i = counter,
  1407. start = cIntValue(0),
  1408. bound = cIntValue(typ.n.len)):
  1409. let nodeLoc = subscript(m.typeNodesName,
  1410. cOp(Add, NimInt, counter, cIntValue(firstNimNode)))
  1411. m.s[cfsTypeInit3].addFieldAssignment(nodeLoc, "kind", cIntValue(1))
  1412. m.s[cfsTypeInit3].addFieldAssignment(nodeLoc, "offset", counter)
  1413. m.s[cfsTypeInit3].addFieldAssignment(nodeLoc, "name",
  1414. subscript(enumArray, counter))
  1415. m.s[cfsTypeInit3].addSubscriptAssignment(nodePtrs, counter,
  1416. cAddr(nodeLoc))
  1417. m.s[cfsTypeInit3].add(extract(specialCases))
  1418. let n = getNimNode(m)
  1419. m.s[cfsTypeInit3].addFieldAssignment(n, "len", typ.n.len)
  1420. m.s[cfsTypeInit3].addFieldAssignment(n, "kind", 0)
  1421. m.s[cfsTypeInit3].addFieldAssignment(n, "sons",
  1422. cAddr(subscript(nodePtrs, cIntValue(0))))
  1423. m.s[cfsTypeInit3].addFieldAssignment(tiNameForHcr(m, name), "node", cAddr(n))
  1424. if hasHoles:
  1425. m.s[cfsTypeInit3].addFieldAssignment(tiNameForHcr(m, name), "flags",
  1426. # 1 << 2 is {ntfEnumHole}
  1427. cOp(Shl, NimUint8, cIntValue(1), cIntValue(2)))
  1428. proc genSetInfo(m: BModule; typ: PType, name: Rope; info: TLineInfo) =
  1429. assert(typ.elementType != nil)
  1430. genTypeInfoAux(m, typ, typ, name, info)
  1431. var tmp = getNimNode(m)
  1432. m.s[cfsTypeInit3].addFieldAssignment(tmp, "len", firstOrd(m.config, typ))
  1433. m.s[cfsTypeInit3].addFieldAssignment(tmp, "kind", 0)
  1434. m.s[cfsTypeInit3].addFieldAssignment(tiNameForHcr(m, name), "node", cAddr(tmp))
  1435. proc genArrayInfo(m: BModule; typ: PType, name: Rope; info: TLineInfo) =
  1436. genTypeInfoAuxBase(m, typ, typ, name, genTypeInfoV1(m, typ.elementType, info), info)
  1437. proc fakeClosureType(m: BModule; owner: PSym): PType =
  1438. # we generate the same RTTI as for a tuple[pointer, ref tuple[]]
  1439. result = newType(tyTuple, m.idgen, owner)
  1440. result.rawAddSon(newType(tyPointer, m.idgen, owner))
  1441. var r = newType(tyRef, m.idgen, owner)
  1442. let obj = createObj(m.g.graph, m.idgen, owner, owner.info, final=false)
  1443. r.rawAddSon(obj)
  1444. result.rawAddSon(r)
  1445. include ccgtrav
  1446. proc genDeepCopyProc(m: BModule; s: PSym; result: Rope) =
  1447. genProc(m, s)
  1448. var desc = newBuilder("")
  1449. var paramBuilder: ProcParamBuilder
  1450. desc.addProcParams(paramBuilder):
  1451. desc.addUnnamedParam(paramBuilder, typ = CPointer)
  1452. let params = extract(desc)
  1453. let pt = procPtrTypeUnnamedNimCall(rettype = CPointer, params = params)
  1454. m.s[cfsTypeInit3].addFieldAssignmentWithValue(result, "deepcopy"):
  1455. m.s[cfsTypeInit3].add(cCast(pt, s.loc.snippet))
  1456. proc declareNimType(m: BModule; name: string; str: Rope, module: int) =
  1457. let nr = rope(name)
  1458. if m.hcrOn:
  1459. m.s[cfsStrData].addVar(kind = Global, name = str, typ = ptrType(nr))
  1460. m.s[cfsTypeInit1].add('\t')
  1461. m.s[cfsTypeInit1].addAssignmentWithValue(str):
  1462. m.s[cfsTypeInit1].addCast(typ = ptrType(nr)):
  1463. var hcrGlobal: CallBuilder
  1464. m.s[cfsTypeInit1].addCall(hcrGlobal, "hcrGetGlobal"):
  1465. m.s[cfsTypeInit1].addArgument(hcrGlobal):
  1466. m.s[cfsTypeInit1].add(getModuleDllPath(m, module))
  1467. m.s[cfsTypeInit1].addArgument(hcrGlobal):
  1468. m.s[cfsTypeInit1].add("\"" & str & "\"")
  1469. else:
  1470. m.s[cfsStrData].addDeclWithVisibility(Extern):
  1471. m.s[cfsStrData].addVar(kind = Local, name = str, typ = nr)
  1472. proc genTypeInfo2Name(m: BModule; t: PType): Rope =
  1473. var it = t
  1474. it = it.skipTypes(skipPtrs)
  1475. if it.sym != nil and tfFromGeneric notin it.flags:
  1476. var m = it.sym.owner
  1477. while m != nil and m.kind != skModule: m = m.owner
  1478. if m == nil or sfSystemModule in m.flags:
  1479. # produce short names for system types:
  1480. result = it.sym.name.s
  1481. else:
  1482. var p = m.owner
  1483. result = ""
  1484. if p != nil and p.kind == skPackage:
  1485. result.add p.name.s & "."
  1486. result.add m.name.s & "."
  1487. result.add it.sym.name.s
  1488. else:
  1489. result = $hashType(it, m.config)
  1490. result = makeCString(result)
  1491. proc isTrivialProc(g: ModuleGraph; s: PSym): bool {.inline.} = getBody(g, s).len == 0
  1492. proc generateRttiDestructor(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp;
  1493. info: TLineInfo; idgen: IdGenerator; theProc: PSym): PSym =
  1494. # the wrapper is roughly like:
  1495. # proc rttiDestroy(x: pointer) =
  1496. # `=destroy`(cast[ptr T](x)[])
  1497. let procname = getIdent(g.cache, "rttiDestroy")
  1498. result = newSym(skProc, procname, idgen, owner, info)
  1499. let dest = newSym(skParam, getIdent(g.cache, "dest"), idgen, result, info)
  1500. dest.typ = getSysType(g, info, tyPointer)
  1501. result.typ = newProcType(info, idgen, owner)
  1502. result.typ.addParam dest
  1503. var n = newNodeI(nkProcDef, info, bodyPos+1)
  1504. for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
  1505. n[namePos] = newSymNode(result)
  1506. n[paramsPos] = result.typ.n
  1507. let body = newNodeI(nkStmtList, info)
  1508. let castType = makePtrType(typ, idgen)
  1509. if theProc.typ.firstParamType.kind != tyVar:
  1510. body.add newTreeI(nkCall, info, newSymNode(theProc), newDeref(newTreeIT(
  1511. nkCast, info, castType, newNodeIT(nkType, info, castType),
  1512. newSymNode(dest)
  1513. ))
  1514. )
  1515. else:
  1516. let addrOf = newNodeIT(nkHiddenAddr, info, theProc.typ.firstParamType)
  1517. addrOf.add newDeref(newTreeIT(
  1518. nkCast, info, castType, newNodeIT(nkType, info, castType),
  1519. newSymNode(dest)
  1520. ))
  1521. body.add newTreeI(nkCall, info, newSymNode(theProc),
  1522. addrOf
  1523. )
  1524. n[bodyPos] = body
  1525. result.ast = n
  1526. incl result.flags, sfFromGeneric
  1527. incl result.flags, sfGeneratedOp
  1528. proc genHook(m: BModule; t: PType; info: TLineInfo; op: TTypeAttachedOp; result: var Builder) =
  1529. let theProc = getAttachedOp(m.g.graph, t, op)
  1530. if theProc != nil and not isTrivialProc(m.g.graph, theProc):
  1531. # the prototype of a destructor is ``=destroy(x: var T)`` and that of a
  1532. # finalizer is: ``proc (x: ref T) {.nimcall.}``. We need to check the calling
  1533. # convention at least:
  1534. if theProc.typ == nil or theProc.typ.callConv != ccNimCall:
  1535. localError(m.config, info,
  1536. theProc.name.s & " needs to have the 'nimcall' calling convention")
  1537. if op == attachedDestructor:
  1538. let wrapper = generateRttiDestructor(m.g.graph, t, theProc.owner, attachedDestructor,
  1539. theProc.info, m.idgen, theProc)
  1540. genProc(m, wrapper)
  1541. result.add wrapper.loc.snippet
  1542. else:
  1543. genProc(m, theProc)
  1544. result.add theProc.loc.snippet
  1545. when false:
  1546. if not canFormAcycle(m.g.graph, t) and op == attachedTrace:
  1547. echo "ayclic but has this =trace ", t, " ", theProc.ast
  1548. else:
  1549. when false:
  1550. if op == attachedTrace and m.config.selectedGC == gcOrc and
  1551. containsGarbageCollectedRef(t):
  1552. # unfortunately this check is wrong for an object type that only contains
  1553. # .cursor fields like 'Node' inside 'cycleleak'.
  1554. internalError(m.config, info, "no attached trace proc found")
  1555. result.add NimNil
  1556. proc getObjDepth(t: PType): int16 =
  1557. var x = t
  1558. result = -1
  1559. while x != nil:
  1560. x = skipTypes(x, skipPtrs)
  1561. x = x[0]
  1562. inc(result)
  1563. proc genDisplayElem(d: MD5Digest): uint32 =
  1564. result = 0
  1565. for i in 0..3:
  1566. result += uint32(d[i])
  1567. result = result shl 8
  1568. proc genDisplay(result: var Builder, m: BModule; t: PType, depth: int) =
  1569. var x = t
  1570. var seqs = newSeq[Snippet](depth+1)
  1571. var i = 0
  1572. while x != nil:
  1573. x = skipTypes(x, skipPtrs)
  1574. seqs[i] = cIntValue(genDisplayElem(MD5Digest(hashType(x, m.config))))
  1575. x = x[0]
  1576. inc i
  1577. var arr: StructInitializer
  1578. result.addStructInitializer(arr, siArray):
  1579. for i in countdown(depth, 1):
  1580. result.addField(arr, ""):
  1581. result.add(seqs[i])
  1582. result.addField(arr, ""):
  1583. result.add(seqs[0])
  1584. proc genVTable(result: var Builder, seqs: seq[PSym]) =
  1585. var table: StructInitializer
  1586. result.addStructInitializer(table, siArray):
  1587. for i in 0..<seqs.len:
  1588. result.addField(table, ""):
  1589. result.add(cCast(CPointer, seqs[i].loc.snippet))
  1590. proc genTypeInfoV2OldImpl(m: BModule; t, origType: PType, name: Rope; info: TLineInfo) =
  1591. cgsym(m, "TNimTypeV2")
  1592. m.s[cfsStrData].addDeclWithVisibility(Private):
  1593. m.s[cfsStrData].addVar(kind = Local, name = name, typ = "TNimTypeV2")
  1594. var flags = 0
  1595. if not canFormAcycle(m.g.graph, t): flags = flags or 1
  1596. var typeEntry = newBuilder("")
  1597. typeEntry.addFieldAssignmentWithValue(name, "destructor"):
  1598. typeEntry.addCast(CPointer):
  1599. genHook(m, t, info, attachedDestructor, typeEntry)
  1600. typeEntry.addFieldAssignmentWithValue(name, "traceImpl"):
  1601. typeEntry.addCast(CPointer):
  1602. genHook(m, t, info, attachedTrace, typeEntry)
  1603. let objDepth = if t.kind == tyObject: getObjDepth(t) else: -1
  1604. if t.kind in {tyObject, tyDistinct} and incompleteType(t):
  1605. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1606. typeToString(t))
  1607. if isDefined(m.config, "nimTypeNames"):
  1608. var typeName: Snippet
  1609. if t.kind in {tyObject, tyDistinct}:
  1610. typeName = genTypeInfo2Name(m, t)
  1611. else:
  1612. typeName = NimNil
  1613. typeEntry.addFieldAssignment(name, "name", typeName)
  1614. let sizeTyp = getTypeDesc(m, t)
  1615. typeEntry.addFieldAssignmentWithValue(name, "size"):
  1616. typeEntry.addSizeof(sizeTyp)
  1617. typeEntry.addFieldAssignmentWithValue(name, "align"):
  1618. typeEntry.addCast(typ = NimInt16):
  1619. typeEntry.addAlignof(sizeTyp)
  1620. typeEntry.addFieldAssignment(name, "depth", objDepth)
  1621. typeEntry.addFieldAssignment(name, "flags", flags)
  1622. if objDepth >= 0:
  1623. let objDisplayStore = getTempName(m)
  1624. m.s[cfsVars].addArrayVarWithInitializer(kind = Global,
  1625. name = objDisplayStore,
  1626. elementType = getTypeDesc(m, getSysType(m.g.graph, unknownLineInfo, tyUInt32), dkVar),
  1627. len = objDepth + 1):
  1628. genDisplay(m.s[cfsVars], m, t, objDepth)
  1629. typeEntry.addFieldAssignment(name, "display", objDisplayStore)
  1630. let dispatchMethods = toSeq(getMethodsPerType(m.g.graph, t))
  1631. if dispatchMethods.len > 0:
  1632. let vTablePointerName = getTempName(m)
  1633. m.s[cfsVars].addArrayVarWithInitializer(kind = Global,
  1634. name = vTablePointerName,
  1635. elementType = CPointer,
  1636. len = dispatchMethods.len):
  1637. genVTable(m.s[cfsVars], dispatchMethods)
  1638. for i in dispatchMethods:
  1639. genProcPrototype(m, i)
  1640. typeEntry.addFieldAssignment(name, "vTable", vTablePointerName)
  1641. m.s[cfsTypeInit3].add extract(typeEntry)
  1642. if t.kind == tyObject and t.baseClass != nil and optEnableDeepCopy in m.config.globalOptions:
  1643. discard genTypeInfoV1(m, t, info)
  1644. proc genTypeInfoV2Impl(m: BModule; t, origType: PType, name: Rope; info: TLineInfo) =
  1645. cgsym(m, "TNimTypeV2")
  1646. m.s[cfsStrData].addDeclWithVisibility(Private):
  1647. m.s[cfsStrData].addVar(kind = Local, name = name, typ = "TNimTypeV2")
  1648. var flags = 0
  1649. if not canFormAcycle(m.g.graph, t): flags = flags or 1
  1650. var typeEntry = newBuilder("")
  1651. typeEntry.addDeclWithVisibility(Private):
  1652. typeEntry.addVarWithInitializer(kind = Local, name = name, typ = "TNimTypeV2"):
  1653. var typeInit: StructInitializer
  1654. typeEntry.addStructInitializer(typeInit, kind = siNamedStruct):
  1655. typeEntry.addField(typeInit, name = "destructor"):
  1656. typeEntry.addCast(CPointer):
  1657. genHook(m, t, info, attachedDestructor, typeEntry)
  1658. let objDepth = if t.kind == tyObject: getObjDepth(t) else: -1
  1659. if t.kind in {tyObject, tyDistinct} and incompleteType(t):
  1660. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1661. typeToString(t))
  1662. let sizeType = getTypeDesc(m, t)
  1663. typeEntry.addField(typeInit, name = "size"):
  1664. typeEntry.addSizeof(sizeType)
  1665. typeEntry.addField(typeInit, name = "align"):
  1666. typeEntry.addCast(NimInt16):
  1667. typeEntry.addAlignof(sizeType)
  1668. typeEntry.addField(typeInit, name = "depth"):
  1669. typeEntry.addIntValue(objDepth)
  1670. if objDepth >= 0:
  1671. let objDisplayStore = getTempName(m)
  1672. m.s[cfsVars].addArrayVarWithInitializer(kind = Const,
  1673. name = objDisplayStore,
  1674. elementType = getTypeDesc(m, getSysType(m.g.graph, unknownLineInfo, tyUInt32), dkVar),
  1675. len = objDepth + 1):
  1676. genDisplay(m.s[cfsVars], m, t, objDepth)
  1677. typeEntry.addField(typeInit, name = "display"):
  1678. typeEntry.add(objDisplayStore)
  1679. if isDefined(m.config, "nimTypeNames"):
  1680. var typeName: Rope
  1681. if t.kind in {tyObject, tyDistinct}:
  1682. typeName = genTypeInfo2Name(m, t)
  1683. else:
  1684. typeName = NimNil
  1685. typeEntry.addField(typeInit, name = "name"):
  1686. typeEntry.add(typeName)
  1687. typeEntry.addField(typeInit, name = "traceImpl"):
  1688. typeEntry.addCast(CPointer):
  1689. genHook(m, t, info, attachedTrace, typeEntry)
  1690. let dispatchMethods = toSeq(getMethodsPerType(m.g.graph, t))
  1691. if dispatchMethods.len > 0:
  1692. typeEntry.addField(typeInit, name = "flags"):
  1693. typeEntry.addIntValue(flags)
  1694. for i in dispatchMethods:
  1695. genProcPrototype(m, i)
  1696. typeEntry.addField(typeInit, name = "vTable"):
  1697. genVTable(typeEntry, dispatchMethods)
  1698. else:
  1699. typeEntry.addField(typeInit, name = "flags"):
  1700. typeEntry.addIntValue(flags)
  1701. m.s[cfsVars].add extract(typeEntry)
  1702. if t.kind == tyObject and t.baseClass != nil and optEnableDeepCopy in m.config.globalOptions:
  1703. discard genTypeInfoV1(m, t, info)
  1704. proc genTypeInfoV2(m: BModule; t: PType; info: TLineInfo): Rope =
  1705. let origType = t
  1706. # distinct types can have their own destructors
  1707. var t = skipTypes(origType, irrelevantForBackend + tyUserTypeClasses - {tyDistinct})
  1708. template prefixTI(x: Snippet): Snippet =
  1709. if m.hcrOn:
  1710. wrapPar(x)
  1711. else:
  1712. cAddr(x)
  1713. let sig = hashType(origType, m.config)
  1714. result = m.typeInfoMarkerV2.getOrDefault(sig)
  1715. if result != "":
  1716. return prefixTI(result)
  1717. let marker = m.g.typeInfoMarkerV2.getOrDefault(sig)
  1718. if marker.str != "":
  1719. cgsym(m, "TNimTypeV2")
  1720. declareNimType(m, "TNimTypeV2", marker.str, marker.owner)
  1721. # also store in local type section:
  1722. m.typeInfoMarkerV2[sig] = marker.str
  1723. return prefixTI(marker.str)
  1724. result = "NTIv2$1_" % [rope($sig)]
  1725. m.typeInfoMarkerV2[sig] = result
  1726. let owner = t.skipTypes(typedescPtrs).itemId.module
  1727. if owner != m.module.position and moduleOpenForCodegen(m.g.graph, FileIndex owner):
  1728. # make sure the type info is created in the owner module
  1729. discard genTypeInfoV2(m.g.modules[owner], origType, info)
  1730. # reference the type info as extern here
  1731. cgsym(m, "TNimTypeV2")
  1732. declareNimType(m, "TNimTypeV2", result, owner)
  1733. return prefixTI(result)
  1734. m.g.typeInfoMarkerV2[sig] = (str: result, owner: owner)
  1735. if m.compileToCpp or m.hcrOn:
  1736. genTypeInfoV2OldImpl(m, t, origType, result, info)
  1737. else:
  1738. genTypeInfoV2Impl(m, t, origType, result, info)
  1739. result = prefixTI(result)
  1740. proc openArrayToTuple(m: BModule; t: PType): PType =
  1741. result = newType(tyTuple, m.idgen, t.owner)
  1742. let p = newType(tyPtr, m.idgen, t.owner)
  1743. let a = newType(tyUncheckedArray, m.idgen, t.owner)
  1744. a.add t.elementType
  1745. p.add a
  1746. result.add p
  1747. result.add getSysType(m.g.graph, t.owner.info, tyInt)
  1748. proc typeToC(t: PType): string =
  1749. ## Just for more readable names, the result doesn't have
  1750. ## to be unique.
  1751. let s = typeToString(t)
  1752. result = newStringOfCap(s.len)
  1753. for c in s:
  1754. case c
  1755. of 'a'..'z':
  1756. result.add c
  1757. of 'A'..'Z':
  1758. result.add toLowerAscii(c)
  1759. of ' ':
  1760. discard
  1761. of ',':
  1762. result.add '_'
  1763. of '.':
  1764. result.add 'O'
  1765. of '[', '(', '{':
  1766. result.add 'L'
  1767. of ']', ')', '}':
  1768. result.add 'T'
  1769. else:
  1770. # We mangle upper letters and digits too so that there cannot
  1771. # be clashes with our special meanings
  1772. result.addInt ord(c)
  1773. proc genTypeInfoV1(m: BModule; t: PType; info: TLineInfo): Rope =
  1774. let origType = t
  1775. var t = skipTypes(origType, irrelevantForBackend + tyUserTypeClasses)
  1776. template prefixTI(x: Snippet): Snippet =
  1777. if m.hcrOn:
  1778. wrapPar(x)
  1779. else:
  1780. cAddr(x)
  1781. let sig = hashType(origType, m.config)
  1782. result = m.typeInfoMarker.getOrDefault(sig)
  1783. if result != "":
  1784. return prefixTI(result)
  1785. let marker = m.g.typeInfoMarker.getOrDefault(sig)
  1786. if marker.str != "":
  1787. cgsym(m, "TNimType")
  1788. cgsym(m, "TNimNode")
  1789. declareNimType(m, "TNimType", marker.str, marker.owner)
  1790. # also store in local type section:
  1791. m.typeInfoMarker[sig] = marker.str
  1792. return prefixTI(marker.str)
  1793. result = "NTI$1$2_" % [rope(typeToC(t)), rope($sig)]
  1794. m.typeInfoMarker[sig] = result
  1795. let old = m.g.graph.emittedTypeInfo.getOrDefault($result)
  1796. if old != FileIndex(0):
  1797. cgsym(m, "TNimType")
  1798. cgsym(m, "TNimNode")
  1799. declareNimType(m, "TNimType", result, old.int)
  1800. return prefixTI(result)
  1801. var owner = t.skipTypes(typedescPtrs).itemId.module
  1802. if owner != m.module.position and moduleOpenForCodegen(m.g.graph, FileIndex owner):
  1803. # make sure the type info is created in the owner module
  1804. discard genTypeInfoV1(m.g.modules[owner], origType, info)
  1805. # reference the type info as extern here
  1806. cgsym(m, "TNimType")
  1807. cgsym(m, "TNimNode")
  1808. declareNimType(m, "TNimType", result, owner)
  1809. return prefixTI(result)
  1810. else:
  1811. owner = m.module.position.int32
  1812. m.g.typeInfoMarker[sig] = (str: result, owner: owner)
  1813. rememberEmittedTypeInfo(m.g.graph, FileIndex(owner), $result)
  1814. case t.kind
  1815. of tyEmpty, tyVoid: result = cIntValue(0)
  1816. of tyPointer, tyBool, tyChar, tyCstring, tyString, tyInt..tyUInt64, tyVar, tyLent:
  1817. genTypeInfoAuxBase(m, t, t, result, cIntValue(0), info)
  1818. of tyStatic:
  1819. if t.n != nil: result = genTypeInfoV1(m, skipModifier t, info)
  1820. else: internalError(m.config, "genTypeInfoV1(" & $t.kind & ')')
  1821. of tyUserTypeClasses:
  1822. internalAssert m.config, t.isResolvedUserTypeClass
  1823. return genTypeInfoV1(m, t.skipModifier, info)
  1824. of tyProc:
  1825. if t.callConv != ccClosure:
  1826. genTypeInfoAuxBase(m, t, t, result, cIntValue(0), info)
  1827. else:
  1828. let x = fakeClosureType(m, t.owner)
  1829. genTupleInfo(m, x, x, result, info)
  1830. of tySequence:
  1831. genTypeInfoAux(m, t, t, result, info)
  1832. if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcGo}:
  1833. let markerProc = genTraverseProc(m, origType, sig)
  1834. m.s[cfsTypeInit3].addFieldAssignment(tiNameForHcr(m, result), "marker", markerProc)
  1835. of tyRef:
  1836. genTypeInfoAux(m, t, t, result, info)
  1837. if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcGo}:
  1838. let markerProc = genTraverseProc(m, origType, sig)
  1839. m.s[cfsTypeInit3].addFieldAssignment(tiNameForHcr(m, result), "marker", markerProc)
  1840. of tyPtr, tyRange, tyUncheckedArray: genTypeInfoAux(m, t, t, result, info)
  1841. of tyArray: genArrayInfo(m, t, result, info)
  1842. of tySet: genSetInfo(m, t, result, info)
  1843. of tyEnum: genEnumInfo(m, t, result, info)
  1844. of tyObject:
  1845. genObjectInfo(m, t, origType, result, info)
  1846. of tyTuple:
  1847. # if t.n != nil: genObjectInfo(m, t, result)
  1848. # else:
  1849. # BUGFIX: use consistently RTTI without proper field names; otherwise
  1850. # results are not deterministic!
  1851. genTupleInfo(m, t, origType, result, info)
  1852. of tyOpenArray:
  1853. let x = openArrayToTuple(m, t)
  1854. genTupleInfo(m, x, origType, result, info)
  1855. else: internalError(m.config, "genTypeInfoV1(" & $t.kind & ')')
  1856. var op = getAttachedOp(m.g.graph, t, attachedDeepCopy)
  1857. if op == nil:
  1858. op = getAttachedOp(m.g.graph, origType, attachedDeepCopy)
  1859. if op != nil:
  1860. genDeepCopyProc(m, op, result)
  1861. if optTinyRtti in m.config.globalOptions and t.kind == tyObject and sfImportc notin t.sym.flags:
  1862. let v2info = genTypeInfoV2(m, origType, info)
  1863. m.s[cfsTypeInit3].addDerefFieldAssignment(v2info, "typeInfoV1", cCast(CPointer, cAddr(result)))
  1864. m.s[cfsTypeInit3].addFieldAssignment(result, "typeInfoV2", cCast(CPointer, v2info))
  1865. result = prefixTI(result)
  1866. proc genTypeInfo*(config: ConfigRef, m: BModule; t: PType; info: TLineInfo): Rope =
  1867. if optTinyRtti in config.globalOptions:
  1868. result = genTypeInfoV2(m, t, info)
  1869. else:
  1870. result = genTypeInfoV1(m, t, info)
  1871. proc genTypeSection(m: BModule, n: PNode) =
  1872. var intSet = initIntSet()
  1873. for i in 0..<n.len:
  1874. if len(n[i]) == 0: continue
  1875. if n[i][0].kind != nkPragmaExpr: continue
  1876. for p in 0..<n[i][0].len:
  1877. if (n[i][0][p].kind notin {nkSym, nkPostfix}): continue
  1878. var s = n[i][0][p]
  1879. if s.kind == nkPostfix:
  1880. s = n[i][0][p][1]
  1881. if {sfExportc, sfCompilerProc} * s.sym.flags == {sfExportc}:
  1882. discard getTypeDescAux(m, s.typ, intSet, descKindFromSymKind(s.sym.kind))
  1883. if m.g.generatedHeader != nil:
  1884. discard getTypeDescAux(m.g.generatedHeader, s.typ, intSet, descKindFromSymKind(s.sym.kind))