ccgtypes.nim 74 KB

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