ccgtypes.nim 62 KB

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