ccgtypes.nim 74 KB

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