ccgtypes.nim 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  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
  12. from lowerings import createObj
  13. proc genProcHeader(m: BModule, prc: PSym, asPtr: bool = false): Rope
  14. proc isKeyword(w: PIdent): bool =
  15. # Nim and C++ share some keywords
  16. # it's more efficient to test the whole Nim keywords range
  17. case w.id
  18. of ccgKeywordsLow..ccgKeywordsHigh,
  19. nimKeywordsLow..nimKeywordsHigh,
  20. ord(wInline): return true
  21. else: return false
  22. proc mangleField(m: BModule; name: PIdent): string =
  23. result = mangle(name.s)
  24. # fields are tricky to get right and thanks to generic types producing
  25. # duplicates we can end up mangling the same field multiple times. However
  26. # if we do so, the 'cppDefines' table might be modified in the meantime
  27. # meaning we produce inconsistent field names (see bug #5404).
  28. # Hence we do not check for ``m.g.config.cppDefines.contains(result)`` here
  29. # anymore:
  30. if isKeyword(name):
  31. result.add "_0"
  32. when false:
  33. proc hashOwner(s: PSym): SigHash =
  34. var m = s
  35. while m.kind != skModule: m = m.owner
  36. let p = m.owner
  37. assert p.kind == skPackage
  38. result = gDebugInfo.register(p.name.s, m.name.s)
  39. proc mangleName(m: BModule; s: PSym): Rope =
  40. result = s.loc.r
  41. if result == nil:
  42. result = s.name.s.mangle.rope
  43. result.add(idOrSig(s, m.module.name.s.mangle, m.sigConflicts))
  44. s.loc.r = result
  45. writeMangledName(m.ndi, s, m.config)
  46. proc mangleParamName(m: BModule; s: PSym): Rope =
  47. ## we cannot use 'sigConflicts' here since we have a BModule, not a BProc.
  48. ## Fortunately C's scoping rules are sane enough so that that doesn't
  49. ## cause any trouble.
  50. result = s.loc.r
  51. if result == nil:
  52. var res = s.name.s.mangle
  53. # Take into account if HCR is on because of the following scenario:
  54. # if a module gets imported and it has some more importc symbols in it,
  55. # some param names might receive the "_0" suffix to distinguish from what
  56. # is newly available. That might lead to changes in the C code in nimcache
  57. # that contain only a parameter name change, but that is enough to mandate
  58. # recompilation of that source file and thus a new shared object will be
  59. # relinked. That may lead to a module getting reloaded which wasn't intended
  60. # and that may be fatal when parts of the current active callstack when
  61. # performCodeReload() was called are from the module being reloaded
  62. # unintentionally - example (3 modules which import one another):
  63. # main => proxy => reloadable
  64. # we call performCodeReload() in proxy to reload only changes in reloadable
  65. # but there is a new import which introduces an importc symbol `socket`
  66. # and a function called in main or proxy uses `socket` as a parameter name.
  67. # That would lead to either needing to reload `proxy` or to overwrite the
  68. # executable file for the main module, which is running (or both!) -> error.
  69. if m.hcrOn or isKeyword(s.name) or m.g.config.cppDefines.contains(res):
  70. res.add "_0"
  71. result = res.rope
  72. s.loc.r = result
  73. writeMangledName(m.ndi, s, m.config)
  74. proc mangleLocalName(p: BProc; s: PSym): Rope =
  75. assert s.kind in skLocalVars+{skTemp}
  76. #assert sfGlobal notin s.flags
  77. result = s.loc.r
  78. if result == nil:
  79. var key = s.name.s.mangle
  80. shallow(key)
  81. let counter = p.sigConflicts.getOrDefault(key)
  82. result = key.rope
  83. if s.kind == skTemp:
  84. # speed up conflict search for temps (these are quite common):
  85. if counter != 0: result.add "_" & rope(counter+1)
  86. elif counter != 0 or isKeyword(s.name) or p.module.g.config.cppDefines.contains(key):
  87. result.add "_" & rope(counter+1)
  88. p.sigConflicts.inc(key)
  89. s.loc.r = result
  90. if s.kind != skTemp: writeMangledName(p.module.ndi, s, p.config)
  91. proc scopeMangledParam(p: BProc; param: PSym) =
  92. ## parameter generation only takes BModule, not a BProc, so we have to
  93. ## remember these parameter names are already in scope to be able to
  94. ## generate unique identifiers reliably (consider that ``var a = a`` is
  95. ## even an idiom in Nim).
  96. var key = param.name.s.mangle
  97. shallow(key)
  98. p.sigConflicts.inc(key)
  99. const
  100. irrelevantForBackend = {tyGenericBody, tyGenericInst, tyGenericInvocation,
  101. tyDistinct, tyRange, tyStatic, tyAlias, tySink,
  102. tyInferred, tyOwned}
  103. proc typeName(typ: PType): Rope =
  104. let typ = typ.skipTypes(irrelevantForBackend)
  105. result =
  106. if typ.sym != nil and typ.kind in {tyObject, tyEnum}:
  107. rope($typ.kind & '_' & typ.sym.name.s.mangle)
  108. else:
  109. rope($typ.kind)
  110. proc getTypeName(m: BModule; typ: PType; sig: SigHash): Rope =
  111. var t = typ
  112. while true:
  113. if t.sym != nil and {sfImportc, sfExportc} * t.sym.flags != {}:
  114. return t.sym.loc.r
  115. if t.kind in irrelevantForBackend:
  116. t = t.lastSon
  117. else:
  118. break
  119. let typ = if typ.kind in {tyAlias, tySink, tyOwned}: typ.lastSon else: typ
  120. if typ.loc.r == nil:
  121. typ.loc.r = typ.typeName & $sig
  122. else:
  123. when defined(debugSigHashes):
  124. # check consistency:
  125. assert($typ.loc.r == $(typ.typeName & $sig))
  126. result = typ.loc.r
  127. if result == nil: internalError(m.config, "getTypeName: " & $typ.kind)
  128. proc mapSetType(conf: ConfigRef; typ: PType): TCTypeKind =
  129. case int(getSize(conf, typ))
  130. of 1: result = ctInt8
  131. of 2: result = ctInt16
  132. of 4: result = ctInt32
  133. of 8: result = ctInt64
  134. else: result = ctArray
  135. proc mapType(conf: ConfigRef; typ: PType; kind: TSymKind): TCTypeKind =
  136. ## Maps a Nim type to a C type
  137. case typ.kind
  138. of tyNone, tyTyped: result = ctVoid
  139. of tyBool: result = ctBool
  140. of tyChar: result = ctChar
  141. of tyNil: result = ctPtr
  142. of tySet: result = mapSetType(conf, typ)
  143. of tyOpenArray, tyVarargs:
  144. if kind == skParam: result = ctArray
  145. else: result = ctStruct
  146. of tyArray, tyUncheckedArray: result = ctArray
  147. of tyObject, tyTuple: result = ctStruct
  148. of tyUserTypeClasses:
  149. doAssert typ.isResolvedUserTypeClass
  150. return mapType(conf, typ.lastSon, kind)
  151. of tyGenericBody, tyGenericInst, tyGenericParam, tyDistinct, tyOrdinal,
  152. tyTypeDesc, tyAlias, tySink, tyInferred, tyOwned:
  153. result = mapType(conf, lastSon(typ), kind)
  154. of tyEnum:
  155. if firstOrd(conf, typ) < 0:
  156. result = ctInt32
  157. else:
  158. case int(getSize(conf, typ))
  159. of 1: result = ctUInt8
  160. of 2: result = ctUInt16
  161. of 4: result = ctInt32
  162. of 8: result = ctInt64
  163. else: result = ctInt32
  164. of tyRange: result = mapType(conf, typ[0], kind)
  165. of tyPtr, tyVar, tyLent, tyRef:
  166. var base = skipTypes(typ.lastSon, typedescInst)
  167. case base.kind
  168. of tyOpenArray, tyArray, tyVarargs, tyUncheckedArray: result = ctPtrToArray
  169. of tySet:
  170. if mapSetType(conf, base) == ctArray: result = ctPtrToArray
  171. else: result = ctPtr
  172. else: result = ctPtr
  173. of tyPointer: result = ctPtr
  174. of tySequence: result = ctNimSeq
  175. of tyProc: result = if typ.callConv != ccClosure: ctProc else: ctStruct
  176. of tyString: result = ctNimStr
  177. of tyCString: result = ctCString
  178. of tyInt..tyUInt64:
  179. result = TCTypeKind(ord(typ.kind) - ord(tyInt) + ord(ctInt))
  180. of tyStatic:
  181. if typ.n != nil: result = mapType(conf, lastSon typ, kind)
  182. else: doAssert(false, "mapType")
  183. else: doAssert(false, "mapType")
  184. proc mapReturnType(conf: ConfigRef; typ: PType): TCTypeKind =
  185. #if skipTypes(typ, typedescInst).kind == tyArray: result = ctPtr
  186. #else:
  187. result = mapType(conf, typ, skResult)
  188. proc isImportedType(t: PType): bool =
  189. result = t.sym != nil and sfImportc in t.sym.flags
  190. proc isImportedCppType(t: PType): bool =
  191. let x = t.skipTypes(irrelevantForBackend)
  192. result = (t.sym != nil and sfInfixCall in t.sym.flags) or
  193. (x.sym != nil and sfInfixCall in x.sym.flags)
  194. proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKind): Rope
  195. proc isObjLackingTypeField(typ: PType): bool {.inline.} =
  196. result = (typ.kind == tyObject) and ((tfFinal in typ.flags) and
  197. (typ[0] == nil) or isPureObject(typ))
  198. proc isInvalidReturnType(conf: ConfigRef; rettype: PType): bool =
  199. # Arrays and sets cannot be returned by a C procedure, because C is
  200. # such a poor programming language.
  201. # We exclude records with refs too. This enhances efficiency and
  202. # is necessary for proper code generation of assignments.
  203. if rettype == nil: result = true
  204. else:
  205. case mapType(conf, rettype, skResult)
  206. of ctArray:
  207. result = not (skipTypes(rettype, typedescInst).kind in
  208. {tyVar, tyLent, tyRef, tyPtr})
  209. of ctStruct:
  210. let t = skipTypes(rettype, typedescInst)
  211. if rettype.isImportedCppType or t.isImportedCppType: return false
  212. result = containsGarbageCollectedRef(t) or
  213. (t.kind == tyObject and not isObjLackingTypeField(t))
  214. else: result = false
  215. const
  216. CallingConvToStr: array[TCallingConvention, string] = ["N_NIMCALL",
  217. "N_STDCALL", "N_CDECL", "N_SAFECALL",
  218. "N_SYSCALL", # this is probably not correct for all platforms,
  219. # but one can #define it to what one wants
  220. "N_INLINE", "N_NOINLINE", "N_FASTCALL", "N_THISCALL", "N_CLOSURE", "N_NOCONV"]
  221. proc cacheGetType(tab: TypeCache; sig: SigHash): Rope =
  222. # returns nil if we need to declare this type
  223. # since types are now unique via the ``getUniqueType`` mechanism, this slow
  224. # linear search is not necessary anymore:
  225. result = tab.getOrDefault(sig)
  226. proc addAbiCheck(m: BModule, t: PType, name: Rope) =
  227. if isDefined(m.config, "checkAbi") and (let size = getSize(m.config, t); size != szUnknownSize):
  228. var msg = "backend & Nim disagree on size for: "
  229. msg.addTypeHeader(m.config, t)
  230. var msg2 = ""
  231. msg2.addQuoted msg # not a hostspot so extra allocation doesn't matter
  232. m.s[cfsTypeInfo].addf("NIM_STATIC_ASSERT(sizeof($1) == $2, $3);$n", [name, rope(size), msg2.rope])
  233. # see `testCodegenABICheck` for example error message it generates
  234. proc ccgIntroducedPtr(conf: ConfigRef; s: PSym, retType: PType): bool =
  235. var pt = skipTypes(s.typ, typedescInst)
  236. assert skResult != s.kind
  237. if tfByRef in pt.flags: return true
  238. elif tfByCopy in pt.flags: return false
  239. case pt.kind
  240. of tyObject:
  241. if s.typ.sym != nil and sfForward in s.typ.sym.flags:
  242. # forwarded objects are *always* passed by pointers for consistency!
  243. result = true
  244. elif (optByRef in s.options) or (getSize(conf, pt) > conf.target.floatSize * 3):
  245. result = true # requested anyway
  246. elif (tfFinal in pt.flags) and (pt[0] == nil):
  247. result = false # no need, because no subtyping possible
  248. else:
  249. result = true # ordinary objects are always passed by reference,
  250. # otherwise casting doesn't work
  251. of tyTuple:
  252. result = (getSize(conf, pt) > conf.target.floatSize*3) or (optByRef in s.options)
  253. else:
  254. result = false
  255. # first parameter and return type is 'lent T'? --> use pass by pointer
  256. if s.position == 0 and retType != nil and retType.kind == tyLent:
  257. result = pt.kind != tyVar
  258. proc fillResult(conf: ConfigRef; param: PNode) =
  259. fillLoc(param.sym.loc, locParam, param, ~"Result",
  260. OnStack)
  261. let t = param.sym.typ
  262. if mapReturnType(conf, t) != ctArray and isInvalidReturnType(conf, t):
  263. incl(param.sym.loc.flags, lfIndirect)
  264. param.sym.loc.storage = OnUnknown
  265. proc typeNameOrLiteral(m: BModule; t: PType, literal: string): Rope =
  266. if t.sym != nil and sfImportc in t.sym.flags and t.sym.magic == mNone:
  267. useHeader(m, t.sym)
  268. result = t.sym.loc.r
  269. else:
  270. result = rope(literal)
  271. proc getSimpleTypeDesc(m: BModule, typ: PType): Rope =
  272. const
  273. NumericalTypeToStr: array[tyInt..tyUInt64, string] = [
  274. "NI", "NI8", "NI16", "NI32", "NI64",
  275. "NF", "NF32", "NF64", "NF128",
  276. "NU", "NU8", "NU16", "NU32", "NU64"]
  277. case typ.kind
  278. of tyPointer:
  279. result = typeNameOrLiteral(m, typ, "void*")
  280. of tyString:
  281. case detectStrVersion(m)
  282. of 2:
  283. discard cgsym(m, "NimStrPayload")
  284. discard cgsym(m, "NimStringV2")
  285. result = typeNameOrLiteral(m, typ, "NimStringV2")
  286. else:
  287. discard cgsym(m, "NimStringDesc")
  288. result = typeNameOrLiteral(m, typ, "NimStringDesc*")
  289. of tyCString: result = typeNameOrLiteral(m, typ, "NCSTRING")
  290. of tyBool: result = typeNameOrLiteral(m, typ, "NIM_BOOL")
  291. of tyChar: result = typeNameOrLiteral(m, typ, "NIM_CHAR")
  292. of tyNil: result = typeNameOrLiteral(m, typ, "void*")
  293. of tyInt..tyUInt64:
  294. result = typeNameOrLiteral(m, typ, NumericalTypeToStr[typ.kind])
  295. of tyDistinct, tyRange, tyOrdinal: result = getSimpleTypeDesc(m, typ[0])
  296. of tyStatic:
  297. if typ.n != nil: result = getSimpleTypeDesc(m, lastSon typ)
  298. else: internalError(m.config, "tyStatic for getSimpleTypeDesc")
  299. of tyGenericInst, tyAlias, tySink, tyOwned:
  300. result = getSimpleTypeDesc(m, lastSon typ)
  301. else: result = nil
  302. if result != nil and typ.isImportedType():
  303. let sig = hashType typ
  304. if cacheGetType(m.typeCache, sig) == nil:
  305. m.typeCache[sig] = result
  306. proc pushType(m: BModule, typ: PType) =
  307. for i in 0..high(m.typeStack):
  308. # pointer equality is good enough here:
  309. if m.typeStack[i] == typ: return
  310. m.typeStack.add(typ)
  311. proc getTypePre(m: BModule, typ: PType; sig: SigHash): Rope =
  312. if typ == nil: result = rope("void")
  313. else:
  314. result = getSimpleTypeDesc(m, typ)
  315. if result == nil: result = cacheGetType(m.typeCache, sig)
  316. proc structOrUnion(t: PType): Rope =
  317. let cachedUnion = rope("union")
  318. let cachedStruct = rope("struct")
  319. let t = t.skipTypes({tyAlias, tySink})
  320. if tfUnion in t.flags: cachedUnion
  321. else: cachedStruct
  322. proc addForwardStructFormat(m: BModule, structOrUnion: Rope, typename: Rope) =
  323. if m.compileToCpp:
  324. m.s[cfsForwardTypes].addf "$1 $2;$n", [structOrUnion, typename]
  325. else:
  326. m.s[cfsForwardTypes].addf "typedef $1 $2 $2;$n", [structOrUnion, typename]
  327. proc seqStar(m: BModule): string =
  328. if optSeqDestructors in m.config.globalOptions: result = ""
  329. else: result = "*"
  330. proc getTypeForward(m: BModule, typ: PType; sig: SigHash): Rope =
  331. result = cacheGetType(m.forwTypeCache, sig)
  332. if result != nil: return
  333. result = getTypePre(m, typ, sig)
  334. if result != nil: return
  335. let concrete = typ.skipTypes(abstractInst)
  336. case concrete.kind
  337. of tySequence, tyTuple, tyObject:
  338. result = getTypeName(m, typ, sig)
  339. m.forwTypeCache[sig] = result
  340. if not isImportedType(concrete):
  341. addForwardStructFormat(m, structOrUnion(typ), result)
  342. else:
  343. pushType(m, concrete)
  344. doAssert m.forwTypeCache[sig] == result
  345. else: internalError(m.config, "getTypeForward(" & $typ.kind & ')')
  346. proc getTypeDescWeak(m: BModule; t: PType; check: var IntSet; kind: TSymKind): Rope =
  347. ## like getTypeDescAux but creates only a *weak* dependency. In other words
  348. ## we know we only need a pointer to it so we only generate a struct forward
  349. ## declaration:
  350. let etB = t.skipTypes(abstractInst)
  351. case etB.kind
  352. of tyObject, tyTuple:
  353. if isImportedCppType(etB) and t.kind == tyGenericInst:
  354. result = getTypeDescAux(m, t, check, kind)
  355. else:
  356. result = getTypeForward(m, t, hashType(t))
  357. pushType(m, t)
  358. of tySequence:
  359. let sig = hashType(t)
  360. if optSeqDestructors in m.config.globalOptions:
  361. if skipTypes(etB[0], typedescInst).kind == tyEmpty:
  362. internalError(m.config, "cannot map the empty seq type to a C type")
  363. result = cacheGetType(m.forwTypeCache, sig)
  364. if result == nil:
  365. result = getTypeName(m, t, sig)
  366. if not isImportedType(t):
  367. m.forwTypeCache[sig] = result
  368. addForwardStructFormat(m, rope"struct", result)
  369. let payload = result & "_Content"
  370. addForwardStructFormat(m, rope"struct", payload)
  371. if cacheGetType(m.typeCache, sig) == nil:
  372. m.typeCache[sig] = result
  373. #echo "adding ", sig, " ", typeToString(t), " ", m.module.name.s
  374. appcg(m, m.s[cfsTypes],
  375. "struct $1 {$N" &
  376. " NI len; $1_Content* p;$N" &
  377. "};$N", [result])
  378. else:
  379. result = getTypeForward(m, t, sig) & seqStar(m)
  380. pushType(m, t)
  381. else:
  382. result = getTypeDescAux(m, t, check, kind)
  383. proc getSeqPayloadType(m: BModule; t: PType): Rope =
  384. var check = initIntSet()
  385. result = getTypeDescWeak(m, t, check, skParam) & "_Content"
  386. #result = getTypeForward(m, t, hashType(t)) & "_Content"
  387. proc seqV2ContentType(m: BModule; t: PType; check: var IntSet) =
  388. let sig = hashType(t)
  389. let result = cacheGetType(m.typeCache, sig)
  390. if result == nil:
  391. discard getTypeDescAux(m, t, check, skVar)
  392. else:
  393. # little hack for now to prevent multiple definitions of the same
  394. # Seq_Content:
  395. appcg(m, m.s[cfsTypes], """$N
  396. $3ifndef $2_Content_PP
  397. $3define $2_Content_PP
  398. struct $2_Content { NI cap; $1 data[SEQ_DECL_SIZE];};
  399. $3endif$N
  400. """, [getTypeDescAux(m, t.skipTypes(abstractInst)[0], check, skVar), result, rope"#"])
  401. proc paramStorageLoc(param: PSym): TStorageLoc =
  402. if param.typ.skipTypes({tyVar, tyLent, tyTypeDesc}).kind notin {
  403. tyArray, tyOpenArray, tyVarargs}:
  404. result = OnStack
  405. else:
  406. result = OnUnknown
  407. proc genProcParams(m: BModule, t: PType, rettype, params: var Rope,
  408. check: var IntSet, declareEnvironment=true;
  409. weakDep=false) =
  410. params = nil
  411. if t[0] == nil or isInvalidReturnType(m.config, t[0]):
  412. rettype = ~"void"
  413. else:
  414. rettype = getTypeDescAux(m, t[0], check, skResult)
  415. for i in 1..<t.n.len:
  416. if t.n[i].kind != nkSym: internalError(m.config, t.n.info, "genProcParams")
  417. var param = t.n[i].sym
  418. if isCompileTimeOnly(param.typ): continue
  419. if params != nil: params.add(~", ")
  420. fillLoc(param.loc, locParam, t.n[i], mangleParamName(m, param),
  421. param.paramStorageLoc)
  422. if ccgIntroducedPtr(m.config, param, t[0]):
  423. params.add(getTypeDescWeak(m, param.typ, check, skParam))
  424. params.add(~"*")
  425. incl(param.loc.flags, lfIndirect)
  426. param.loc.storage = OnUnknown
  427. elif weakDep:
  428. params.add(getTypeDescWeak(m, param.typ, check, skParam))
  429. else:
  430. params.add(getTypeDescAux(m, param.typ, check, skParam))
  431. params.add(~" ")
  432. if sfNoalias in param.flags:
  433. params.add(~"NIM_NOALIAS ")
  434. params.add(param.loc.r)
  435. # declare the len field for open arrays:
  436. var arr = param.typ
  437. if arr.kind in {tyVar, tyLent, tySink}: arr = arr.lastSon
  438. var j = 0
  439. while arr.kind in {tyOpenArray, tyVarargs}:
  440. # this fixes the 'sort' bug:
  441. if param.typ.kind in {tyVar, tyLent}: param.loc.storage = OnUnknown
  442. # need to pass hidden parameter:
  443. params.addf(", NI $1Len_$2", [param.loc.r, j.rope])
  444. inc(j)
  445. arr = arr[0].skipTypes({tySink})
  446. if t[0] != nil and isInvalidReturnType(m.config, t[0]):
  447. var arr = t[0]
  448. if params != nil: params.add(", ")
  449. if mapReturnType(m.config, t[0]) != ctArray:
  450. params.add(getTypeDescWeak(m, arr, check, skResult))
  451. params.add("*")
  452. else:
  453. params.add(getTypeDescAux(m, arr, check, skResult))
  454. params.addf(" Result", [])
  455. if t.callConv == ccClosure and declareEnvironment:
  456. if params != nil: params.add(", ")
  457. params.add("void* ClE_0")
  458. if tfVarargs in t.flags:
  459. if params != nil: params.add(", ")
  460. params.add("...")
  461. if params == nil: params.add("void)")
  462. else: params.add(")")
  463. params = "(" & params
  464. proc mangleRecFieldName(m: BModule; field: PSym): Rope =
  465. if {sfImportc, sfExportc} * field.flags != {}:
  466. result = field.loc.r
  467. else:
  468. result = rope(mangleField(m, field.name))
  469. if result == nil: internalError(m.config, field.info, "mangleRecFieldName")
  470. proc genRecordFieldsAux(m: BModule, n: PNode,
  471. rectype: PType,
  472. check: var IntSet, unionPrefix = ""): Rope =
  473. result = nil
  474. case n.kind
  475. of nkRecList:
  476. for i in 0..<n.len:
  477. result.add(genRecordFieldsAux(m, n[i], rectype, check, unionPrefix))
  478. of nkRecCase:
  479. if n[0].kind != nkSym: internalError(m.config, n.info, "genRecordFieldsAux")
  480. result.add(genRecordFieldsAux(m, n[0], rectype, check, unionPrefix))
  481. # prefix mangled name with "_U" to avoid clashes with other field names,
  482. # since identifiers are not allowed to start with '_'
  483. var unionBody: Rope = nil
  484. for i in 1..<n.len:
  485. case n[i].kind
  486. of nkOfBranch, nkElse:
  487. let k = lastSon(n[i])
  488. if k.kind != nkSym:
  489. let structName = "_" & mangleRecFieldName(m, n[0].sym) & "_" & $i
  490. let a = genRecordFieldsAux(m, k, rectype, check, unionPrefix & $structName & ".")
  491. if a != nil:
  492. if tfPacked notin rectype.flags:
  493. unionBody.add("struct {")
  494. else:
  495. if hasAttribute in CC[m.config.cCompiler].props:
  496. unionBody.add("struct __attribute__((__packed__)){")
  497. else:
  498. unionBody.addf("#pragma pack(push, 1)$nstruct{", [])
  499. unionBody.add(a)
  500. unionBody.addf("} $1;$n", [structName])
  501. if tfPacked in rectype.flags and hasAttribute notin CC[m.config.cCompiler].props:
  502. unionBody.addf("#pragma pack(pop)$n", [])
  503. else:
  504. unionBody.add(genRecordFieldsAux(m, k, rectype, check, unionPrefix))
  505. else: internalError(m.config, "genRecordFieldsAux(record case branch)")
  506. if unionBody != nil:
  507. result.addf("union{$n$1};$n", [unionBody])
  508. of nkSym:
  509. let field = n.sym
  510. if field.typ.kind == tyVoid: return
  511. #assert(field.ast == nil)
  512. let sname = mangleRecFieldName(m, field)
  513. fillLoc(field.loc, locField, n, unionPrefix & sname, OnUnknown)
  514. if field.alignment > 0:
  515. result.addf "NIM_ALIGN($1) ", [rope(field.alignment)]
  516. # for importcpp'ed objects, we only need to set field.loc, but don't
  517. # have to recurse via 'getTypeDescAux'. And not doing so prevents problems
  518. # with heavily templatized C++ code:
  519. if not isImportedCppType(rectype):
  520. let fieldType = field.loc.lode.typ.skipTypes(abstractInst)
  521. if fieldType.kind == tyUncheckedArray:
  522. result.addf("$1 $2[SEQ_DECL_SIZE];$n",
  523. [getTypeDescAux(m, fieldType.elemType, check, skField), sname])
  524. elif fieldType.kind == tySequence:
  525. # we need to use a weak dependency here for trecursive_table.
  526. result.addf("$1 $2;$n", [getTypeDescWeak(m, field.loc.t, check, skField), sname])
  527. elif field.bitsize != 0:
  528. result.addf("$1 $2:$3;$n", [getTypeDescAux(m, field.loc.t, check, skField), sname, rope($field.bitsize)])
  529. else:
  530. # don't use fieldType here because we need the
  531. # tyGenericInst for C++ template support
  532. result.addf("$1 $2;$n", [getTypeDescAux(m, field.loc.t, check, skField), sname])
  533. else: internalError(m.config, n.info, "genRecordFieldsAux()")
  534. proc getRecordFields(m: BModule, typ: PType, check: var IntSet): Rope =
  535. result = genRecordFieldsAux(m, typ.n, typ, check)
  536. proc fillObjectFields*(m: BModule; typ: PType) =
  537. # sometimes generic objects are not consistently merged. We patch over
  538. # this fact here.
  539. var check = initIntSet()
  540. discard getRecordFields(m, typ, check)
  541. proc mangleDynLibProc(sym: PSym): Rope
  542. proc getRecordDesc(m: BModule, typ: PType, name: Rope,
  543. check: var IntSet): Rope =
  544. # declare the record:
  545. var hasField = false
  546. if tfPacked in typ.flags:
  547. if hasAttribute in CC[m.config.cCompiler].props:
  548. result = structOrUnion(typ) & " __attribute__((__packed__))"
  549. else:
  550. result = "#pragma pack(push, 1)\L" & structOrUnion(typ)
  551. else:
  552. result = structOrUnion(typ)
  553. result.add " "
  554. result.add name
  555. if typ.kind == tyObject:
  556. if typ[0] == nil:
  557. if (typ.sym != nil and sfPure in typ.sym.flags) or tfFinal in typ.flags:
  558. appcg(m, result, " {$n", [])
  559. else:
  560. if optTinyRtti in m.config.globalOptions:
  561. appcg(m, result, " {$n#TNimTypeV2* m_type;$n", [])
  562. else:
  563. appcg(m, result, " {$n#TNimType* m_type;$n", [])
  564. hasField = true
  565. elif m.compileToCpp:
  566. appcg(m, result, " : public $1 {$n",
  567. [getTypeDescAux(m, typ[0].skipTypes(skipPtrs), check, skField)])
  568. if typ.isException and m.config.exc == excCpp:
  569. when false:
  570. appcg(m, result, "virtual void raise() { throw *this; }$n", []) # required for polymorphic exceptions
  571. if typ.sym.magic == mException:
  572. # Add cleanup destructor to Exception base class
  573. appcg(m, result, "~$1();$n", [name])
  574. # define it out of the class body and into the procs section so we don't have to
  575. # artificially forward-declare popCurrentExceptionEx (very VERY troublesome for HCR)
  576. appcg(m, cfsProcs, "inline $1::~$1() {if(this->raiseId) #popCurrentExceptionEx(this->raiseId);}$n", [name])
  577. hasField = true
  578. else:
  579. appcg(m, result, " {$n $1 Sup;$n",
  580. [getTypeDescAux(m, typ[0].skipTypes(skipPtrs), check, skField)])
  581. hasField = true
  582. else:
  583. result.addf(" {$n", [name])
  584. let desc = getRecordFields(m, typ, check)
  585. if desc == nil and not hasField:
  586. result.addf("char dummy;$n", [])
  587. else:
  588. result.add(desc)
  589. result.add("};\L")
  590. if tfPacked in typ.flags and hasAttribute notin CC[m.config.cCompiler].props:
  591. result.add "#pragma pack(pop)\L"
  592. proc getTupleDesc(m: BModule, typ: PType, name: Rope,
  593. check: var IntSet): Rope =
  594. result = "$1 $2 {$n" % [structOrUnion(typ), name]
  595. var desc: Rope = nil
  596. for i in 0..<typ.len:
  597. desc.addf("$1 Field$2;$n",
  598. [getTypeDescAux(m, typ[i], check, skField), rope(i)])
  599. if desc == nil: result.add("char dummy;\L")
  600. else: result.add(desc)
  601. result.add("};\L")
  602. proc scanCppGenericSlot(pat: string, cursor, outIdx, outStars: var int): bool =
  603. # A helper proc for handling cppimport patterns, involving numeric
  604. # placeholders for generic types (e.g. '0, '**2, etc).
  605. # pre: the cursor must be placed at the ' symbol
  606. # post: the cursor will be placed after the final digit
  607. # false will returned if the input is not recognized as a placeholder
  608. inc cursor
  609. let begin = cursor
  610. while pat[cursor] == '*': inc cursor
  611. if pat[cursor] in Digits:
  612. outIdx = pat[cursor].ord - '0'.ord
  613. outStars = cursor - begin
  614. inc cursor
  615. return true
  616. else:
  617. return false
  618. proc resolveStarsInCppType(typ: PType, idx, stars: int): PType =
  619. # Make sure the index refers to one of the generic params of the type.
  620. # XXX: we should catch this earlier and report it as a semantic error.
  621. if idx >= typ.len:
  622. doAssert false, "invalid apostrophe type parameter index"
  623. result = typ[idx]
  624. for i in 1..stars:
  625. if result != nil and result.len > 0:
  626. result = if result.kind == tyGenericInst: result[1]
  627. else: result.elemType
  628. proc getOpenArrayDesc(m: BModule, t: PType, check: var IntSet; kind: TSymKind): Rope =
  629. let sig = hashType(t)
  630. if kind == skParam:
  631. result = getTypeDescWeak(m, t[0], check, kind) & "*"
  632. else:
  633. result = cacheGetType(m.typeCache, sig)
  634. if result == nil:
  635. result = getTypeName(m, t, sig)
  636. m.typeCache[sig] = result
  637. let elemType = getTypeDescWeak(m, t[0], check, kind)
  638. m.s[cfsTypes].addf("typedef struct {$n$2* Field0;$nNI Field1;$n} $1;$n",
  639. [result, elemType])
  640. proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKind): Rope =
  641. # returns only the type's name
  642. var t = origTyp.skipTypes(irrelevantForBackend-{tyOwned})
  643. if containsOrIncl(check, t.id):
  644. if not (isImportedCppType(origTyp) or isImportedCppType(t)):
  645. internalError(m.config, "cannot generate C type for: " & typeToString(origTyp))
  646. # XXX: this BUG is hard to fix -> we need to introduce helper structs,
  647. # but determining when this needs to be done is hard. We should split
  648. # C type generation into an analysis and a code generation phase somehow.
  649. if t.sym != nil: useHeader(m, t.sym)
  650. if t != origTyp and origTyp.sym != nil: useHeader(m, origTyp.sym)
  651. let sig = hashType(origTyp)
  652. defer: # defer is the simplest in this case
  653. if isImportedType(t) and not m.typeABICache.containsOrIncl(sig):
  654. addAbiCheck(m, t, result)
  655. result = getTypePre(m, t, sig)
  656. if result != nil and t.kind != tyOpenArray:
  657. excl(check, t.id)
  658. return
  659. case t.kind
  660. of tyRef, tyPtr, tyVar, tyLent:
  661. var star = if t.kind in {tyVar} and tfVarIsPtr notin origTyp.flags and
  662. compileToCpp(m): "&" else: "*"
  663. var et = origTyp.skipTypes(abstractInst).lastSon
  664. var etB = et.skipTypes(abstractInst)
  665. if mapType(m.config, t, kind) == ctPtrToArray and (etB.kind != tyOpenArray or kind == skParam):
  666. if etB.kind == tySet:
  667. et = getSysType(m.g.graph, unknownLineInfo, tyUInt8)
  668. else:
  669. et = elemType(etB)
  670. etB = et.skipTypes(abstractInst)
  671. star[0] = '*'
  672. case etB.kind
  673. of tyObject, tyTuple:
  674. if isImportedCppType(etB) and et.kind == tyGenericInst:
  675. result = getTypeDescAux(m, et, check, kind) & star
  676. else:
  677. # no restriction! We have a forward declaration for structs
  678. let name = getTypeForward(m, et, hashType et)
  679. result = name & star
  680. m.typeCache[sig] = result
  681. of tySequence:
  682. if optSeqDestructors in m.config.globalOptions:
  683. result = getTypeDescWeak(m, et, check, kind) & star
  684. m.typeCache[sig] = result
  685. else:
  686. # no restriction! We have a forward declaration for structs
  687. let name = getTypeForward(m, et, hashType et)
  688. result = name & seqStar(m) & star
  689. m.typeCache[sig] = result
  690. pushType(m, et)
  691. else:
  692. # else we have a strong dependency :-(
  693. result = getTypeDescAux(m, et, check, kind) & star
  694. m.typeCache[sig] = result
  695. of tyOpenArray, tyVarargs:
  696. result = getOpenArrayDesc(m, t, check, kind)
  697. of tyEnum:
  698. result = cacheGetType(m.typeCache, sig)
  699. if result == nil:
  700. result = getTypeName(m, origTyp, sig)
  701. if not (isImportedCppType(t) or
  702. (sfImportc in t.sym.flags and t.sym.magic == mNone)):
  703. m.typeCache[sig] = result
  704. var size: int
  705. if firstOrd(m.config, t) < 0:
  706. m.s[cfsTypes].addf("typedef NI32 $1;$n", [result])
  707. size = 4
  708. else:
  709. size = int(getSize(m.config, t))
  710. case size
  711. of 1: m.s[cfsTypes].addf("typedef NU8 $1;$n", [result])
  712. of 2: m.s[cfsTypes].addf("typedef NU16 $1;$n", [result])
  713. of 4: m.s[cfsTypes].addf("typedef NI32 $1;$n", [result])
  714. of 8: m.s[cfsTypes].addf("typedef NI64 $1;$n", [result])
  715. else: internalError(m.config, t.sym.info, "getTypeDescAux: enum")
  716. when false:
  717. let owner = hashOwner(t.sym)
  718. if not gDebugInfo.hasEnum(t.sym.name.s, t.sym.info.line, owner):
  719. var vals: seq[(string, int)] = @[]
  720. for i in 0..<t.n.len:
  721. assert(t.n[i].kind == nkSym)
  722. let field = t.n[i].sym
  723. vals.add((field.name.s, field.position.int))
  724. gDebugInfo.registerEnum(EnumDesc(size: size, owner: owner, id: t.sym.id,
  725. name: t.sym.name.s, values: vals))
  726. of tyProc:
  727. result = getTypeName(m, origTyp, sig)
  728. m.typeCache[sig] = result
  729. var rettype, desc: Rope
  730. genProcParams(m, t, rettype, desc, check, true, true)
  731. if not isImportedType(t):
  732. if t.callConv != ccClosure: # procedure vars may need a closure!
  733. m.s[cfsTypes].addf("typedef $1_PTR($2, $3) $4;$n",
  734. [rope(CallingConvToStr[t.callConv]), rettype, result, desc])
  735. else:
  736. m.s[cfsTypes].addf("typedef struct {$n" &
  737. "N_NIMCALL_PTR($2, ClP_0) $3;$n" &
  738. "void* ClE_0;$n} $1;$n",
  739. [result, rettype, desc])
  740. of tySequence:
  741. if optSeqDestructors in m.config.globalOptions:
  742. result = getTypeDescWeak(m, t, check, kind)
  743. else:
  744. # we cannot use getTypeForward here because then t would be associated
  745. # with the name of the struct, not with the pointer to the struct:
  746. result = cacheGetType(m.forwTypeCache, sig)
  747. if result == nil:
  748. result = getTypeName(m, origTyp, sig)
  749. if not isImportedType(t):
  750. addForwardStructFormat(m, structOrUnion(t), result)
  751. m.forwTypeCache[sig] = result
  752. assert(cacheGetType(m.typeCache, sig) == nil)
  753. m.typeCache[sig] = result & seqStar(m)
  754. if not isImportedType(t):
  755. if skipTypes(t[0], typedescInst).kind != tyEmpty:
  756. const
  757. cppSeq = "struct $2 : #TGenericSeq {$n"
  758. cSeq = "struct $2 {$n" &
  759. " #TGenericSeq Sup;$n"
  760. if m.compileToCpp:
  761. appcg(m, m.s[cfsSeqTypes],
  762. cppSeq & " $1 data[SEQ_DECL_SIZE];$n" &
  763. "};$n", [getTypeDescAux(m, t[0], check, kind), result])
  764. else:
  765. appcg(m, m.s[cfsSeqTypes],
  766. cSeq & " $1 data[SEQ_DECL_SIZE];$n" &
  767. "};$n", [getTypeDescAux(m, t[0], check, kind), result])
  768. else:
  769. result = rope("TGenericSeq")
  770. result.add(seqStar(m))
  771. of tyUncheckedArray:
  772. result = getTypeName(m, origTyp, sig)
  773. m.typeCache[sig] = result
  774. if not isImportedType(t):
  775. let foo = getTypeDescAux(m, t[0], check, kind)
  776. m.s[cfsTypes].addf("typedef $1 $2[1];$n", [foo, result])
  777. of tyArray:
  778. var n: BiggestInt = toInt64(lengthOrd(m.config, t))
  779. if n <= 0: n = 1 # make an array of at least one element
  780. result = getTypeName(m, origTyp, sig)
  781. m.typeCache[sig] = result
  782. if not isImportedType(t):
  783. let foo = getTypeDescAux(m, t[1], check, kind)
  784. m.s[cfsTypes].addf("typedef $1 $2[$3];$n",
  785. [foo, result, rope(n)])
  786. of tyObject, tyTuple:
  787. if isImportedCppType(t) and origTyp.kind == tyGenericInst:
  788. let cppName = getTypeName(m, t, sig)
  789. var i = 0
  790. var chunkStart = 0
  791. template addResultType(ty: untyped) =
  792. if ty == nil or ty.kind == tyVoid:
  793. result.add(~"void")
  794. elif ty.kind == tyStatic:
  795. internalAssert m.config, ty.n != nil
  796. result.add ty.n.renderTree
  797. else:
  798. result.add getTypeDescAux(m, ty, check, kind)
  799. while i < cppName.data.len:
  800. if cppName.data[i] == '\'':
  801. var chunkEnd = i-1
  802. var idx, stars: int
  803. if scanCppGenericSlot(cppName.data, i, idx, stars):
  804. result.add cppName.data.substr(chunkStart, chunkEnd)
  805. chunkStart = i
  806. let typeInSlot = resolveStarsInCppType(origTyp, idx + 1, stars)
  807. addResultType(typeInSlot)
  808. else:
  809. inc i
  810. if chunkStart != 0:
  811. result.add cppName.data.substr(chunkStart)
  812. else:
  813. result = cppName & "<"
  814. for i in 1..<origTyp.len-1:
  815. if i > 1: result.add(" COMMA ")
  816. addResultType(origTyp[i])
  817. result.add("> ")
  818. # always call for sideeffects:
  819. assert t.kind != tyTuple
  820. discard getRecordDesc(m, t, result, check)
  821. # The resulting type will include commas and these won't play well
  822. # with the C macros for defining procs such as N_NIMCALL. We must
  823. # create a typedef for the type and use it in the proc signature:
  824. let typedefName = ~"TY" & $sig
  825. m.s[cfsTypes].addf("typedef $1 $2;$n", [result, typedefName])
  826. m.typeCache[sig] = typedefName
  827. result = typedefName
  828. else:
  829. result = cacheGetType(m.forwTypeCache, sig)
  830. if result == nil:
  831. result = getTypeName(m, origTyp, sig)
  832. m.forwTypeCache[sig] = result
  833. if not isImportedType(t):
  834. addForwardStructFormat(m, structOrUnion(t), result)
  835. assert m.forwTypeCache[sig] == result
  836. m.typeCache[sig] = result # always call for sideeffects:
  837. if not incompleteType(t):
  838. let recdesc = if t.kind != tyTuple: getRecordDesc(m, t, result, check)
  839. else: getTupleDesc(m, t, result, check)
  840. if not isImportedType(t):
  841. m.s[cfsTypes].add(recdesc)
  842. elif tfIncompleteStruct notin t.flags:
  843. discard # addAbiCheck(m, t, result) # already handled elsewhere
  844. of tySet:
  845. # Don't use the imported name as it may be scoped: 'Foo::SomeKind'
  846. result = $t.kind & '_' & t.lastSon.typeName & $t.lastSon.hashType
  847. m.typeCache[sig] = result
  848. if not isImportedType(t):
  849. let s = int(getSize(m.config, t))
  850. case s
  851. of 1, 2, 4, 8: m.s[cfsTypes].addf("typedef NU$2 $1;$n", [result, rope(s*8)])
  852. else: m.s[cfsTypes].addf("typedef NU8 $1[$2];$n",
  853. [result, rope(getSize(m.config, t))])
  854. of tyGenericInst, tyDistinct, tyOrdinal, tyTypeDesc, tyAlias, tySink, tyOwned,
  855. tyUserTypeClass, tyUserTypeClassInst, tyInferred:
  856. result = getTypeDescAux(m, lastSon(t), check, kind)
  857. else:
  858. internalError(m.config, "getTypeDescAux(" & $t.kind & ')')
  859. result = nil
  860. # fixes bug #145:
  861. excl(check, t.id)
  862. proc getTypeDesc(m: BModule, typ: PType; kind = skParam): Rope =
  863. var check = initIntSet()
  864. result = getTypeDescAux(m, typ, check, kind)
  865. type
  866. TClosureTypeKind = enum ## In C closures are mapped to 3 different things.
  867. clHalf, ## fn(args) type without the trailing 'void* env' parameter
  868. clHalfWithEnv, ## fn(args, void* env) type with trailing 'void* env' parameter
  869. clFull ## struct {fn(args, void* env), env}
  870. proc getClosureType(m: BModule, t: PType, kind: TClosureTypeKind): Rope =
  871. assert t.kind == tyProc
  872. var check = initIntSet()
  873. result = getTempName(m)
  874. var rettype, desc: Rope
  875. genProcParams(m, t, rettype, desc, check, declareEnvironment=kind != clHalf)
  876. if not isImportedType(t):
  877. if t.callConv != ccClosure or kind != clFull:
  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. proc finishTypeDescriptions(m: BModule) =
  886. var i = 0
  887. var check = initIntSet()
  888. while i < m.typeStack.len:
  889. let t = m.typeStack[i]
  890. if optSeqDestructors in m.config.globalOptions and t.skipTypes(abstractInst).kind == tySequence:
  891. seqV2ContentType(m, t, check)
  892. else:
  893. discard getTypeDescAux(m, t, check, skParam)
  894. inc(i)
  895. m.typeStack.setLen 0
  896. template cgDeclFrmt*(s: PSym): string =
  897. s.constraint.strVal
  898. proc isReloadable(m: BModule, prc: PSym): bool =
  899. return m.hcrOn and sfNonReloadable notin prc.flags
  900. proc isNonReloadable(m: BModule, prc: PSym): bool =
  901. return m.hcrOn and sfNonReloadable in prc.flags
  902. proc genProcHeader(m: BModule, prc: PSym, asPtr: bool = false): Rope =
  903. var
  904. rettype, params: Rope
  905. # using static is needed for inline procs
  906. if lfExportLib in prc.loc.flags:
  907. if isHeaderFile in m.flags:
  908. result.add "N_LIB_IMPORT "
  909. else:
  910. result.add "N_LIB_EXPORT "
  911. elif prc.typ.callConv == ccInline or asPtr or isNonReloadable(m, prc):
  912. result.add "static "
  913. elif sfImportc notin prc.flags:
  914. result.add "N_LIB_PRIVATE "
  915. var check = initIntSet()
  916. fillLoc(prc.loc, locProc, prc.ast[namePos], mangleName(m, prc), OnUnknown)
  917. genProcParams(m, prc.typ, rettype, params, check)
  918. # handle the 2 options for hotcodereloading codegen - function pointer
  919. # (instead of forward declaration) or header for function body with "_actual" postfix
  920. let asPtrStr = rope(if asPtr: "_PTR" else: "")
  921. var name = prc.loc.r
  922. if isReloadable(m, prc) and not asPtr:
  923. name.add("_actual")
  924. # careful here! don't access ``prc.ast`` as that could reload large parts of
  925. # the object graph!
  926. if prc.constraint.isNil:
  927. result.addf("$1$2($3, $4)$5",
  928. [rope(CallingConvToStr[prc.typ.callConv]), asPtrStr, rettype, name,
  929. params])
  930. else:
  931. let asPtrStr = if asPtr: (rope("(*") & name & ")") else: name
  932. result = runtimeFormat(prc.cgDeclFrmt, [rettype, asPtrStr, params])
  933. # ------------------ type info generation -------------------------------------
  934. proc genTypeInfoV1(m: BModule, t: PType; info: TLineInfo): Rope
  935. proc getNimNode(m: BModule): Rope =
  936. result = "$1[$2]" % [m.typeNodesName, rope(m.typeNodes)]
  937. inc(m.typeNodes)
  938. proc tiNameForHcr(m: BModule, name: Rope): Rope =
  939. return if m.hcrOn: "(*".rope & name & ")" else: name
  940. proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
  941. name, base: Rope; info: TLineInfo) =
  942. var nimtypeKind: int
  943. #allocMemTI(m, typ, name)
  944. if isObjLackingTypeField(typ):
  945. nimtypeKind = ord(tyPureObject)
  946. else:
  947. nimtypeKind = ord(typ.kind)
  948. let nameHcr = tiNameForHcr(m, name)
  949. var size: Rope
  950. if tfIncompleteStruct in typ.flags:
  951. size = rope"void*"
  952. else:
  953. size = getTypeDesc(m, origType, skVar)
  954. m.s[cfsTypeInit3].addf(
  955. "$1.size = sizeof($2);$n$1.align = NIM_ALIGNOF($2);$n$1.kind = $3;$n$1.base = $4;$n",
  956. [nameHcr, size, rope(nimtypeKind), base]
  957. )
  958. # compute type flags for GC optimization
  959. var flags = 0
  960. if not containsGarbageCollectedRef(typ): flags = flags or 1
  961. if not canFormAcycle(typ): flags = flags or 2
  962. #else MessageOut("can contain a cycle: " & typeToString(typ))
  963. if flags != 0:
  964. m.s[cfsTypeInit3].addf("$1.flags = $2;$n", [nameHcr, rope(flags)])
  965. discard cgsym(m, "TNimType")
  966. if isDefined(m.config, "nimTypeNames"):
  967. var typename = typeToString(if origType.typeInst != nil: origType.typeInst
  968. else: origType, preferName)
  969. if typename == "ref object" and origType.skipTypes(skipPtrs).sym != nil:
  970. typename = "anon ref object from " & m.config$origType.skipTypes(skipPtrs).sym.info
  971. m.s[cfsTypeInit3].addf("$1.name = $2;$n",
  972. [nameHcr, makeCString typename])
  973. discard cgsym(m, "nimTypeRoot")
  974. m.s[cfsTypeInit3].addf("$1.nextType = nimTypeRoot; nimTypeRoot=&$1;$n",
  975. [nameHcr])
  976. if m.hcrOn:
  977. m.s[cfsData].addf("static TNimType* $1;$n", [name])
  978. m.hcrCreateTypeInfosProc.addf("\thcrRegisterGlobal($2, \"$1\", sizeof(TNimType), NULL, (void**)&$1);$n",
  979. [name, getModuleDllPath(m, m.module)])
  980. else:
  981. m.s[cfsData].addf("N_LIB_PRIVATE TNimType $1;$n", [name])
  982. proc genTypeInfoAux(m: BModule, typ, origType: PType, name: Rope;
  983. info: TLineInfo) =
  984. var base: Rope
  985. if typ.len > 0 and typ.lastSon != nil:
  986. var x = typ.lastSon
  987. if typ.kind == tyObject: x = x.skipTypes(skipPtrs)
  988. if typ.kind == tyPtr and x.kind == tyObject and incompleteType(x):
  989. base = rope("0")
  990. else:
  991. base = genTypeInfoV1(m, x, info)
  992. else:
  993. base = rope("0")
  994. genTypeInfoAuxBase(m, typ, origType, name, base, info)
  995. proc discriminatorTableName(m: BModule, objtype: PType, d: PSym): Rope =
  996. # bugfix: we need to search the type that contains the discriminator:
  997. var objtype = objtype.skipTypes(abstractPtrs)
  998. while lookupInRecord(objtype.n, d.name) == nil:
  999. objtype = objtype[0].skipTypes(abstractPtrs)
  1000. if objtype.sym == nil:
  1001. internalError(m.config, d.info, "anonymous obj with discriminator")
  1002. result = "NimDT_$1_$2" % [rope($hashType(objtype)), rope(d.name.s.mangle)]
  1003. proc rope(arg: Int128): Rope = rope($arg)
  1004. proc discriminatorTableDecl(m: BModule, objtype: PType, d: PSym): Rope =
  1005. discard cgsym(m, "TNimNode")
  1006. var tmp = discriminatorTableName(m, objtype, d)
  1007. result = "TNimNode* $1[$2];$n" % [tmp, rope(lengthOrd(m.config, d.typ)+1)]
  1008. proc genTNimNodeArray(m: BModule, name: Rope, size: Rope) =
  1009. if m.hcrOn:
  1010. m.s[cfsData].addf("static TNimNode** $1;$n", [name])
  1011. m.hcrCreateTypeInfosProc.addf("\thcrRegisterGlobal($3, \"$1\", sizeof(TNimNode*) * $2, NULL, (void**)&$1);$n",
  1012. [name, size, getModuleDllPath(m, m.module)])
  1013. else:
  1014. m.s[cfsTypeInit1].addf("static TNimNode* $1[$2];$n", [name, size])
  1015. proc genObjectFields(m: BModule, typ, origType: PType, n: PNode, expr: Rope;
  1016. info: TLineInfo) =
  1017. case n.kind
  1018. of nkRecList:
  1019. if n.len == 1:
  1020. genObjectFields(m, typ, origType, n[0], expr, info)
  1021. elif n.len > 0:
  1022. var tmp = getTempName(m) & "_" & $n.len
  1023. genTNimNodeArray(m, tmp, rope(n.len))
  1024. for i in 0..<n.len:
  1025. var tmp2 = getNimNode(m)
  1026. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(i), tmp2])
  1027. genObjectFields(m, typ, origType, n[i], tmp2, info)
  1028. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n",
  1029. [expr, rope(n.len), tmp])
  1030. else:
  1031. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2;$n", [expr, rope(n.len)])
  1032. of nkRecCase:
  1033. assert(n[0].kind == nkSym)
  1034. var field = n[0].sym
  1035. var tmp = discriminatorTableName(m, typ, field)
  1036. var L = lengthOrd(m.config, field.typ)
  1037. assert L > 0
  1038. if field.loc.r == nil: fillObjectFields(m, typ)
  1039. if field.loc.t == nil:
  1040. internalError(m.config, n.info, "genObjectFields")
  1041. m.s[cfsTypeInit3].addf("$1.kind = 3;$n" &
  1042. "$1.offset = offsetof($2, $3);$n" & "$1.typ = $4;$n" &
  1043. "$1.name = $5;$n" & "$1.sons = &$6[0];$n" &
  1044. "$1.len = $7;$n", [expr, getTypeDesc(m, origType, skVar), field.loc.r,
  1045. genTypeInfoV1(m, field.typ, info),
  1046. makeCString(field.name.s),
  1047. tmp, rope(L)])
  1048. m.s[cfsData].addf("TNimNode* $1[$2];$n", [tmp, rope(L+1)])
  1049. for i in 1..<n.len:
  1050. var b = n[i] # branch
  1051. var tmp2 = getNimNode(m)
  1052. genObjectFields(m, typ, origType, lastSon(b), tmp2, info)
  1053. case b.kind
  1054. of nkOfBranch:
  1055. if b.len < 2:
  1056. internalError(m.config, b.info, "genObjectFields; nkOfBranch broken")
  1057. for j in 0..<b.len - 1:
  1058. if b[j].kind == nkRange:
  1059. var x = toInt(getOrdValue(b[j][0]))
  1060. var y = toInt(getOrdValue(b[j][1]))
  1061. while x <= y:
  1062. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(x), tmp2])
  1063. inc(x)
  1064. else:
  1065. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n",
  1066. [tmp, rope(getOrdValue(b[j])), tmp2])
  1067. of nkElse:
  1068. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n",
  1069. [tmp, rope(L), tmp2])
  1070. else: internalError(m.config, n.info, "genObjectFields(nkRecCase)")
  1071. of nkSym:
  1072. var field = n.sym
  1073. # Do not produce code for void types
  1074. if isEmptyType(field.typ): return
  1075. if field.bitsize == 0:
  1076. if field.loc.r == nil: fillObjectFields(m, typ)
  1077. if field.loc.t == nil:
  1078. internalError(m.config, n.info, "genObjectFields")
  1079. m.s[cfsTypeInit3].addf("$1.kind = 1;$n" &
  1080. "$1.offset = offsetof($2, $3);$n" & "$1.typ = $4;$n" &
  1081. "$1.name = $5;$n", [expr, getTypeDesc(m, origType, skVar),
  1082. field.loc.r, genTypeInfoV1(m, field.typ, info), makeCString(field.name.s)])
  1083. else: internalError(m.config, n.info, "genObjectFields")
  1084. proc genObjectInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo) =
  1085. if typ.kind == tyObject:
  1086. if incompleteType(typ):
  1087. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1088. typeToString(typ))
  1089. genTypeInfoAux(m, typ, origType, name, info)
  1090. else:
  1091. genTypeInfoAuxBase(m, typ, origType, name, rope("0"), info)
  1092. var tmp = getNimNode(m)
  1093. if not isImportedType(typ):
  1094. genObjectFields(m, typ, origType, typ.n, tmp, info)
  1095. m.s[cfsTypeInit3].addf("$1.node = &$2;$n", [tiNameForHcr(m, name), tmp])
  1096. var t = typ[0]
  1097. while t != nil:
  1098. t = t.skipTypes(skipPtrs)
  1099. t.flags.incl tfObjHasKids
  1100. t = t[0]
  1101. proc genTupleInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo) =
  1102. genTypeInfoAuxBase(m, typ, typ, name, rope("0"), info)
  1103. var expr = getNimNode(m)
  1104. if typ.len > 0:
  1105. var tmp = getTempName(m) & "_" & $typ.len
  1106. genTNimNodeArray(m, tmp, rope(typ.len))
  1107. for i in 0..<typ.len:
  1108. var a = typ[i]
  1109. var tmp2 = getNimNode(m)
  1110. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(i), tmp2])
  1111. m.s[cfsTypeInit3].addf("$1.kind = 1;$n" &
  1112. "$1.offset = offsetof($2, Field$3);$n" &
  1113. "$1.typ = $4;$n" &
  1114. "$1.name = \"Field$3\";$n",
  1115. [tmp2, getTypeDesc(m, origType, skVar), rope(i), genTypeInfoV1(m, a, info)])
  1116. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n",
  1117. [expr, rope(typ.len), tmp])
  1118. else:
  1119. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2;$n",
  1120. [expr, rope(typ.len)])
  1121. m.s[cfsTypeInit3].addf("$1.node = &$2;$n", [tiNameForHcr(m, name), expr])
  1122. proc genEnumInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1123. # Type information for enumerations is quite heavy, so we do some
  1124. # optimizations here: The ``typ`` field is never set, as it is redundant
  1125. # anyway. We generate a cstring array and a loop over it. Exceptional
  1126. # positions will be reset after the loop.
  1127. genTypeInfoAux(m, typ, typ, name, info)
  1128. var nodePtrs = getTempName(m) & "_" & $typ.n.len
  1129. genTNimNodeArray(m, nodePtrs, rope(typ.n.len))
  1130. var enumNames, specialCases: Rope
  1131. var firstNimNode = m.typeNodes
  1132. var hasHoles = false
  1133. for i in 0..<typ.n.len:
  1134. assert(typ.n[i].kind == nkSym)
  1135. var field = typ.n[i].sym
  1136. var elemNode = getNimNode(m)
  1137. if field.ast == nil:
  1138. # no explicit string literal for the enum field, so use field.name:
  1139. enumNames.add(makeCString(field.name.s))
  1140. else:
  1141. enumNames.add(makeCString(field.ast.strVal))
  1142. if i < typ.n.len - 1: enumNames.add(", \L")
  1143. if field.position != i or tfEnumHasHoles in typ.flags:
  1144. specialCases.addf("$1.offset = $2;$n", [elemNode, rope(field.position)])
  1145. hasHoles = true
  1146. var enumArray = getTempName(m)
  1147. var counter = getTempName(m)
  1148. m.s[cfsTypeInit1].addf("NI $1;$n", [counter])
  1149. m.s[cfsTypeInit1].addf("static char* NIM_CONST $1[$2] = {$n$3};$n",
  1150. [enumArray, rope(typ.n.len), enumNames])
  1151. m.s[cfsTypeInit3].addf("for ($1 = 0; $1 < $2; $1++) {$n" &
  1152. "$3[$1+$4].kind = 1;$n" & "$3[$1+$4].offset = $1;$n" &
  1153. "$3[$1+$4].name = $5[$1];$n" & "$6[$1] = &$3[$1+$4];$n" & "}$n", [counter,
  1154. rope(typ.n.len), m.typeNodesName, rope(firstNimNode), enumArray, nodePtrs])
  1155. m.s[cfsTypeInit3].add(specialCases)
  1156. m.s[cfsTypeInit3].addf(
  1157. "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n",
  1158. [getNimNode(m), rope(typ.n.len), nodePtrs, tiNameForHcr(m, name)])
  1159. if hasHoles:
  1160. # 1 << 2 is {ntfEnumHole}
  1161. m.s[cfsTypeInit3].addf("$1.flags = 1<<2;$n", [tiNameForHcr(m, name)])
  1162. proc genSetInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1163. assert(typ[0] != nil)
  1164. genTypeInfoAux(m, typ, typ, name, info)
  1165. var tmp = getNimNode(m)
  1166. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 0;$n" & "$3.node = &$1;$n",
  1167. [tmp, rope(firstOrd(m.config, typ)), tiNameForHcr(m, name)])
  1168. proc genArrayInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1169. genTypeInfoAuxBase(m, typ, typ, name, genTypeInfoV1(m, typ[1], info), info)
  1170. proc fakeClosureType(m: BModule; owner: PSym): PType =
  1171. # we generate the same RTTI as for a tuple[pointer, ref tuple[]]
  1172. result = newType(tyTuple, owner)
  1173. result.rawAddSon(newType(tyPointer, owner))
  1174. var r = newType(tyRef, owner)
  1175. let obj = createObj(m.g.graph, owner, owner.info, final=false)
  1176. r.rawAddSon(obj)
  1177. result.rawAddSon(r)
  1178. include ccgtrav
  1179. proc genDeepCopyProc(m: BModule; s: PSym; result: Rope) =
  1180. genProc(m, s)
  1181. m.s[cfsTypeInit3].addf("$1.deepcopy =(void* (N_RAW_NIMCALL*)(void*))$2;$n",
  1182. [result, s.loc.r])
  1183. proc declareNimType(m: BModule, name: string; str: Rope, ownerModule: PSym) =
  1184. let nr = rope(name)
  1185. if m.hcrOn:
  1186. m.s[cfsData].addf("static $2* $1;$n", [str, nr])
  1187. m.s[cfsTypeInit1].addf("\t$1 = ($3*)hcrGetGlobal($2, \"$1\");$n",
  1188. [str, getModuleDllPath(m, ownerModule), nr])
  1189. else:
  1190. m.s[cfsData].addf("extern $2 $1;$n", [str, nr])
  1191. proc genTypeInfo2Name(m: BModule; t: PType): Rope =
  1192. var res = "|"
  1193. var it = t
  1194. while it != nil:
  1195. it = it.skipTypes(skipPtrs)
  1196. if it.sym != nil:
  1197. var m = it.sym.owner
  1198. while m != nil and m.kind != skModule: m = m.owner
  1199. if m == nil or sfSystemModule in m.flags:
  1200. # produce short names for system types:
  1201. res.add it.sym.name.s
  1202. else:
  1203. var p = m.owner
  1204. if p != nil and p.kind == skPackage:
  1205. res.add p.name.s & "."
  1206. res.add m.name.s & "."
  1207. res.add it.sym.name.s
  1208. else:
  1209. res.add $hashType(it)
  1210. res.add "|"
  1211. it = it[0]
  1212. result = makeCString(res)
  1213. proc isTrivialProc(s: PSym): bool {.inline.} = s.ast[bodyPos].len == 0
  1214. proc genHook(m: BModule; t: PType; info: TLineInfo; op: TTypeAttachedOp): Rope =
  1215. let theProc = t.attachedOps[op]
  1216. if theProc != nil and not isTrivialProc(theProc):
  1217. # the prototype of a destructor is ``=destroy(x: var T)`` and that of a
  1218. # finalizer is: ``proc (x: ref T) {.nimcall.}``. We need to check the calling
  1219. # convention at least:
  1220. if theProc.typ == nil or theProc.typ.callConv != ccNimCall:
  1221. localError(m.config, info,
  1222. theProc.name.s & " needs to have the 'nimcall' calling convention")
  1223. genProc(m, theProc)
  1224. result = theProc.loc.r
  1225. else:
  1226. when false:
  1227. if op == attachedTrace and m.config.selectedGC == gcOrc and
  1228. containsGarbageCollectedRef(t):
  1229. # unfortunately this check is wrong for an object type that only contains
  1230. # .cursor fields like 'Node' inside 'cycleleak'.
  1231. internalError(m.config, info, "no attached trace proc found")
  1232. result = rope("NIM_NIL")
  1233. proc genTypeInfoV2Impl(m: BModule, t, origType: PType, name: Rope; info: TLineInfo) =
  1234. var typeName: Rope
  1235. if t.kind == tyObject:
  1236. if incompleteType(t):
  1237. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1238. typeToString(t))
  1239. typeName = genTypeInfo2Name(m, t)
  1240. else:
  1241. typeName = rope("NIM_NIL")
  1242. discard cgsym(m, "TNimTypeV2")
  1243. m.s[cfsData].addf("N_LIB_PRIVATE TNimTypeV2 $1;$n", [name])
  1244. let destroyImpl = genHook(m, t, info, attachedDestructor)
  1245. let traceImpl = genHook(m, t, info, attachedTrace)
  1246. let disposeImpl = genHook(m, t, info, attachedDispose)
  1247. addf(m.s[cfsTypeInit3], "$1.destructor = (void*)$2; $1.size = sizeof($3); $1.align = NIM_ALIGNOF($3); $1.name = $4;$n; $1.traceImpl = (void*)$5; $1.disposeImpl = (void*)$6;", [
  1248. name, destroyImpl, getTypeDesc(m, t), typeName,
  1249. traceImpl, disposeImpl])
  1250. proc genTypeInfoV2(m: BModule, t: PType; info: TLineInfo): Rope =
  1251. let origType = t
  1252. var t = skipTypes(origType, irrelevantForBackend + tyUserTypeClasses)
  1253. let prefixTI = if m.hcrOn: "(" else: "(&"
  1254. let sig = hashType(origType)
  1255. result = m.typeInfoMarkerV2.getOrDefault(sig)
  1256. if result != nil:
  1257. return prefixTI.rope & result & ")".rope
  1258. let marker = m.g.typeInfoMarkerV2.getOrDefault(sig)
  1259. if marker.str != nil:
  1260. discard cgsym(m, "TNimTypeV2")
  1261. declareNimType(m, "TNimTypeV2", marker.str, marker.owner)
  1262. # also store in local type section:
  1263. m.typeInfoMarkerV2[sig] = marker.str
  1264. return prefixTI.rope & marker.str & ")".rope
  1265. result = "NTIv2$1_" % [rope($sig)]
  1266. m.typeInfoMarkerV2[sig] = result
  1267. let owner = t.skipTypes(typedescPtrs).owner.getModule
  1268. if owner != m.module:
  1269. # make sure the type info is created in the owner module
  1270. assert m.g.modules[owner.position] != nil
  1271. discard genTypeInfoV2(m.g.modules[owner.position], origType, info)
  1272. # reference the type info as extern here
  1273. discard cgsym(m, "TNimTypeV2")
  1274. declareNimType(m, "TNimTypeV2", result, owner)
  1275. return prefixTI.rope & result & ")".rope
  1276. m.g.typeInfoMarkerV2[sig] = (str: result, owner: owner)
  1277. genTypeInfoV2Impl(m, t, origType, result, info)
  1278. result = prefixTI.rope & result & ")".rope
  1279. proc openArrayToTuple(m: BModule; t: PType): PType =
  1280. result = newType(tyTuple, t.owner)
  1281. let p = newType(tyPtr, t.owner)
  1282. let a = newType(tyUncheckedArray, t.owner)
  1283. a.add t.lastSon
  1284. p.add a
  1285. result.add p
  1286. result.add getSysType(m.g.graph, t.owner.info, tyInt)
  1287. proc genTypeInfoV1(m: BModule, t: PType; info: TLineInfo): Rope =
  1288. let origType = t
  1289. var t = skipTypes(origType, irrelevantForBackend + tyUserTypeClasses)
  1290. let prefixTI = if m.hcrOn: "(" else: "(&"
  1291. let sig = hashType(origType)
  1292. result = m.typeInfoMarker.getOrDefault(sig)
  1293. if result != nil:
  1294. return prefixTI.rope & result & ")".rope
  1295. let marker = m.g.typeInfoMarker.getOrDefault(sig)
  1296. if marker.str != nil:
  1297. discard cgsym(m, "TNimType")
  1298. discard cgsym(m, "TNimNode")
  1299. declareNimType(m, "TNimType", marker.str, marker.owner)
  1300. # also store in local type section:
  1301. m.typeInfoMarker[sig] = marker.str
  1302. return prefixTI.rope & marker.str & ")".rope
  1303. result = "NTI$1_" % [rope($sig)]
  1304. m.typeInfoMarker[sig] = result
  1305. let owner = t.skipTypes(typedescPtrs).owner.getModule
  1306. if owner != m.module:
  1307. # make sure the type info is created in the owner module
  1308. assert m.g.modules[owner.position] != nil
  1309. discard genTypeInfoV1(m.g.modules[owner.position], origType, info)
  1310. # reference the type info as extern here
  1311. discard cgsym(m, "TNimType")
  1312. discard cgsym(m, "TNimNode")
  1313. declareNimType(m, "TNimType", result, owner)
  1314. return prefixTI.rope & result & ")".rope
  1315. m.g.typeInfoMarker[sig] = (str: result, owner: owner)
  1316. case t.kind
  1317. of tyEmpty, tyVoid: result = rope"0"
  1318. of tyPointer, tyBool, tyChar, tyCString, tyString, tyInt..tyUInt64, tyVar, tyLent:
  1319. genTypeInfoAuxBase(m, t, t, result, rope"0", info)
  1320. of tyStatic:
  1321. if t.n != nil: result = genTypeInfoV1(m, lastSon t, info)
  1322. else: internalError(m.config, "genTypeInfoV1(" & $t.kind & ')')
  1323. of tyUserTypeClasses:
  1324. internalAssert m.config, t.isResolvedUserTypeClass
  1325. return genTypeInfoV1(m, t.lastSon, info)
  1326. of tyProc:
  1327. if t.callConv != ccClosure:
  1328. genTypeInfoAuxBase(m, t, t, result, rope"0", info)
  1329. else:
  1330. let x = fakeClosureType(m, t.owner)
  1331. genTupleInfo(m, x, x, result, info)
  1332. of tySequence:
  1333. genTypeInfoAux(m, t, t, result, info)
  1334. if m.config.selectedGC >= gcMarkAndSweep:
  1335. let markerProc = genTraverseProc(m, origType, sig)
  1336. m.s[cfsTypeInit3].addf("$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
  1337. of tyRef:
  1338. genTypeInfoAux(m, t, t, result, info)
  1339. if m.config.selectedGC >= gcMarkAndSweep:
  1340. let markerProc = genTraverseProc(m, origType, sig)
  1341. m.s[cfsTypeInit3].addf("$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
  1342. of tyPtr, tyRange, tyUncheckedArray: genTypeInfoAux(m, t, t, result, info)
  1343. of tyArray: genArrayInfo(m, t, result, info)
  1344. of tySet: genSetInfo(m, t, result, info)
  1345. of tyEnum: genEnumInfo(m, t, result, info)
  1346. of tyObject:
  1347. genObjectInfo(m, t, origType, result, info)
  1348. of tyTuple:
  1349. # if t.n != nil: genObjectInfo(m, t, result)
  1350. # else:
  1351. # BUGFIX: use consistently RTTI without proper field names; otherwise
  1352. # results are not deterministic!
  1353. genTupleInfo(m, t, origType, result, info)
  1354. of tyOpenArray:
  1355. let x = openArrayToTuple(m, t)
  1356. genTupleInfo(m, x, origType, result, info)
  1357. else: internalError(m.config, "genTypeInfoV1(" & $t.kind & ')')
  1358. if t.attachedOps[attachedDeepCopy] != nil:
  1359. genDeepCopyProc(m, t.attachedOps[attachedDeepCopy], result)
  1360. elif origType.attachedOps[attachedDeepCopy] != nil:
  1361. genDeepCopyProc(m, origType.attachedOps[attachedDeepCopy], result)
  1362. if optTinyRtti in m.config.globalOptions and t.kind == tyObject:
  1363. let v2info = genTypeInfoV2(m, origType, info)
  1364. addf(m.s[cfsTypeInit3], "$1->typeInfoV1 = (void*)&$2; $2.typeInfoV2 = (void*)$1;$n", [
  1365. v2info, result])
  1366. result = prefixTI.rope & result & ")".rope
  1367. proc genTypeSection(m: BModule, n: PNode) =
  1368. discard