ccgtypes.nim 62 KB

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