ccgtypes.nim 48 KB

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