ccgtypes.nim 74 KB

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