ccgtypes.nim 48 KB

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