ccgtypes.nim 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  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 = not (pt.kind in {tyVar, tyArray, tyOpenArray, tyVarargs, tyRef, tyPtr, tyPointer} or
  258. pt.kind == tySet and mapSetType(conf, pt) == ctArray)
  259. proc fillResult(conf: ConfigRef; param: PNode) =
  260. fillLoc(param.sym.loc, locParam, param, ~"Result",
  261. OnStack)
  262. let t = param.sym.typ
  263. if mapReturnType(conf, t) != ctArray and isInvalidReturnType(conf, t):
  264. incl(param.sym.loc.flags, lfIndirect)
  265. param.sym.loc.storage = OnUnknown
  266. proc typeNameOrLiteral(m: BModule; t: PType, literal: string): Rope =
  267. if t.sym != nil and sfImportc in t.sym.flags and t.sym.magic == mNone:
  268. useHeader(m, t.sym)
  269. result = t.sym.loc.r
  270. else:
  271. result = rope(literal)
  272. proc getSimpleTypeDesc(m: BModule, typ: PType): Rope =
  273. const
  274. NumericalTypeToStr: array[tyInt..tyUInt64, string] = [
  275. "NI", "NI8", "NI16", "NI32", "NI64",
  276. "NF", "NF32", "NF64", "NF128",
  277. "NU", "NU8", "NU16", "NU32", "NU64"]
  278. case typ.kind
  279. of tyPointer:
  280. result = typeNameOrLiteral(m, typ, "void*")
  281. of tyString:
  282. case detectStrVersion(m)
  283. of 2:
  284. discard cgsym(m, "NimStrPayload")
  285. discard cgsym(m, "NimStringV2")
  286. result = typeNameOrLiteral(m, typ, "NimStringV2")
  287. else:
  288. discard cgsym(m, "NimStringDesc")
  289. result = typeNameOrLiteral(m, typ, "NimStringDesc*")
  290. of tyCString: result = typeNameOrLiteral(m, typ, "NCSTRING")
  291. of tyBool: result = typeNameOrLiteral(m, typ, "NIM_BOOL")
  292. of tyChar: result = typeNameOrLiteral(m, typ, "NIM_CHAR")
  293. of tyNil: result = typeNameOrLiteral(m, typ, "void*")
  294. of tyInt..tyUInt64:
  295. result = typeNameOrLiteral(m, typ, NumericalTypeToStr[typ.kind])
  296. of tyDistinct, tyRange, tyOrdinal: result = getSimpleTypeDesc(m, typ[0])
  297. of tyStatic:
  298. if typ.n != nil: result = getSimpleTypeDesc(m, lastSon typ)
  299. else: internalError(m.config, "tyStatic for getSimpleTypeDesc")
  300. of tyGenericInst, tyAlias, tySink, tyOwned:
  301. result = getSimpleTypeDesc(m, lastSon typ)
  302. else: result = nil
  303. if result != nil and typ.isImportedType():
  304. let sig = hashType typ
  305. if cacheGetType(m.typeCache, sig) == nil:
  306. m.typeCache[sig] = result
  307. proc pushType(m: BModule, typ: PType) =
  308. for i in 0..high(m.typeStack):
  309. # pointer equality is good enough here:
  310. if m.typeStack[i] == typ: return
  311. m.typeStack.add(typ)
  312. proc getTypePre(m: BModule, typ: PType; sig: SigHash): Rope =
  313. if typ == nil: result = rope("void")
  314. else:
  315. result = getSimpleTypeDesc(m, typ)
  316. if result == nil: result = cacheGetType(m.typeCache, sig)
  317. proc structOrUnion(t: PType): Rope =
  318. let cachedUnion = rope("union")
  319. let cachedStruct = rope("struct")
  320. let t = t.skipTypes({tyAlias, tySink})
  321. if tfUnion in t.flags: cachedUnion
  322. else: cachedStruct
  323. proc addForwardStructFormat(m: BModule, structOrUnion: Rope, typename: Rope) =
  324. if m.compileToCpp:
  325. m.s[cfsForwardTypes].addf "$1 $2;$n", [structOrUnion, typename]
  326. else:
  327. m.s[cfsForwardTypes].addf "typedef $1 $2 $2;$n", [structOrUnion, typename]
  328. proc seqStar(m: BModule): string =
  329. if optSeqDestructors in m.config.globalOptions: result = ""
  330. else: result = "*"
  331. proc getTypeForward(m: BModule, typ: PType; sig: SigHash): Rope =
  332. result = cacheGetType(m.forwTypeCache, sig)
  333. if result != nil: return
  334. result = getTypePre(m, typ, sig)
  335. if result != nil: return
  336. let concrete = typ.skipTypes(abstractInst)
  337. case concrete.kind
  338. of tySequence, tyTuple, tyObject:
  339. result = getTypeName(m, typ, sig)
  340. m.forwTypeCache[sig] = result
  341. if not isImportedType(concrete):
  342. addForwardStructFormat(m, structOrUnion(typ), result)
  343. else:
  344. pushType(m, concrete)
  345. doAssert m.forwTypeCache[sig] == result
  346. else: internalError(m.config, "getTypeForward(" & $typ.kind & ')')
  347. proc getTypeDescWeak(m: BModule; t: PType; check: var IntSet; kind: TSymKind): Rope =
  348. ## like getTypeDescAux but creates only a *weak* dependency. In other words
  349. ## we know we only need a pointer to it so we only generate a struct forward
  350. ## declaration:
  351. let etB = t.skipTypes(abstractInst)
  352. case etB.kind
  353. of tyObject, tyTuple:
  354. if isImportedCppType(etB) and t.kind == tyGenericInst:
  355. result = getTypeDescAux(m, t, check, kind)
  356. else:
  357. result = getTypeForward(m, t, hashType(t))
  358. pushType(m, t)
  359. of tySequence:
  360. let sig = hashType(t)
  361. if optSeqDestructors in m.config.globalOptions:
  362. if skipTypes(etB[0], typedescInst).kind == tyEmpty:
  363. internalError(m.config, "cannot map the empty seq type to a C type")
  364. result = cacheGetType(m.forwTypeCache, sig)
  365. if result == nil:
  366. result = getTypeName(m, t, sig)
  367. if not isImportedType(t):
  368. m.forwTypeCache[sig] = result
  369. addForwardStructFormat(m, rope"struct", result)
  370. let payload = result & "_Content"
  371. addForwardStructFormat(m, rope"struct", payload)
  372. if cacheGetType(m.typeCache, sig) == nil:
  373. m.typeCache[sig] = result
  374. #echo "adding ", sig, " ", typeToString(t), " ", m.module.name.s
  375. appcg(m, m.s[cfsTypes],
  376. "struct $1 {$N" &
  377. " NI len; $1_Content* p;$N" &
  378. "};$N", [result])
  379. else:
  380. result = getTypeForward(m, t, sig) & seqStar(m)
  381. pushType(m, t)
  382. else:
  383. result = getTypeDescAux(m, t, check, kind)
  384. proc getSeqPayloadType(m: BModule; t: PType): Rope =
  385. var check = initIntSet()
  386. result = getTypeDescWeak(m, t, check, skParam) & "_Content"
  387. #result = getTypeForward(m, t, hashType(t)) & "_Content"
  388. proc seqV2ContentType(m: BModule; t: PType; check: var IntSet) =
  389. let sig = hashType(t)
  390. let result = cacheGetType(m.typeCache, sig)
  391. if result == nil:
  392. discard getTypeDescAux(m, t, check, skVar)
  393. else:
  394. # little hack for now to prevent multiple definitions of the same
  395. # Seq_Content:
  396. appcg(m, m.s[cfsTypes], """$N
  397. $3ifndef $2_Content_PP
  398. $3define $2_Content_PP
  399. struct $2_Content { NI cap; $1 data[SEQ_DECL_SIZE];};
  400. $3endif$N
  401. """, [getTypeDescAux(m, t.skipTypes(abstractInst)[0], check, skVar), result, rope"#"])
  402. proc paramStorageLoc(param: PSym): TStorageLoc =
  403. if param.typ.skipTypes({tyVar, tyLent, tyTypeDesc}).kind notin {
  404. tyArray, tyOpenArray, tyVarargs}:
  405. result = OnStack
  406. else:
  407. result = OnUnknown
  408. proc genProcParams(m: BModule, t: PType, rettype, params: var Rope,
  409. check: var IntSet, declareEnvironment=true;
  410. weakDep=false) =
  411. params = nil
  412. if t[0] == nil or isInvalidReturnType(m.config, t[0]):
  413. rettype = ~"void"
  414. else:
  415. rettype = getTypeDescAux(m, t[0], check, skResult)
  416. for i in 1..<t.n.len:
  417. if t.n[i].kind != nkSym: internalError(m.config, t.n.info, "genProcParams")
  418. var param = t.n[i].sym
  419. if isCompileTimeOnly(param.typ): continue
  420. if params != nil: params.add(~", ")
  421. fillLoc(param.loc, locParam, t.n[i], mangleParamName(m, param),
  422. param.paramStorageLoc)
  423. if ccgIntroducedPtr(m.config, param, t[0]):
  424. params.add(getTypeDescWeak(m, param.typ, check, skParam))
  425. params.add(~"*")
  426. incl(param.loc.flags, lfIndirect)
  427. param.loc.storage = OnUnknown
  428. elif weakDep:
  429. params.add(getTypeDescWeak(m, param.typ, check, skParam))
  430. else:
  431. params.add(getTypeDescAux(m, param.typ, check, skParam))
  432. params.add(~" ")
  433. if sfNoalias in param.flags:
  434. params.add(~"NIM_NOALIAS ")
  435. params.add(param.loc.r)
  436. # declare the len field for open arrays:
  437. var arr = param.typ
  438. if arr.kind in {tyVar, tyLent, tySink}: arr = arr.lastSon
  439. var j = 0
  440. while arr.kind in {tyOpenArray, tyVarargs}:
  441. # this fixes the 'sort' bug:
  442. if param.typ.kind in {tyVar, tyLent}: param.loc.storage = OnUnknown
  443. # need to pass hidden parameter:
  444. params.addf(", NI $1Len_$2", [param.loc.r, j.rope])
  445. inc(j)
  446. arr = arr[0].skipTypes({tySink})
  447. if t[0] != nil and isInvalidReturnType(m.config, t[0]):
  448. var arr = t[0]
  449. if params != nil: params.add(", ")
  450. if mapReturnType(m.config, t[0]) != ctArray:
  451. params.add(getTypeDescWeak(m, arr, check, skResult))
  452. params.add("*")
  453. else:
  454. params.add(getTypeDescAux(m, arr, check, skResult))
  455. params.addf(" Result", [])
  456. if t.callConv == ccClosure and declareEnvironment:
  457. if params != nil: params.add(", ")
  458. params.add("void* ClE_0")
  459. if tfVarargs in t.flags:
  460. if params != nil: params.add(", ")
  461. params.add("...")
  462. if params == nil: params.add("void)")
  463. else: params.add(")")
  464. params = "(" & params
  465. proc mangleRecFieldName(m: BModule; field: PSym): Rope =
  466. if {sfImportc, sfExportc} * field.flags != {}:
  467. result = field.loc.r
  468. else:
  469. result = rope(mangleField(m, field.name))
  470. if result == nil: internalError(m.config, field.info, "mangleRecFieldName")
  471. proc genRecordFieldsAux(m: BModule, n: PNode,
  472. rectype: PType,
  473. check: var IntSet, unionPrefix = ""): Rope =
  474. result = nil
  475. case n.kind
  476. of nkRecList:
  477. for i in 0..<n.len:
  478. result.add(genRecordFieldsAux(m, n[i], rectype, check, unionPrefix))
  479. of nkRecCase:
  480. if n[0].kind != nkSym: internalError(m.config, n.info, "genRecordFieldsAux")
  481. result.add(genRecordFieldsAux(m, n[0], rectype, check, unionPrefix))
  482. # prefix mangled name with "_U" to avoid clashes with other field names,
  483. # since identifiers are not allowed to start with '_'
  484. var unionBody: Rope = nil
  485. for i in 1..<n.len:
  486. case n[i].kind
  487. of nkOfBranch, nkElse:
  488. let k = lastSon(n[i])
  489. if k.kind != nkSym:
  490. let structName = "_" & mangleRecFieldName(m, n[0].sym) & "_" & $i
  491. let a = genRecordFieldsAux(m, k, rectype, check, unionPrefix & $structName & ".")
  492. if a != nil:
  493. if tfPacked notin rectype.flags:
  494. unionBody.add("struct {")
  495. else:
  496. if hasAttribute in CC[m.config.cCompiler].props:
  497. unionBody.add("struct __attribute__((__packed__)){")
  498. else:
  499. unionBody.addf("#pragma pack(push, 1)$nstruct{", [])
  500. unionBody.add(a)
  501. unionBody.addf("} $1;$n", [structName])
  502. if tfPacked in rectype.flags and hasAttribute notin CC[m.config.cCompiler].props:
  503. unionBody.addf("#pragma pack(pop)$n", [])
  504. else:
  505. unionBody.add(genRecordFieldsAux(m, k, rectype, check, unionPrefix))
  506. else: internalError(m.config, "genRecordFieldsAux(record case branch)")
  507. if unionBody != nil:
  508. result.addf("union{$n$1};$n", [unionBody])
  509. of nkSym:
  510. let field = n.sym
  511. if field.typ.kind == tyVoid: return
  512. #assert(field.ast == nil)
  513. let sname = mangleRecFieldName(m, field)
  514. fillLoc(field.loc, locField, n, unionPrefix & sname, OnUnknown)
  515. if field.alignment > 0:
  516. result.addf "NIM_ALIGN($1) ", [rope(field.alignment)]
  517. # for importcpp'ed objects, we only need to set field.loc, but don't
  518. # have to recurse via 'getTypeDescAux'. And not doing so prevents problems
  519. # with heavily templatized C++ code:
  520. if not isImportedCppType(rectype):
  521. let noAlias = if sfNoalias in field.flags: ~" NIM_NOALIAS" else: nil
  522. let fieldType = field.loc.lode.typ.skipTypes(abstractInst)
  523. if fieldType.kind == tyUncheckedArray:
  524. result.addf("$1 $2[SEQ_DECL_SIZE];$n",
  525. [getTypeDescAux(m, fieldType.elemType, check, skField), sname])
  526. elif fieldType.kind == tySequence:
  527. # we need to use a weak dependency here for trecursive_table.
  528. result.addf("$1$3 $2;$n", [getTypeDescWeak(m, field.loc.t, check, skField), sname, noAlias])
  529. elif field.bitsize != 0:
  530. result.addf("$1$4 $2:$3;$n", [getTypeDescAux(m, field.loc.t, check, skField), sname, rope($field.bitsize), noAlias])
  531. else:
  532. # don't use fieldType here because we need the
  533. # tyGenericInst for C++ template support
  534. result.addf("$1$3 $2;$n", [getTypeDescAux(m, field.loc.t, check, skField), sname, noAlias])
  535. else: internalError(m.config, n.info, "genRecordFieldsAux()")
  536. proc getRecordFields(m: BModule, typ: PType, check: var IntSet): Rope =
  537. result = genRecordFieldsAux(m, typ.n, typ, check)
  538. proc fillObjectFields*(m: BModule; typ: PType) =
  539. # sometimes generic objects are not consistently merged. We patch over
  540. # this fact here.
  541. var check = initIntSet()
  542. discard getRecordFields(m, typ, check)
  543. proc mangleDynLibProc(sym: PSym): Rope
  544. proc getRecordDesc(m: BModule, typ: PType, name: Rope,
  545. check: var IntSet): Rope =
  546. # declare the record:
  547. var hasField = false
  548. if tfPacked in typ.flags:
  549. if hasAttribute in CC[m.config.cCompiler].props:
  550. result = structOrUnion(typ) & " __attribute__((__packed__))"
  551. else:
  552. result = "#pragma pack(push, 1)\L" & structOrUnion(typ)
  553. else:
  554. result = structOrUnion(typ)
  555. result.add " "
  556. result.add name
  557. if typ.kind == tyObject:
  558. if typ[0] == nil:
  559. if (typ.sym != nil and sfPure in typ.sym.flags) or tfFinal in typ.flags:
  560. appcg(m, result, " {$n", [])
  561. else:
  562. if optTinyRtti in m.config.globalOptions:
  563. appcg(m, result, " {$n#TNimTypeV2* m_type;$n", [])
  564. else:
  565. appcg(m, result, " {$n#TNimType* m_type;$n", [])
  566. hasField = true
  567. elif m.compileToCpp:
  568. appcg(m, result, " : public $1 {$n",
  569. [getTypeDescAux(m, typ[0].skipTypes(skipPtrs), check, skField)])
  570. if typ.isException and m.config.exc == excCpp:
  571. when false:
  572. appcg(m, result, "virtual void raise() { throw *this; }$n", []) # required for polymorphic exceptions
  573. if typ.sym.magic == mException:
  574. # Add cleanup destructor to Exception base class
  575. appcg(m, result, "~$1();$n", [name])
  576. # define it out of the class body and into the procs section so we don't have to
  577. # artificially forward-declare popCurrentExceptionEx (very VERY troublesome for HCR)
  578. appcg(m, cfsProcs, "inline $1::~$1() {if(this->raiseId) #popCurrentExceptionEx(this->raiseId);}$n", [name])
  579. hasField = true
  580. else:
  581. appcg(m, result, " {$n $1 Sup;$n",
  582. [getTypeDescAux(m, typ[0].skipTypes(skipPtrs), check, skField)])
  583. hasField = true
  584. else:
  585. result.addf(" {$n", [name])
  586. let desc = getRecordFields(m, typ, check)
  587. if desc == nil and not hasField:
  588. result.addf("char dummy;$n", [])
  589. else:
  590. result.add(desc)
  591. result.add("};\L")
  592. if tfPacked in typ.flags and hasAttribute notin CC[m.config.cCompiler].props:
  593. result.add "#pragma pack(pop)\L"
  594. proc getTupleDesc(m: BModule, typ: PType, name: Rope,
  595. check: var IntSet): Rope =
  596. result = "$1 $2 {$n" % [structOrUnion(typ), name]
  597. var desc: Rope = nil
  598. for i in 0..<typ.len:
  599. desc.addf("$1 Field$2;$n",
  600. [getTypeDescAux(m, typ[i], check, skField), rope(i)])
  601. if desc == nil: result.add("char dummy;\L")
  602. else: result.add(desc)
  603. result.add("};\L")
  604. proc scanCppGenericSlot(pat: string, cursor, outIdx, outStars: var int): bool =
  605. # A helper proc for handling cppimport patterns, involving numeric
  606. # placeholders for generic types (e.g. '0, '**2, etc).
  607. # pre: the cursor must be placed at the ' symbol
  608. # post: the cursor will be placed after the final digit
  609. # false will returned if the input is not recognized as a placeholder
  610. inc cursor
  611. let begin = cursor
  612. while pat[cursor] == '*': inc cursor
  613. if pat[cursor] in Digits:
  614. outIdx = pat[cursor].ord - '0'.ord
  615. outStars = cursor - begin
  616. inc cursor
  617. return true
  618. else:
  619. return false
  620. proc resolveStarsInCppType(typ: PType, idx, stars: int): PType =
  621. # Make sure the index refers to one of the generic params of the type.
  622. # XXX: we should catch this earlier and report it as a semantic error.
  623. if idx >= typ.len:
  624. doAssert false, "invalid apostrophe type parameter index"
  625. result = typ[idx]
  626. for i in 1..stars:
  627. if result != nil and result.len > 0:
  628. result = if result.kind == tyGenericInst: result[1]
  629. else: result.elemType
  630. proc getOpenArrayDesc(m: BModule, t: PType, check: var IntSet; kind: TSymKind): Rope =
  631. let sig = hashType(t)
  632. if kind == skParam:
  633. result = getTypeDescWeak(m, t[0], check, kind) & "*"
  634. else:
  635. result = cacheGetType(m.typeCache, sig)
  636. if result == nil:
  637. result = getTypeName(m, t, sig)
  638. m.typeCache[sig] = result
  639. let elemType = getTypeDescWeak(m, t[0], check, kind)
  640. m.s[cfsTypes].addf("typedef struct {$n$2* Field0;$nNI Field1;$n} $1;$n",
  641. [result, elemType])
  642. proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKind): Rope =
  643. # returns only the type's name
  644. var t = origTyp.skipTypes(irrelevantForBackend-{tyOwned})
  645. if containsOrIncl(check, t.id):
  646. if not (isImportedCppType(origTyp) or isImportedCppType(t)):
  647. internalError(m.config, "cannot generate C type for: " & typeToString(origTyp))
  648. # XXX: this BUG is hard to fix -> we need to introduce helper structs,
  649. # but determining when this needs to be done is hard. We should split
  650. # C type generation into an analysis and a code generation phase somehow.
  651. if t.sym != nil: useHeader(m, t.sym)
  652. if t != origTyp and origTyp.sym != nil: useHeader(m, origTyp.sym)
  653. let sig = hashType(origTyp)
  654. defer: # defer is the simplest in this case
  655. if isImportedType(t) and not m.typeABICache.containsOrIncl(sig):
  656. addAbiCheck(m, t, result)
  657. result = getTypePre(m, t, sig)
  658. if result != nil and t.kind != tyOpenArray:
  659. excl(check, t.id)
  660. return
  661. case t.kind
  662. of tyRef, tyPtr, tyVar, tyLent:
  663. var star = if t.kind in {tyVar} and tfVarIsPtr notin origTyp.flags and
  664. compileToCpp(m): "&" else: "*"
  665. var et = origTyp.skipTypes(abstractInst).lastSon
  666. var etB = et.skipTypes(abstractInst)
  667. if mapType(m.config, t, kind) == ctPtrToArray and (etB.kind != tyOpenArray or kind == skParam):
  668. if etB.kind == tySet:
  669. et = getSysType(m.g.graph, unknownLineInfo, tyUInt8)
  670. else:
  671. et = elemType(etB)
  672. etB = et.skipTypes(abstractInst)
  673. star[0] = '*'
  674. case etB.kind
  675. of tyObject, tyTuple:
  676. if isImportedCppType(etB) and et.kind == tyGenericInst:
  677. result = getTypeDescAux(m, et, check, kind) & star
  678. else:
  679. # no restriction! We have a forward declaration for structs
  680. let name = getTypeForward(m, et, hashType et)
  681. result = name & star
  682. m.typeCache[sig] = result
  683. of tySequence:
  684. if optSeqDestructors in m.config.globalOptions:
  685. result = getTypeDescWeak(m, et, check, kind) & star
  686. m.typeCache[sig] = result
  687. else:
  688. # no restriction! We have a forward declaration for structs
  689. let name = getTypeForward(m, et, hashType et)
  690. result = name & seqStar(m) & star
  691. m.typeCache[sig] = result
  692. pushType(m, et)
  693. else:
  694. # else we have a strong dependency :-(
  695. result = getTypeDescAux(m, et, check, kind) & star
  696. m.typeCache[sig] = result
  697. of tyOpenArray, tyVarargs:
  698. result = getOpenArrayDesc(m, t, check, kind)
  699. of tyEnum:
  700. result = cacheGetType(m.typeCache, sig)
  701. if result == nil:
  702. result = getTypeName(m, origTyp, sig)
  703. if not (isImportedCppType(t) or
  704. (sfImportc in t.sym.flags and t.sym.magic == mNone)):
  705. m.typeCache[sig] = result
  706. var size: int
  707. if firstOrd(m.config, t) < 0:
  708. m.s[cfsTypes].addf("typedef NI32 $1;$n", [result])
  709. size = 4
  710. else:
  711. size = int(getSize(m.config, t))
  712. case size
  713. of 1: m.s[cfsTypes].addf("typedef NU8 $1;$n", [result])
  714. of 2: m.s[cfsTypes].addf("typedef NU16 $1;$n", [result])
  715. of 4: m.s[cfsTypes].addf("typedef NI32 $1;$n", [result])
  716. of 8: m.s[cfsTypes].addf("typedef NI64 $1;$n", [result])
  717. else: internalError(m.config, t.sym.info, "getTypeDescAux: enum")
  718. when false:
  719. let owner = hashOwner(t.sym)
  720. if not gDebugInfo.hasEnum(t.sym.name.s, t.sym.info.line, owner):
  721. var vals: seq[(string, int)] = @[]
  722. for i in 0..<t.n.len:
  723. assert(t.n[i].kind == nkSym)
  724. let field = t.n[i].sym
  725. vals.add((field.name.s, field.position.int))
  726. gDebugInfo.registerEnum(EnumDesc(size: size, owner: owner, id: t.sym.id,
  727. name: t.sym.name.s, values: vals))
  728. of tyProc:
  729. result = getTypeName(m, origTyp, sig)
  730. m.typeCache[sig] = result
  731. var rettype, desc: Rope
  732. genProcParams(m, t, rettype, desc, check, true, true)
  733. if not isImportedType(t):
  734. if t.callConv != ccClosure: # procedure vars may need a closure!
  735. m.s[cfsTypes].addf("typedef $1_PTR($2, $3) $4;$n",
  736. [rope(CallingConvToStr[t.callConv]), rettype, result, desc])
  737. else:
  738. m.s[cfsTypes].addf("typedef struct {$n" &
  739. "N_NIMCALL_PTR($2, ClP_0) $3;$n" &
  740. "void* ClE_0;$n} $1;$n",
  741. [result, rettype, desc])
  742. of tySequence:
  743. if optSeqDestructors in m.config.globalOptions:
  744. result = getTypeDescWeak(m, t, check, kind)
  745. else:
  746. # we cannot use getTypeForward here because then t would be associated
  747. # with the name of the struct, not with the pointer to the struct:
  748. result = cacheGetType(m.forwTypeCache, sig)
  749. if result == nil:
  750. result = getTypeName(m, origTyp, sig)
  751. if not isImportedType(t):
  752. addForwardStructFormat(m, structOrUnion(t), result)
  753. m.forwTypeCache[sig] = result
  754. assert(cacheGetType(m.typeCache, sig) == nil)
  755. m.typeCache[sig] = result & seqStar(m)
  756. if not isImportedType(t):
  757. if skipTypes(t[0], typedescInst).kind != tyEmpty:
  758. const
  759. cppSeq = "struct $2 : #TGenericSeq {$n"
  760. cSeq = "struct $2 {$n" &
  761. " #TGenericSeq Sup;$n"
  762. if m.compileToCpp:
  763. appcg(m, m.s[cfsSeqTypes],
  764. cppSeq & " $1 data[SEQ_DECL_SIZE];$n" &
  765. "};$n", [getTypeDescAux(m, t[0], check, kind), result])
  766. else:
  767. appcg(m, m.s[cfsSeqTypes],
  768. cSeq & " $1 data[SEQ_DECL_SIZE];$n" &
  769. "};$n", [getTypeDescAux(m, t[0], check, kind), result])
  770. else:
  771. result = rope("TGenericSeq")
  772. result.add(seqStar(m))
  773. of tyUncheckedArray:
  774. result = getTypeName(m, origTyp, sig)
  775. m.typeCache[sig] = result
  776. if not isImportedType(t):
  777. let foo = getTypeDescAux(m, t[0], check, kind)
  778. m.s[cfsTypes].addf("typedef $1 $2[1];$n", [foo, result])
  779. of tyArray:
  780. var n: BiggestInt = toInt64(lengthOrd(m.config, t))
  781. if n <= 0: n = 1 # make an array of at least one element
  782. result = getTypeName(m, origTyp, sig)
  783. m.typeCache[sig] = result
  784. if not isImportedType(t):
  785. let foo = getTypeDescAux(m, t[1], check, kind)
  786. m.s[cfsTypes].addf("typedef $1 $2[$3];$n",
  787. [foo, result, rope(n)])
  788. of tyObject, tyTuple:
  789. if isImportedCppType(t) and origTyp.kind == tyGenericInst:
  790. let cppName = getTypeName(m, t, sig)
  791. var i = 0
  792. var chunkStart = 0
  793. template addResultType(ty: untyped) =
  794. if ty == nil or ty.kind == tyVoid:
  795. result.add(~"void")
  796. elif ty.kind == tyStatic:
  797. internalAssert m.config, ty.n != nil
  798. result.add ty.n.renderTree
  799. else:
  800. result.add getTypeDescAux(m, ty, check, kind)
  801. while i < cppName.data.len:
  802. if cppName.data[i] == '\'':
  803. var chunkEnd = i-1
  804. var idx, stars: int
  805. if scanCppGenericSlot(cppName.data, i, idx, stars):
  806. result.add cppName.data.substr(chunkStart, chunkEnd)
  807. chunkStart = i
  808. let typeInSlot = resolveStarsInCppType(origTyp, idx + 1, stars)
  809. addResultType(typeInSlot)
  810. else:
  811. inc i
  812. if chunkStart != 0:
  813. result.add cppName.data.substr(chunkStart)
  814. else:
  815. result = cppName & "<"
  816. for i in 1..<origTyp.len-1:
  817. if i > 1: result.add(" COMMA ")
  818. addResultType(origTyp[i])
  819. result.add("> ")
  820. # always call for sideeffects:
  821. assert t.kind != tyTuple
  822. discard getRecordDesc(m, t, result, check)
  823. # The resulting type will include commas and these won't play well
  824. # with the C macros for defining procs such as N_NIMCALL. We must
  825. # create a typedef for the type and use it in the proc signature:
  826. let typedefName = ~"TY" & $sig
  827. m.s[cfsTypes].addf("typedef $1 $2;$n", [result, typedefName])
  828. m.typeCache[sig] = typedefName
  829. result = typedefName
  830. else:
  831. result = cacheGetType(m.forwTypeCache, sig)
  832. if result == nil:
  833. result = getTypeName(m, origTyp, sig)
  834. m.forwTypeCache[sig] = result
  835. if not isImportedType(t):
  836. addForwardStructFormat(m, structOrUnion(t), result)
  837. assert m.forwTypeCache[sig] == result
  838. m.typeCache[sig] = result # always call for sideeffects:
  839. if not incompleteType(t):
  840. let recdesc = if t.kind != tyTuple: getRecordDesc(m, t, result, check)
  841. else: getTupleDesc(m, t, result, check)
  842. if not isImportedType(t):
  843. m.s[cfsTypes].add(recdesc)
  844. elif tfIncompleteStruct notin t.flags:
  845. discard # addAbiCheck(m, t, result) # already handled elsewhere
  846. of tySet:
  847. # Don't use the imported name as it may be scoped: 'Foo::SomeKind'
  848. result = $t.kind & '_' & t.lastSon.typeName & $t.lastSon.hashType
  849. m.typeCache[sig] = result
  850. if not isImportedType(t):
  851. let s = int(getSize(m.config, t))
  852. case s
  853. of 1, 2, 4, 8: m.s[cfsTypes].addf("typedef NU$2 $1;$n", [result, rope(s*8)])
  854. else: m.s[cfsTypes].addf("typedef NU8 $1[$2];$n",
  855. [result, rope(getSize(m.config, t))])
  856. of tyGenericInst, tyDistinct, tyOrdinal, tyTypeDesc, tyAlias, tySink, tyOwned,
  857. tyUserTypeClass, tyUserTypeClassInst, tyInferred:
  858. result = getTypeDescAux(m, lastSon(t), check, kind)
  859. else:
  860. internalError(m.config, "getTypeDescAux(" & $t.kind & ')')
  861. result = nil
  862. # fixes bug #145:
  863. excl(check, t.id)
  864. proc getTypeDesc(m: BModule, typ: PType; kind = skParam): Rope =
  865. var check = initIntSet()
  866. result = getTypeDescAux(m, typ, check, kind)
  867. type
  868. TClosureTypeKind = enum ## In C closures are mapped to 3 different things.
  869. clHalf, ## fn(args) type without the trailing 'void* env' parameter
  870. clHalfWithEnv, ## fn(args, void* env) type with trailing 'void* env' parameter
  871. clFull ## struct {fn(args, void* env), env}
  872. proc getClosureType(m: BModule, t: PType, kind: TClosureTypeKind): Rope =
  873. assert t.kind == tyProc
  874. var check = initIntSet()
  875. result = getTempName(m)
  876. var rettype, desc: Rope
  877. genProcParams(m, t, rettype, desc, check, declareEnvironment=kind != clHalf)
  878. if not isImportedType(t):
  879. if t.callConv != ccClosure or kind != clFull:
  880. m.s[cfsTypes].addf("typedef $1_PTR($2, $3) $4;$n",
  881. [rope(CallingConvToStr[t.callConv]), rettype, result, desc])
  882. else:
  883. m.s[cfsTypes].addf("typedef struct {$n" &
  884. "N_NIMCALL_PTR($2, ClP_0) $3;$n" &
  885. "void* ClE_0;$n} $1;$n",
  886. [result, rettype, desc])
  887. proc finishTypeDescriptions(m: BModule) =
  888. var i = 0
  889. var check = initIntSet()
  890. while i < m.typeStack.len:
  891. let t = m.typeStack[i]
  892. if optSeqDestructors in m.config.globalOptions and t.skipTypes(abstractInst).kind == tySequence:
  893. seqV2ContentType(m, t, check)
  894. else:
  895. discard getTypeDescAux(m, t, check, skParam)
  896. inc(i)
  897. m.typeStack.setLen 0
  898. template cgDeclFrmt*(s: PSym): string =
  899. s.constraint.strVal
  900. proc isReloadable(m: BModule, prc: PSym): bool =
  901. return m.hcrOn and sfNonReloadable notin prc.flags
  902. proc isNonReloadable(m: BModule, prc: PSym): bool =
  903. return m.hcrOn and sfNonReloadable in prc.flags
  904. proc genProcHeader(m: BModule, prc: PSym, asPtr: bool = false): Rope =
  905. var
  906. rettype, params: Rope
  907. # using static is needed for inline procs
  908. if lfExportLib in prc.loc.flags:
  909. if isHeaderFile in m.flags:
  910. result.add "N_LIB_IMPORT "
  911. else:
  912. result.add "N_LIB_EXPORT "
  913. elif prc.typ.callConv == ccInline or asPtr or isNonReloadable(m, prc):
  914. result.add "static "
  915. elif sfImportc notin prc.flags:
  916. result.add "N_LIB_PRIVATE "
  917. var check = initIntSet()
  918. fillLoc(prc.loc, locProc, prc.ast[namePos], mangleName(m, prc), OnUnknown)
  919. genProcParams(m, prc.typ, rettype, params, check)
  920. # handle the 2 options for hotcodereloading codegen - function pointer
  921. # (instead of forward declaration) or header for function body with "_actual" postfix
  922. let asPtrStr = rope(if asPtr: "_PTR" else: "")
  923. var name = prc.loc.r
  924. if isReloadable(m, prc) and not asPtr:
  925. name.add("_actual")
  926. # careful here! don't access ``prc.ast`` as that could reload large parts of
  927. # the object graph!
  928. if prc.constraint.isNil:
  929. result.addf("$1$2($3, $4)$5",
  930. [rope(CallingConvToStr[prc.typ.callConv]), asPtrStr, rettype, name,
  931. params])
  932. else:
  933. let asPtrStr = if asPtr: (rope("(*") & name & ")") else: name
  934. result = runtimeFormat(prc.cgDeclFrmt, [rettype, asPtrStr, params])
  935. # ------------------ type info generation -------------------------------------
  936. proc genTypeInfoV1(m: BModule, t: PType; info: TLineInfo): Rope
  937. proc getNimNode(m: BModule): Rope =
  938. result = "$1[$2]" % [m.typeNodesName, rope(m.typeNodes)]
  939. inc(m.typeNodes)
  940. proc tiNameForHcr(m: BModule, name: Rope): Rope =
  941. return if m.hcrOn: "(*".rope & name & ")" else: name
  942. proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
  943. name, base: Rope; info: TLineInfo) =
  944. var nimtypeKind: int
  945. #allocMemTI(m, typ, name)
  946. if isObjLackingTypeField(typ):
  947. nimtypeKind = ord(tyPureObject)
  948. else:
  949. nimtypeKind = ord(typ.kind)
  950. let nameHcr = tiNameForHcr(m, name)
  951. var size: Rope
  952. if tfIncompleteStruct in typ.flags:
  953. size = rope"void*"
  954. else:
  955. size = getTypeDesc(m, origType, skVar)
  956. m.s[cfsTypeInit3].addf(
  957. "$1.size = sizeof($2);$n$1.align = NIM_ALIGNOF($2);$n$1.kind = $3;$n$1.base = $4;$n",
  958. [nameHcr, size, rope(nimtypeKind), base]
  959. )
  960. # compute type flags for GC optimization
  961. var flags = 0
  962. if not containsGarbageCollectedRef(typ): flags = flags or 1
  963. if not canFormAcycle(typ): flags = flags or 2
  964. #else MessageOut("can contain a cycle: " & typeToString(typ))
  965. if flags != 0:
  966. m.s[cfsTypeInit3].addf("$1.flags = $2;$n", [nameHcr, rope(flags)])
  967. discard cgsym(m, "TNimType")
  968. if isDefined(m.config, "nimTypeNames"):
  969. var typename = typeToString(if origType.typeInst != nil: origType.typeInst
  970. else: origType, preferName)
  971. if typename == "ref object" and origType.skipTypes(skipPtrs).sym != nil:
  972. typename = "anon ref object from " & m.config$origType.skipTypes(skipPtrs).sym.info
  973. m.s[cfsTypeInit3].addf("$1.name = $2;$n",
  974. [nameHcr, makeCString typename])
  975. discard cgsym(m, "nimTypeRoot")
  976. m.s[cfsTypeInit3].addf("$1.nextType = nimTypeRoot; nimTypeRoot=&$1;$n",
  977. [nameHcr])
  978. if m.hcrOn:
  979. m.s[cfsData].addf("static TNimType* $1;$n", [name])
  980. m.hcrCreateTypeInfosProc.addf("\thcrRegisterGlobal($2, \"$1\", sizeof(TNimType), NULL, (void**)&$1);$n",
  981. [name, getModuleDllPath(m, m.module)])
  982. else:
  983. m.s[cfsData].addf("N_LIB_PRIVATE TNimType $1;$n", [name])
  984. proc genTypeInfoAux(m: BModule, typ, origType: PType, name: Rope;
  985. info: TLineInfo) =
  986. var base: Rope
  987. if typ.len > 0 and typ.lastSon != nil:
  988. var x = typ.lastSon
  989. if typ.kind == tyObject: x = x.skipTypes(skipPtrs)
  990. if typ.kind == tyPtr and x.kind == tyObject and incompleteType(x):
  991. base = rope("0")
  992. else:
  993. base = genTypeInfoV1(m, x, info)
  994. else:
  995. base = rope("0")
  996. genTypeInfoAuxBase(m, typ, origType, name, base, info)
  997. proc discriminatorTableName(m: BModule, objtype: PType, d: PSym): Rope =
  998. # bugfix: we need to search the type that contains the discriminator:
  999. var objtype = objtype.skipTypes(abstractPtrs)
  1000. while lookupInRecord(objtype.n, d.name) == nil:
  1001. objtype = objtype[0].skipTypes(abstractPtrs)
  1002. if objtype.sym == nil:
  1003. internalError(m.config, d.info, "anonymous obj with discriminator")
  1004. result = "NimDT_$1_$2" % [rope($hashType(objtype)), rope(d.name.s.mangle)]
  1005. proc rope(arg: Int128): Rope = rope($arg)
  1006. proc discriminatorTableDecl(m: BModule, objtype: PType, d: PSym): Rope =
  1007. discard cgsym(m, "TNimNode")
  1008. var tmp = discriminatorTableName(m, objtype, d)
  1009. result = "TNimNode* $1[$2];$n" % [tmp, rope(lengthOrd(m.config, d.typ)+1)]
  1010. proc genTNimNodeArray(m: BModule, name: Rope, size: Rope) =
  1011. if m.hcrOn:
  1012. m.s[cfsData].addf("static TNimNode** $1;$n", [name])
  1013. m.hcrCreateTypeInfosProc.addf("\thcrRegisterGlobal($3, \"$1\", sizeof(TNimNode*) * $2, NULL, (void**)&$1);$n",
  1014. [name, size, getModuleDllPath(m, m.module)])
  1015. else:
  1016. m.s[cfsTypeInit1].addf("static TNimNode* $1[$2];$n", [name, size])
  1017. proc genObjectFields(m: BModule, typ, origType: PType, n: PNode, expr: Rope;
  1018. info: TLineInfo) =
  1019. case n.kind
  1020. of nkRecList:
  1021. if n.len == 1:
  1022. genObjectFields(m, typ, origType, n[0], expr, info)
  1023. elif n.len > 0:
  1024. var tmp = getTempName(m) & "_" & $n.len
  1025. genTNimNodeArray(m, tmp, rope(n.len))
  1026. for i in 0..<n.len:
  1027. var tmp2 = getNimNode(m)
  1028. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(i), tmp2])
  1029. genObjectFields(m, typ, origType, n[i], tmp2, info)
  1030. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n",
  1031. [expr, rope(n.len), tmp])
  1032. else:
  1033. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2;$n", [expr, rope(n.len)])
  1034. of nkRecCase:
  1035. assert(n[0].kind == nkSym)
  1036. var field = n[0].sym
  1037. var tmp = discriminatorTableName(m, typ, field)
  1038. var L = lengthOrd(m.config, field.typ)
  1039. assert L > 0
  1040. if field.loc.r == nil: fillObjectFields(m, typ)
  1041. if field.loc.t == nil:
  1042. internalError(m.config, n.info, "genObjectFields")
  1043. m.s[cfsTypeInit3].addf("$1.kind = 3;$n" &
  1044. "$1.offset = offsetof($2, $3);$n" & "$1.typ = $4;$n" &
  1045. "$1.name = $5;$n" & "$1.sons = &$6[0];$n" &
  1046. "$1.len = $7;$n", [expr, getTypeDesc(m, origType, skVar), field.loc.r,
  1047. genTypeInfoV1(m, field.typ, info),
  1048. makeCString(field.name.s),
  1049. tmp, rope(L)])
  1050. m.s[cfsData].addf("TNimNode* $1[$2];$n", [tmp, rope(L+1)])
  1051. for i in 1..<n.len:
  1052. var b = n[i] # branch
  1053. var tmp2 = getNimNode(m)
  1054. genObjectFields(m, typ, origType, lastSon(b), tmp2, info)
  1055. case b.kind
  1056. of nkOfBranch:
  1057. if b.len < 2:
  1058. internalError(m.config, b.info, "genObjectFields; nkOfBranch broken")
  1059. for j in 0..<b.len - 1:
  1060. if b[j].kind == nkRange:
  1061. var x = toInt(getOrdValue(b[j][0]))
  1062. var y = toInt(getOrdValue(b[j][1]))
  1063. while x <= y:
  1064. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(x), tmp2])
  1065. inc(x)
  1066. else:
  1067. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n",
  1068. [tmp, rope(getOrdValue(b[j])), tmp2])
  1069. of nkElse:
  1070. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n",
  1071. [tmp, rope(L), tmp2])
  1072. else: internalError(m.config, n.info, "genObjectFields(nkRecCase)")
  1073. of nkSym:
  1074. var field = n.sym
  1075. # Do not produce code for void types
  1076. if isEmptyType(field.typ): return
  1077. if field.bitsize == 0:
  1078. if field.loc.r == nil: fillObjectFields(m, typ)
  1079. if field.loc.t == nil:
  1080. internalError(m.config, n.info, "genObjectFields")
  1081. m.s[cfsTypeInit3].addf("$1.kind = 1;$n" &
  1082. "$1.offset = offsetof($2, $3);$n" & "$1.typ = $4;$n" &
  1083. "$1.name = $5;$n", [expr, getTypeDesc(m, origType, skVar),
  1084. field.loc.r, genTypeInfoV1(m, field.typ, info), makeCString(field.name.s)])
  1085. else: internalError(m.config, n.info, "genObjectFields")
  1086. proc genObjectInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo) =
  1087. if typ.kind == tyObject:
  1088. if incompleteType(typ):
  1089. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1090. typeToString(typ))
  1091. genTypeInfoAux(m, typ, origType, name, info)
  1092. else:
  1093. genTypeInfoAuxBase(m, typ, origType, name, rope("0"), info)
  1094. var tmp = getNimNode(m)
  1095. if not isImportedType(typ):
  1096. genObjectFields(m, typ, origType, typ.n, tmp, info)
  1097. m.s[cfsTypeInit3].addf("$1.node = &$2;$n", [tiNameForHcr(m, name), tmp])
  1098. var t = typ[0]
  1099. while t != nil:
  1100. t = t.skipTypes(skipPtrs)
  1101. t.flags.incl tfObjHasKids
  1102. t = t[0]
  1103. proc genTupleInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo) =
  1104. genTypeInfoAuxBase(m, typ, typ, name, rope("0"), info)
  1105. var expr = getNimNode(m)
  1106. if typ.len > 0:
  1107. var tmp = getTempName(m) & "_" & $typ.len
  1108. genTNimNodeArray(m, tmp, rope(typ.len))
  1109. for i in 0..<typ.len:
  1110. var a = typ[i]
  1111. var tmp2 = getNimNode(m)
  1112. m.s[cfsTypeInit3].addf("$1[$2] = &$3;$n", [tmp, rope(i), tmp2])
  1113. m.s[cfsTypeInit3].addf("$1.kind = 1;$n" &
  1114. "$1.offset = offsetof($2, Field$3);$n" &
  1115. "$1.typ = $4;$n" &
  1116. "$1.name = \"Field$3\";$n",
  1117. [tmp2, getTypeDesc(m, origType, skVar), rope(i), genTypeInfoV1(m, a, info)])
  1118. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n",
  1119. [expr, rope(typ.len), tmp])
  1120. else:
  1121. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 2;$n",
  1122. [expr, rope(typ.len)])
  1123. m.s[cfsTypeInit3].addf("$1.node = &$2;$n", [tiNameForHcr(m, name), expr])
  1124. proc genEnumInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1125. # Type information for enumerations is quite heavy, so we do some
  1126. # optimizations here: The ``typ`` field is never set, as it is redundant
  1127. # anyway. We generate a cstring array and a loop over it. Exceptional
  1128. # positions will be reset after the loop.
  1129. genTypeInfoAux(m, typ, typ, name, info)
  1130. var nodePtrs = getTempName(m) & "_" & $typ.n.len
  1131. genTNimNodeArray(m, nodePtrs, rope(typ.n.len))
  1132. var enumNames, specialCases: Rope
  1133. var firstNimNode = m.typeNodes
  1134. var hasHoles = false
  1135. for i in 0..<typ.n.len:
  1136. assert(typ.n[i].kind == nkSym)
  1137. var field = typ.n[i].sym
  1138. var elemNode = getNimNode(m)
  1139. if field.ast == nil:
  1140. # no explicit string literal for the enum field, so use field.name:
  1141. enumNames.add(makeCString(field.name.s))
  1142. else:
  1143. enumNames.add(makeCString(field.ast.strVal))
  1144. if i < typ.n.len - 1: enumNames.add(", \L")
  1145. if field.position != i or tfEnumHasHoles in typ.flags:
  1146. specialCases.addf("$1.offset = $2;$n", [elemNode, rope(field.position)])
  1147. hasHoles = true
  1148. var enumArray = getTempName(m)
  1149. var counter = getTempName(m)
  1150. m.s[cfsTypeInit1].addf("NI $1;$n", [counter])
  1151. m.s[cfsTypeInit1].addf("static char* NIM_CONST $1[$2] = {$n$3};$n",
  1152. [enumArray, rope(typ.n.len), enumNames])
  1153. m.s[cfsTypeInit3].addf("for ($1 = 0; $1 < $2; $1++) {$n" &
  1154. "$3[$1+$4].kind = 1;$n" & "$3[$1+$4].offset = $1;$n" &
  1155. "$3[$1+$4].name = $5[$1];$n" & "$6[$1] = &$3[$1+$4];$n" & "}$n", [counter,
  1156. rope(typ.n.len), m.typeNodesName, rope(firstNimNode), enumArray, nodePtrs])
  1157. m.s[cfsTypeInit3].add(specialCases)
  1158. m.s[cfsTypeInit3].addf(
  1159. "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n",
  1160. [getNimNode(m), rope(typ.n.len), nodePtrs, tiNameForHcr(m, name)])
  1161. if hasHoles:
  1162. # 1 << 2 is {ntfEnumHole}
  1163. m.s[cfsTypeInit3].addf("$1.flags = 1<<2;$n", [tiNameForHcr(m, name)])
  1164. proc genSetInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1165. assert(typ[0] != nil)
  1166. genTypeInfoAux(m, typ, typ, name, info)
  1167. var tmp = getNimNode(m)
  1168. m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 0;$n" & "$3.node = &$1;$n",
  1169. [tmp, rope(firstOrd(m.config, typ)), tiNameForHcr(m, name)])
  1170. proc genArrayInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1171. genTypeInfoAuxBase(m, typ, typ, name, genTypeInfoV1(m, typ[1], info), info)
  1172. proc fakeClosureType(m: BModule; owner: PSym): PType =
  1173. # we generate the same RTTI as for a tuple[pointer, ref tuple[]]
  1174. result = newType(tyTuple, nextId m.idgen, owner)
  1175. result.rawAddSon(newType(tyPointer, nextId m.idgen, owner))
  1176. var r = newType(tyRef, nextId m.idgen, owner)
  1177. let obj = createObj(m.g.graph, m.idgen, owner, owner.info, final=false)
  1178. r.rawAddSon(obj)
  1179. result.rawAddSon(r)
  1180. include ccgtrav
  1181. proc genDeepCopyProc(m: BModule; s: PSym; result: Rope) =
  1182. genProc(m, s)
  1183. m.s[cfsTypeInit3].addf("$1.deepcopy =(void* (N_RAW_NIMCALL*)(void*))$2;$n",
  1184. [result, s.loc.r])
  1185. proc declareNimType(m: BModule, name: string; str: Rope, ownerModule: PSym) =
  1186. let nr = rope(name)
  1187. if m.hcrOn:
  1188. m.s[cfsData].addf("static $2* $1;$n", [str, nr])
  1189. m.s[cfsTypeInit1].addf("\t$1 = ($3*)hcrGetGlobal($2, \"$1\");$n",
  1190. [str, getModuleDllPath(m, ownerModule), nr])
  1191. else:
  1192. m.s[cfsData].addf("extern $2 $1;$n", [str, nr])
  1193. proc genTypeInfo2Name(m: BModule; t: PType): Rope =
  1194. var res = "|"
  1195. var it = t
  1196. while it != nil:
  1197. it = it.skipTypes(skipPtrs)
  1198. if it.sym != nil:
  1199. var m = it.sym.owner
  1200. while m != nil and m.kind != skModule: m = m.owner
  1201. if m == nil or sfSystemModule in m.flags:
  1202. # produce short names for system types:
  1203. res.add it.sym.name.s
  1204. else:
  1205. var p = m.owner
  1206. if p != nil and p.kind == skPackage:
  1207. res.add p.name.s & "."
  1208. res.add m.name.s & "."
  1209. res.add it.sym.name.s
  1210. else:
  1211. res.add $hashType(it)
  1212. res.add "|"
  1213. it = it[0]
  1214. result = makeCString(res)
  1215. proc isTrivialProc(s: PSym): bool {.inline.} = s.ast[bodyPos].len == 0
  1216. proc genHook(m: BModule; t: PType; info: TLineInfo; op: TTypeAttachedOp): Rope =
  1217. let theProc = t.attachedOps[op]
  1218. if theProc != nil and not isTrivialProc(theProc):
  1219. # the prototype of a destructor is ``=destroy(x: var T)`` and that of a
  1220. # finalizer is: ``proc (x: ref T) {.nimcall.}``. We need to check the calling
  1221. # convention at least:
  1222. if theProc.typ == nil or theProc.typ.callConv != ccNimCall:
  1223. localError(m.config, info,
  1224. theProc.name.s & " needs to have the 'nimcall' calling convention")
  1225. genProc(m, theProc)
  1226. result = theProc.loc.r
  1227. else:
  1228. when false:
  1229. if op == attachedTrace and m.config.selectedGC == gcOrc and
  1230. containsGarbageCollectedRef(t):
  1231. # unfortunately this check is wrong for an object type that only contains
  1232. # .cursor fields like 'Node' inside 'cycleleak'.
  1233. internalError(m.config, info, "no attached trace proc found")
  1234. result = rope("NIM_NIL")
  1235. proc genTypeInfoV2Impl(m: BModule, t, origType: PType, name: Rope; info: TLineInfo) =
  1236. var typeName: Rope
  1237. if t.kind == tyObject:
  1238. if incompleteType(t):
  1239. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  1240. typeToString(t))
  1241. typeName = genTypeInfo2Name(m, t)
  1242. else:
  1243. typeName = rope("NIM_NIL")
  1244. discard cgsym(m, "TNimTypeV2")
  1245. m.s[cfsData].addf("N_LIB_PRIVATE TNimTypeV2 $1;$n", [name])
  1246. let destroyImpl = genHook(m, t, info, attachedDestructor)
  1247. let traceImpl = genHook(m, t, info, attachedTrace)
  1248. let disposeImpl = genHook(m, t, info, attachedDispose)
  1249. 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;", [
  1250. name, destroyImpl, getTypeDesc(m, t), typeName,
  1251. traceImpl, disposeImpl])
  1252. if t.kind == tyObject and t.len > 0 and t[0] != nil and optEnableDeepCopy in m.config.globalOptions:
  1253. discard genTypeInfoV1(m, t, info)
  1254. proc genTypeInfoV2(m: BModule, t: PType; info: TLineInfo): Rope =
  1255. let origType = t
  1256. var t = skipTypes(origType, irrelevantForBackend + tyUserTypeClasses)
  1257. let prefixTI = if m.hcrOn: "(" else: "(&"
  1258. let sig = hashType(origType)
  1259. result = m.typeInfoMarkerV2.getOrDefault(sig)
  1260. if result != nil:
  1261. return prefixTI.rope & result & ")".rope
  1262. let marker = m.g.typeInfoMarkerV2.getOrDefault(sig)
  1263. if marker.str != nil:
  1264. discard cgsym(m, "TNimTypeV2")
  1265. declareNimType(m, "TNimTypeV2", marker.str, marker.owner)
  1266. # also store in local type section:
  1267. m.typeInfoMarkerV2[sig] = marker.str
  1268. return prefixTI.rope & marker.str & ")".rope
  1269. result = "NTIv2$1_" % [rope($sig)]
  1270. m.typeInfoMarkerV2[sig] = result
  1271. let owner = t.skipTypes(typedescPtrs).owner.getModule
  1272. if owner != m.module:
  1273. # make sure the type info is created in the owner module
  1274. assert m.g.modules[owner.position] != nil
  1275. discard genTypeInfoV2(m.g.modules[owner.position], origType, info)
  1276. # reference the type info as extern here
  1277. discard cgsym(m, "TNimTypeV2")
  1278. declareNimType(m, "TNimTypeV2", result, owner)
  1279. return prefixTI.rope & result & ")".rope
  1280. m.g.typeInfoMarkerV2[sig] = (str: result, owner: owner)
  1281. genTypeInfoV2Impl(m, t, origType, result, info)
  1282. result = prefixTI.rope & result & ")".rope
  1283. proc openArrayToTuple(m: BModule; t: PType): PType =
  1284. result = newType(tyTuple, nextId m.idgen, t.owner)
  1285. let p = newType(tyPtr, nextId m.idgen, t.owner)
  1286. let a = newType(tyUncheckedArray, nextId m.idgen, t.owner)
  1287. a.add t.lastSon
  1288. p.add a
  1289. result.add p
  1290. result.add getSysType(m.g.graph, t.owner.info, tyInt)
  1291. proc genTypeInfoV1(m: BModule, t: PType; info: TLineInfo): Rope =
  1292. let origType = t
  1293. var t = skipTypes(origType, irrelevantForBackend + tyUserTypeClasses)
  1294. let prefixTI = if m.hcrOn: "(" else: "(&"
  1295. let sig = hashType(origType)
  1296. result = m.typeInfoMarker.getOrDefault(sig)
  1297. if result != nil:
  1298. return prefixTI.rope & result & ")".rope
  1299. let marker = m.g.typeInfoMarker.getOrDefault(sig)
  1300. if marker.str != nil:
  1301. discard cgsym(m, "TNimType")
  1302. discard cgsym(m, "TNimNode")
  1303. declareNimType(m, "TNimType", marker.str, marker.owner)
  1304. # also store in local type section:
  1305. m.typeInfoMarker[sig] = marker.str
  1306. return prefixTI.rope & marker.str & ")".rope
  1307. result = "NTI$1_" % [rope($sig)]
  1308. m.typeInfoMarker[sig] = result
  1309. let owner = t.skipTypes(typedescPtrs).owner.getModule
  1310. if owner != m.module:
  1311. # make sure the type info is created in the owner module
  1312. assert m.g.modules[owner.position] != nil
  1313. discard genTypeInfoV1(m.g.modules[owner.position], origType, info)
  1314. # reference the type info as extern here
  1315. discard cgsym(m, "TNimType")
  1316. discard cgsym(m, "TNimNode")
  1317. declareNimType(m, "TNimType", result, owner)
  1318. return prefixTI.rope & result & ")".rope
  1319. m.g.typeInfoMarker[sig] = (str: result, owner: owner)
  1320. case t.kind
  1321. of tyEmpty, tyVoid: result = rope"0"
  1322. of tyPointer, tyBool, tyChar, tyCString, tyString, tyInt..tyUInt64, tyVar, tyLent:
  1323. genTypeInfoAuxBase(m, t, t, result, rope"0", info)
  1324. of tyStatic:
  1325. if t.n != nil: result = genTypeInfoV1(m, lastSon t, info)
  1326. else: internalError(m.config, "genTypeInfoV1(" & $t.kind & ')')
  1327. of tyUserTypeClasses:
  1328. internalAssert m.config, t.isResolvedUserTypeClass
  1329. return genTypeInfoV1(m, t.lastSon, info)
  1330. of tyProc:
  1331. if t.callConv != ccClosure:
  1332. genTypeInfoAuxBase(m, t, t, result, rope"0", info)
  1333. else:
  1334. let x = fakeClosureType(m, t.owner)
  1335. genTupleInfo(m, x, x, result, info)
  1336. of tySequence:
  1337. genTypeInfoAux(m, t, t, result, info)
  1338. if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcV2, gcGo}:
  1339. let markerProc = genTraverseProc(m, origType, sig)
  1340. m.s[cfsTypeInit3].addf("$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
  1341. of tyRef:
  1342. genTypeInfoAux(m, t, t, result, info)
  1343. if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcV2, gcGo}:
  1344. let markerProc = genTraverseProc(m, origType, sig)
  1345. m.s[cfsTypeInit3].addf("$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
  1346. of tyPtr, tyRange, tyUncheckedArray: genTypeInfoAux(m, t, t, result, info)
  1347. of tyArray: genArrayInfo(m, t, result, info)
  1348. of tySet: genSetInfo(m, t, result, info)
  1349. of tyEnum: genEnumInfo(m, t, result, info)
  1350. of tyObject:
  1351. genObjectInfo(m, t, origType, result, info)
  1352. of tyTuple:
  1353. # if t.n != nil: genObjectInfo(m, t, result)
  1354. # else:
  1355. # BUGFIX: use consistently RTTI without proper field names; otherwise
  1356. # results are not deterministic!
  1357. genTupleInfo(m, t, origType, result, info)
  1358. of tyOpenArray:
  1359. let x = openArrayToTuple(m, t)
  1360. genTupleInfo(m, x, origType, result, info)
  1361. else: internalError(m.config, "genTypeInfoV1(" & $t.kind & ')')
  1362. if t.attachedOps[attachedDeepCopy] != nil:
  1363. genDeepCopyProc(m, t.attachedOps[attachedDeepCopy], result)
  1364. elif origType.attachedOps[attachedDeepCopy] != nil:
  1365. genDeepCopyProc(m, origType.attachedOps[attachedDeepCopy], result)
  1366. if optTinyRtti in m.config.globalOptions and t.kind == tyObject and sfImportc notin t.sym.flags:
  1367. let v2info = genTypeInfoV2(m, origType, info)
  1368. addf(m.s[cfsTypeInit3], "$1->typeInfoV1 = (void*)&$2; $2.typeInfoV2 = (void*)$1;$n", [
  1369. v2info, result])
  1370. result = prefixTI.rope & result & ")".rope
  1371. proc genTypeSection(m: BModule, n: PNode) =
  1372. discard