ccgtypes.nim 77 KB

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