ccgtypes.nim 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  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: 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: 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, "0")
  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, rectype: PType): Rope =
  393. if (rectype.sym != nil) and
  394. ({sfImportc, sfExportc} * rectype.sym.flags != {}):
  395. result = field.loc.r
  396. else:
  397. result = rope(mangleField(m, field.name))
  398. if result == nil: internalError(m.config, field.info, "mangleRecFieldName")
  399. proc genRecordFieldsAux(m: BModule, n: PNode,
  400. accessExpr: Rope, rectype: PType,
  401. check: var IntSet): Rope =
  402. result = nil
  403. case n.kind
  404. of nkRecList:
  405. for i in countup(0, sonsLen(n) - 1):
  406. add(result, genRecordFieldsAux(m, n.sons[i], accessExpr, rectype, check))
  407. of nkRecCase:
  408. if n.sons[0].kind != nkSym: internalError(m.config, n.info, "genRecordFieldsAux")
  409. add(result, genRecordFieldsAux(m, n.sons[0], accessExpr, rectype, check))
  410. # prefix mangled name with "_U" to avoid clashes with other field names,
  411. # since identifiers are not allowed to start with '_'
  412. let uname = rope("_U" & mangle(n.sons[0].sym.name.s))
  413. let ae = if accessExpr != nil: "$1.$2" % [accessExpr, uname]
  414. else: uname
  415. var unionBody: Rope = nil
  416. for i in countup(1, sonsLen(n) - 1):
  417. case n.sons[i].kind
  418. of nkOfBranch, nkElse:
  419. let k = lastSon(n.sons[i])
  420. if k.kind != nkSym:
  421. let sname = "S" & rope(i)
  422. let a = genRecordFieldsAux(m, k, "$1.$2" % [ae, sname], rectype,
  423. check)
  424. if a != nil:
  425. if tfPacked notin rectype.flags:
  426. add(unionBody, "struct {")
  427. else:
  428. if hasAttribute in CC[m.config.cCompiler].props:
  429. add(unionBody, "struct __attribute__((__packed__)){" )
  430. else:
  431. addf(unionBody, "#pragma pack(push, 1)$nstruct{", [])
  432. add(unionBody, a)
  433. addf(unionBody, "} $1;$n", [sname])
  434. if tfPacked in rectype.flags and hasAttribute notin CC[m.config.cCompiler].props:
  435. addf(unionBody, "#pragma pack(pop)$n", [])
  436. else:
  437. add(unionBody, genRecordFieldsAux(m, k, ae, rectype, check))
  438. else: internalError(m.config, "genRecordFieldsAux(record case branch)")
  439. if unionBody != nil:
  440. addf(result, "union{$n$1} $2;$n", [unionBody, uname])
  441. of nkSym:
  442. let field = n.sym
  443. if field.typ.kind == tyVoid: return
  444. #assert(field.ast == nil)
  445. let sname = mangleRecFieldName(m, field, rectype)
  446. let ae = if accessExpr != nil: "$1.$2" % [accessExpr, sname]
  447. else: sname
  448. fillLoc(field.loc, locField, n, ae, OnUnknown)
  449. # for importcpp'ed objects, we only need to set field.loc, but don't
  450. # have to recurse via 'getTypeDescAux'. And not doing so prevents problems
  451. # with heavily templatized C++ code:
  452. if not isImportedCppType(rectype):
  453. let fieldType = field.loc.lode.typ.skipTypes(abstractInst)
  454. if fieldType.kind == tyArray and tfUncheckedArray in fieldType.flags:
  455. addf(result, "$1 $2[SEQ_DECL_SIZE];$n",
  456. [getTypeDescAux(m, fieldType.elemType, check), sname])
  457. elif fieldType.kind == tySequence and m.config.selectedGC != gcDestructors:
  458. # we need to use a weak dependency here for trecursive_table.
  459. addf(result, "$1 $2;$n", [getTypeDescWeak(m, field.loc.t, check), sname])
  460. elif field.bitsize != 0:
  461. addf(result, "$1 $2:$3;$n", [getTypeDescAux(m, field.loc.t, check), sname, rope($field.bitsize)])
  462. else:
  463. # don't use fieldType here because we need the
  464. # tyGenericInst for C++ template support
  465. addf(result, "$1 $2;$n", [getTypeDescAux(m, field.loc.t, check), sname])
  466. else: internalError(m.config, n.info, "genRecordFieldsAux()")
  467. proc getRecordFields(m: BModule, typ: PType, check: var IntSet): Rope =
  468. result = genRecordFieldsAux(m, typ.n, nil, typ, check)
  469. proc fillObjectFields*(m: BModule; typ: PType) =
  470. # sometimes generic objects are not consistently merged. We patch over
  471. # this fact here.
  472. var check = initIntSet()
  473. discard getRecordFields(m, typ, check)
  474. proc getRecordDesc(m: BModule, typ: PType, name: Rope,
  475. check: var IntSet): Rope =
  476. # declare the record:
  477. var hasField = false
  478. if tfPacked in typ.flags:
  479. if hasAttribute in CC[m.config.cCompiler].props:
  480. result = structOrUnion(typ) & " __attribute__((__packed__))"
  481. else:
  482. result = "#pragma pack(push, 1)\L" & structOrUnion(typ)
  483. else:
  484. result = structOrUnion(typ)
  485. result.add " "
  486. result.add name
  487. if typ.kind == tyObject:
  488. if typ.sons[0] == nil:
  489. if (typ.sym != nil and sfPure in typ.sym.flags) or tfFinal in typ.flags:
  490. appcg(m, result, " {$n", [])
  491. else:
  492. appcg(m, result, " {$n#TNimType* m_type;$n", [])
  493. hasField = true
  494. elif m.compileToCpp:
  495. appcg(m, result, " : public $1 {$n",
  496. [getTypeDescAux(m, typ.sons[0].skipTypes(skipPtrs), check)])
  497. if typ.isException:
  498. appcg(m, result, "virtual void raise() {throw *this;}$n") # required for polymorphic exceptions
  499. if typ.sym.magic == mException:
  500. # Add cleanup destructor to Exception base class
  501. appcg(m, result, "~$1() {if(this->raise_id) popCurrentExceptionEx(this->raise_id);}$n", [name])
  502. # hack: forward declare popCurrentExceptionEx() on top of type description,
  503. # proper request to generate popCurrentExceptionEx not possible for 2 reasons:
  504. # generated function will be below declared Exception type and circular dependency
  505. # between Exception and popCurrentExceptionEx function
  506. result = genProcHeader(m, magicsys.getCompilerProc(m.g.graph, "popCurrentExceptionEx")) & ";" & result
  507. hasField = true
  508. else:
  509. appcg(m, result, " {$n $1 Sup;$n",
  510. [getTypeDescAux(m, typ.sons[0].skipTypes(skipPtrs), check)])
  511. hasField = true
  512. else:
  513. addf(result, " {$n", [name])
  514. let desc = getRecordFields(m, typ, check)
  515. if desc == nil and not hasField:
  516. addf(result, "char dummy;$n", [])
  517. else:
  518. add(result, desc)
  519. add(result, "};\L")
  520. if tfPacked in typ.flags and hasAttribute notin CC[m.config.cCompiler].props:
  521. result.add "#pragma pack(pop)\L"
  522. proc getTupleDesc(m: BModule, typ: PType, name: Rope,
  523. check: var IntSet): Rope =
  524. result = "$1 $2 {$n" % [structOrUnion(typ), name]
  525. var desc: Rope = nil
  526. for i in countup(0, sonsLen(typ) - 1):
  527. addf(desc, "$1 Field$2;$n",
  528. [getTypeDescAux(m, typ.sons[i], check), rope(i)])
  529. if desc == nil: add(result, "char dummy;\L")
  530. else: add(result, desc)
  531. add(result, "};\L")
  532. proc scanCppGenericSlot(pat: string, cursor, outIdx, outStars: var int): bool =
  533. # A helper proc for handling cppimport patterns, involving numeric
  534. # placeholders for generic types (e.g. '0, '**2, etc).
  535. # pre: the cursor must be placed at the ' symbol
  536. # post: the cursor will be placed after the final digit
  537. # false will returned if the input is not recognized as a placeholder
  538. inc cursor
  539. let begin = cursor
  540. while pat[cursor] == '*': inc cursor
  541. if pat[cursor] in Digits:
  542. outIdx = pat[cursor].ord - '0'.ord
  543. outStars = cursor - begin
  544. inc cursor
  545. return true
  546. else:
  547. return false
  548. proc resolveStarsInCppType(typ: PType, idx, stars: int): PType =
  549. # Make sure the index refers to one of the generic params of the type.
  550. # XXX: we should catch this earlier and report it as a semantic error.
  551. if idx >= typ.len:
  552. doAssert false, "invalid apostrophe type parameter index"
  553. result = typ.sons[idx]
  554. for i in 1..stars:
  555. if result != nil and result.len > 0:
  556. result = if result.kind == tyGenericInst: result.sons[1]
  557. else: result.elemType
  558. proc getSeqPayloadType(m: BModule; t: PType): Rope =
  559. result = getTypeForward(m, t, hashType(t)) & "_Content"
  560. when false:
  561. var check = initIntSet()
  562. # XXX remove this duplication:
  563. appcg(m, m.s[cfsSeqTypes],
  564. "struct $2_Content { NI cap; void* allocator; $1 data[SEQ_DECL_SIZE]; };$n",
  565. [getTypeDescAux(m, t.sons[0], check), result])
  566. proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet): Rope =
  567. # returns only the type's name
  568. var t = origTyp.skipTypes(irrelevantForBackend)
  569. if containsOrIncl(check, t.id):
  570. if not (isImportedCppType(origTyp) or isImportedCppType(t)):
  571. internalError(m.config, "cannot generate C type for: " & typeToString(origTyp))
  572. # XXX: this BUG is hard to fix -> we need to introduce helper structs,
  573. # but determining when this needs to be done is hard. We should split
  574. # C type generation into an analysis and a code generation phase somehow.
  575. if t.sym != nil: useHeader(m, t.sym)
  576. if t != origTyp and origTyp.sym != nil: useHeader(m, origTyp.sym)
  577. let sig = hashType(origTyp)
  578. result = getTypePre(m, t, sig)
  579. if result != nil:
  580. excl(check, t.id)
  581. return
  582. case t.kind
  583. of tyRef, tyOptAsRef, tyPtr, tyVar, tyLent:
  584. var star = if t.kind == tyVar and tfVarIsPtr notin origTyp.flags and
  585. compileToCpp(m): "&" else: "*"
  586. var et = origTyp.skipTypes(abstractInst).lastSon
  587. var etB = et.skipTypes(abstractInst)
  588. if mapType(m.config, t) == ctPtrToArray:
  589. if etB.kind == tySet:
  590. et = getSysType(m.g.graph, unknownLineInfo(), tyUInt8)
  591. else:
  592. et = elemType(etB)
  593. etB = et.skipTypes(abstractInst)
  594. star[0] = '*'
  595. case etB.kind
  596. of tyObject, tyTuple:
  597. if isImportedCppType(etB) and et.kind == tyGenericInst:
  598. result = getTypeDescAux(m, et, check) & star
  599. else:
  600. # no restriction! We have a forward declaration for structs
  601. let name = getTypeForward(m, et, hashType et)
  602. result = name & star
  603. m.typeCache[sig] = result
  604. of tySequence:
  605. # no restriction! We have a forward declaration for structs
  606. let name = getTypeForward(m, et, hashType et)
  607. result = name & seqStar(m) & star
  608. m.typeCache[sig] = result
  609. pushType(m, et)
  610. else:
  611. # else we have a strong dependency :-(
  612. result = getTypeDescAux(m, et, check) & star
  613. m.typeCache[sig] = result
  614. of tyOpenArray, tyVarargs:
  615. result = getTypeDescWeak(m, t.sons[0], check) & "*"
  616. m.typeCache[sig] = result
  617. of tyEnum:
  618. result = cacheGetType(m.typeCache, sig)
  619. if result == nil:
  620. result = getTypeName(m, origTyp, sig)
  621. if not (isImportedCppType(t) or
  622. (sfImportc in t.sym.flags and t.sym.magic == mNone)):
  623. m.typeCache[sig] = result
  624. var size: int
  625. if firstOrd(m.config, t) < 0:
  626. addf(m.s[cfsTypes], "typedef NI32 $1;$n", [result])
  627. size = 4
  628. else:
  629. size = int(getSize(m.config, t))
  630. case size
  631. of 1: addf(m.s[cfsTypes], "typedef NU8 $1;$n", [result])
  632. of 2: addf(m.s[cfsTypes], "typedef NU16 $1;$n", [result])
  633. of 4: addf(m.s[cfsTypes], "typedef NI32 $1;$n", [result])
  634. of 8: addf(m.s[cfsTypes], "typedef NI64 $1;$n", [result])
  635. else: internalError(m.config, t.sym.info, "getTypeDescAux: enum")
  636. when false:
  637. let owner = hashOwner(t.sym)
  638. if not gDebugInfo.hasEnum(t.sym.name.s, t.sym.info.line, owner):
  639. var vals: seq[(string, int)] = @[]
  640. for i in countup(0, t.n.len - 1):
  641. assert(t.n.sons[i].kind == nkSym)
  642. let field = t.n.sons[i].sym
  643. vals.add((field.name.s, field.position.int))
  644. gDebugInfo.registerEnum(EnumDesc(size: size, owner: owner, id: t.sym.id,
  645. name: t.sym.name.s, values: vals))
  646. of tyProc:
  647. result = getTypeName(m, origTyp, sig)
  648. m.typeCache[sig] = result
  649. var rettype, desc: Rope
  650. genProcParams(m, t, rettype, desc, check, true, true)
  651. if not isImportedType(t):
  652. if t.callConv != ccClosure: # procedure vars may need a closure!
  653. addf(m.s[cfsTypes], "typedef $1_PTR($2, $3) $4;$n",
  654. [rope(CallingConvToStr[t.callConv]), rettype, result, desc])
  655. else:
  656. addf(m.s[cfsTypes], "typedef struct {$n" &
  657. "N_NIMCALL_PTR($2, ClP_0) $3;$n" &
  658. "void* ClE_0;$n} $1;$n",
  659. [result, rettype, desc])
  660. of tySequence:
  661. # we cannot use getTypeForward here because then t would be associated
  662. # with the name of the struct, not with the pointer to the struct:
  663. result = cacheGetType(m.forwTypeCache, sig)
  664. if result == nil:
  665. result = getTypeName(m, origTyp, sig)
  666. if not isImportedType(t):
  667. addf(m.s[cfsForwardTypes], getForwardStructFormat(m),
  668. [structOrUnion(t), result])
  669. m.forwTypeCache[sig] = result
  670. assert(cacheGetType(m.typeCache, sig) == nil)
  671. m.typeCache[sig] = result & seqStar(m)
  672. if not isImportedType(t):
  673. if skipTypes(t.sons[0], typedescInst).kind != tyEmpty:
  674. const
  675. cppSeq = "struct $2 : #TGenericSeq {$n"
  676. cSeq = "struct $2 {$n" &
  677. " #TGenericSeq Sup;$n"
  678. if m.config.selectedGC == gcDestructors:
  679. appcg(m, m.s[cfsTypes],
  680. "typedef struct{ NI cap;void* allocator;$1 data[SEQ_DECL_SIZE];}$2_Content;$n" &
  681. "struct $2 {$n" &
  682. " NI len; $2_Content* p;$n" &
  683. "};$n", [getTypeDescAux(m, t.sons[0], check), result])
  684. else:
  685. appcg(m, m.s[cfsSeqTypes],
  686. (if m.compileToCpp: cppSeq else: cSeq) &
  687. " $1 data[SEQ_DECL_SIZE];$n" &
  688. "};$n", [getTypeDescAux(m, t.sons[0], check), result])
  689. elif m.config.selectedGC == gcDestructors:
  690. internalError(m.config, "cannot map the empty seq type to a C type")
  691. else:
  692. result = rope("TGenericSeq")
  693. add(result, seqStar(m))
  694. of tyArray:
  695. var n: BiggestInt = lengthOrd(m.config, t)
  696. if n <= 0: n = 1 # make an array of at least one element
  697. result = getTypeName(m, origTyp, sig)
  698. m.typeCache[sig] = result
  699. if not isImportedType(t):
  700. let foo = getTypeDescAux(m, t.sons[1], check)
  701. addf(m.s[cfsTypes], "typedef $1 $2[$3];$n",
  702. [foo, result, rope(n)])
  703. else: addAbiCheck(m, t, result)
  704. of tyObject, tyTuple:
  705. if isImportedCppType(t) and origTyp.kind == tyGenericInst:
  706. let cppName = getTypeName(m, t, sig)
  707. var i = 0
  708. var chunkStart = 0
  709. template addResultType(ty: untyped) =
  710. if ty == nil or ty.kind == tyVoid:
  711. result.add(~"void")
  712. elif ty.kind == tyStatic:
  713. internalAssert m.config, ty.n != nil
  714. result.add ty.n.renderTree
  715. else:
  716. result.add getTypeDescAux(m, ty, check)
  717. while i < cppName.data.len:
  718. if cppName.data[i] == '\'':
  719. var chunkEnd = i-1
  720. var idx, stars: int
  721. if scanCppGenericSlot(cppName.data, i, idx, stars):
  722. result.add cppName.data.substr(chunkStart, chunkEnd)
  723. chunkStart = i
  724. let typeInSlot = resolveStarsInCppType(origTyp, idx + 1, stars)
  725. addResultType(typeInSlot)
  726. else:
  727. inc i
  728. if chunkStart != 0:
  729. result.add cppName.data.substr(chunkStart)
  730. else:
  731. result = cppName & "<"
  732. for i in 1 .. origTyp.len-2:
  733. if i > 1: result.add(" COMMA ")
  734. addResultType(origTyp.sons[i])
  735. result.add("> ")
  736. # always call for sideeffects:
  737. assert t.kind != tyTuple
  738. discard getRecordDesc(m, t, result, check)
  739. # The resulting type will include commas and these won't play well
  740. # with the C macros for defining procs such as N_NIMCALL. We must
  741. # create a typedef for the type and use it in the proc signature:
  742. let typedefName = ~"TY" & $sig
  743. addf(m.s[cfsTypes], "typedef $1 $2;$n", [result, typedefName])
  744. m.typeCache[sig] = typedefName
  745. result = typedefName
  746. else:
  747. when false:
  748. if t.sym != nil and t.sym.name.s == "KeyValuePair":
  749. if t == origTyp:
  750. echo "wtf: came here"
  751. writeStackTrace()
  752. quit 1
  753. result = cacheGetType(m.forwTypeCache, sig)
  754. if result == nil:
  755. when false:
  756. if t.sym != nil and t.sym.name.s == "KeyValuePair":
  757. # or {sfImportc, sfExportc} * t.sym.flags == {}:
  758. if t.loc.r != nil:
  759. echo t.kind, " ", hashType t
  760. echo origTyp.kind, " ", sig
  761. assert t.loc.r == nil
  762. result = getTypeName(m, origTyp, sig)
  763. m.forwTypeCache[sig] = result
  764. if not isImportedType(t):
  765. addf(m.s[cfsForwardTypes], getForwardStructFormat(m),
  766. [structOrUnion(t), result])
  767. assert m.forwTypeCache[sig] == result
  768. m.typeCache[sig] = result # always call for sideeffects:
  769. if not incompleteType(t):
  770. let recdesc = if t.kind != tyTuple: getRecordDesc(m, t, result, check)
  771. else: getTupleDesc(m, t, result, check)
  772. if not isImportedType(t):
  773. add(m.s[cfsTypes], recdesc)
  774. elif tfIncompleteStruct notin t.flags: addAbiCheck(m, t, result)
  775. of tySet:
  776. result = $t.kind & '_' & getTypeName(m, t.lastSon, hashType t.lastSon)
  777. m.typeCache[sig] = result
  778. if not isImportedType(t):
  779. let s = int(getSize(m.config, t))
  780. case s
  781. of 1, 2, 4, 8: addf(m.s[cfsTypes], "typedef NU$2 $1;$n", [result, rope(s*8)])
  782. else: addf(m.s[cfsTypes], "typedef NU8 $1[$2];$n",
  783. [result, rope(getSize(m.config, t))])
  784. of tyGenericInst, tyDistinct, tyOrdinal, tyTypeDesc, tyAlias, tySink,
  785. tyUserTypeClass, tyUserTypeClassInst, tyInferred:
  786. result = getTypeDescAux(m, lastSon(t), check)
  787. else:
  788. internalError(m.config, "getTypeDescAux(" & $t.kind & ')')
  789. result = nil
  790. # fixes bug #145:
  791. excl(check, t.id)
  792. proc getTypeDesc(m: BModule, typ: PType): Rope =
  793. var check = initIntSet()
  794. result = getTypeDescAux(m, typ, check)
  795. type
  796. TClosureTypeKind = enum
  797. clHalf, clHalfWithEnv, clFull
  798. proc getClosureType(m: BModule, t: PType, kind: TClosureTypeKind): Rope =
  799. assert t.kind == tyProc
  800. var check = initIntSet()
  801. result = getTempName(m)
  802. var rettype, desc: Rope
  803. genProcParams(m, t, rettype, desc, check, declareEnvironment=kind != clHalf)
  804. if not isImportedType(t):
  805. if t.callConv != ccClosure or kind != clFull:
  806. addf(m.s[cfsTypes], "typedef $1_PTR($2, $3) $4;$n",
  807. [rope(CallingConvToStr[t.callConv]), rettype, result, desc])
  808. else:
  809. addf(m.s[cfsTypes], "typedef struct {$n" &
  810. "N_NIMCALL_PTR($2, ClP_0) $3;$n" &
  811. "void* ClE_0;$n} $1;$n",
  812. [result, rettype, desc])
  813. proc finishTypeDescriptions(m: BModule) =
  814. var i = 0
  815. while i < len(m.typeStack):
  816. discard getTypeDesc(m, m.typeStack[i])
  817. inc(i)
  818. template cgDeclFrmt*(s: PSym): string = s.constraint.strVal
  819. proc genProcHeader(m: BModule, prc: PSym): Rope =
  820. var
  821. rettype, params: Rope
  822. genCLineDir(result, prc.info, m.config)
  823. # using static is needed for inline procs
  824. if lfExportLib in prc.loc.flags:
  825. if isHeaderFile in m.flags:
  826. result.add "N_LIB_IMPORT "
  827. else:
  828. result.add "N_LIB_EXPORT "
  829. elif prc.typ.callConv == ccInline:
  830. result.add "static "
  831. elif {sfImportc, sfExportc} * prc.flags == {}:
  832. result.add "N_LIB_PRIVATE "
  833. var check = initIntSet()
  834. fillLoc(prc.loc, locProc, prc.ast[namePos], mangleName(m, prc), OnUnknown)
  835. genProcParams(m, prc.typ, rettype, params, check)
  836. # careful here! don't access ``prc.ast`` as that could reload large parts of
  837. # the object graph!
  838. if prc.constraint.isNil:
  839. addf(result, "$1($2, $3)$4",
  840. [rope(CallingConvToStr[prc.typ.callConv]), rettype, prc.loc.r,
  841. params])
  842. else:
  843. result = prc.cgDeclFrmt % [rettype, prc.loc.r, params]
  844. # ------------------ type info generation -------------------------------------
  845. proc genTypeInfo(m: BModule, t: PType; info: TLineInfo): Rope
  846. proc getNimNode(m: BModule): Rope =
  847. result = "$1[$2]" % [m.typeNodesName, rope(m.typeNodes)]
  848. inc(m.typeNodes)
  849. proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
  850. name, base: Rope; info: TLineInfo) =
  851. var nimtypeKind: int
  852. #allocMemTI(m, typ, name)
  853. if isObjLackingTypeField(typ):
  854. nimtypeKind = ord(tyPureObject)
  855. else:
  856. nimtypeKind = ord(typ.kind)
  857. var size: Rope
  858. if tfIncompleteStruct in typ.flags: size = rope"void*"
  859. else: size = getTypeDesc(m, origType)
  860. addf(m.s[cfsTypeInit3],
  861. "$1.size = sizeof($2);$n" & "$1.kind = $3;$n" & "$1.base = $4;$n",
  862. [name, size, rope(nimtypeKind), base])
  863. # compute type flags for GC optimization
  864. var flags = 0
  865. if not containsGarbageCollectedRef(typ): flags = flags or 1
  866. if not canFormAcycle(typ): flags = flags or 2
  867. #else MessageOut("can contain a cycle: " & typeToString(typ))
  868. if flags != 0:
  869. addf(m.s[cfsTypeInit3], "$1.flags = $2;$n", [name, rope(flags)])
  870. discard cgsym(m, "TNimType")
  871. if isDefined(m.config, "nimTypeNames"):
  872. var typename = typeToString(if origType.typeInst != nil: origType.typeInst
  873. else: origType, preferName)
  874. if typename == "ref object" and origType.skipTypes(skipPtrs).sym != nil:
  875. typename = "anon ref object from " & m.config$origType.skipTypes(skipPtrs).sym.info
  876. addf(m.s[cfsTypeInit3], "$1.name = $2;$n",
  877. [name, makeCstring typename])
  878. discard cgsym(m, "nimTypeRoot")
  879. addf(m.s[cfsTypeInit3], "$1.nextType = nimTypeRoot; nimTypeRoot=&$1;$n",
  880. [name])
  881. addf(m.s[cfsVars], "TNimType $1;$n", [name])
  882. proc genTypeInfoAux(m: BModule, typ, origType: PType, name: Rope;
  883. info: TLineInfo) =
  884. var base: Rope
  885. if sonsLen(typ) > 0 and typ.lastSon != nil:
  886. var x = typ.lastSon
  887. if typ.kind == tyObject: x = x.skipTypes(skipPtrs)
  888. if typ.kind == tyPtr and x.kind == tyObject and incompleteType(x):
  889. base = rope("0")
  890. else:
  891. base = genTypeInfo(m, x, info)
  892. else:
  893. base = rope("0")
  894. genTypeInfoAuxBase(m, typ, origType, name, base, info)
  895. proc discriminatorTableName(m: BModule, objtype: PType, d: PSym): Rope =
  896. # bugfix: we need to search the type that contains the discriminator:
  897. var objtype = objtype
  898. while lookupInRecord(objtype.n, d.name) == nil:
  899. objtype = objtype.sons[0]
  900. if objtype.sym == nil:
  901. internalError(m.config, d.info, "anonymous obj with discriminator")
  902. result = "NimDT_$1_$2" % [rope($hashType(objtype)), rope(d.name.s.mangle)]
  903. proc discriminatorTableDecl(m: BModule, objtype: PType, d: PSym): Rope =
  904. discard cgsym(m, "TNimNode")
  905. var tmp = discriminatorTableName(m, objtype, d)
  906. result = "TNimNode* $1[$2];$n" % [tmp, rope(lengthOrd(m.config, d.typ)+1)]
  907. proc genObjectFields(m: BModule, typ, origType: PType, n: PNode, expr: Rope;
  908. info: TLineInfo) =
  909. case n.kind
  910. of nkRecList:
  911. var L = sonsLen(n)
  912. if L == 1:
  913. genObjectFields(m, typ, origType, n.sons[0], expr, info)
  914. elif L > 0:
  915. var tmp = getTempName(m)
  916. addf(m.s[cfsTypeInit1], "static TNimNode* $1[$2];$n", [tmp, rope(L)])
  917. for i in countup(0, L-1):
  918. var tmp2 = getNimNode(m)
  919. addf(m.s[cfsTypeInit3], "$1[$2] = &$3;$n", [tmp, rope(i), tmp2])
  920. genObjectFields(m, typ, origType, n.sons[i], tmp2, info)
  921. addf(m.s[cfsTypeInit3], "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n",
  922. [expr, rope(L), tmp])
  923. else:
  924. addf(m.s[cfsTypeInit3], "$1.len = $2; $1.kind = 2;$n", [expr, rope(L)])
  925. of nkRecCase:
  926. assert(n.sons[0].kind == nkSym)
  927. var field = n.sons[0].sym
  928. var tmp = discriminatorTableName(m, typ, field)
  929. var L = lengthOrd(m.config, field.typ)
  930. assert L > 0
  931. if field.loc.r == nil: fillObjectFields(m, typ)
  932. if field.loc.t == nil:
  933. internalError(m.config, n.info, "genObjectFields")
  934. addf(m.s[cfsTypeInit3], "$1.kind = 3;$n" &
  935. "$1.offset = offsetof($2, $3);$n" & "$1.typ = $4;$n" &
  936. "$1.name = $5;$n" & "$1.sons = &$6[0];$n" &
  937. "$1.len = $7;$n", [expr, getTypeDesc(m, origType), field.loc.r,
  938. genTypeInfo(m, field.typ, info),
  939. makeCString(field.name.s),
  940. tmp, rope(L)])
  941. addf(m.s[cfsData], "TNimNode* $1[$2];$n", [tmp, rope(L+1)])
  942. for i in countup(1, sonsLen(n)-1):
  943. var b = n.sons[i] # branch
  944. var tmp2 = getNimNode(m)
  945. genObjectFields(m, typ, origType, lastSon(b), tmp2, info)
  946. case b.kind
  947. of nkOfBranch:
  948. if sonsLen(b) < 2:
  949. internalError(m.config, b.info, "genObjectFields; nkOfBranch broken")
  950. for j in countup(0, sonsLen(b) - 2):
  951. if b.sons[j].kind == nkRange:
  952. var x = int(getOrdValue(b.sons[j].sons[0]))
  953. var y = int(getOrdValue(b.sons[j].sons[1]))
  954. while x <= y:
  955. addf(m.s[cfsTypeInit3], "$1[$2] = &$3;$n", [tmp, rope(x), tmp2])
  956. inc(x)
  957. else:
  958. addf(m.s[cfsTypeInit3], "$1[$2] = &$3;$n",
  959. [tmp, rope(getOrdValue(b.sons[j])), tmp2])
  960. of nkElse:
  961. addf(m.s[cfsTypeInit3], "$1[$2] = &$3;$n",
  962. [tmp, rope(L), tmp2])
  963. else: internalError(m.config, n.info, "genObjectFields(nkRecCase)")
  964. of nkSym:
  965. var field = n.sym
  966. if field.bitsize == 0:
  967. if field.loc.r == nil: fillObjectFields(m, typ)
  968. if field.loc.t == nil:
  969. internalError(m.config, n.info, "genObjectFields")
  970. addf(m.s[cfsTypeInit3], "$1.kind = 1;$n" &
  971. "$1.offset = offsetof($2, $3);$n" & "$1.typ = $4;$n" &
  972. "$1.name = $5;$n", [expr, getTypeDesc(m, origType),
  973. field.loc.r, genTypeInfo(m, field.typ, info), makeCString(field.name.s)])
  974. else: internalError(m.config, n.info, "genObjectFields")
  975. proc genObjectInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo) =
  976. if typ.kind == tyObject:
  977. if incompleteType(typ):
  978. localError(m.config, info, "request for RTTI generation for incomplete object: " &
  979. typeToString(typ))
  980. genTypeInfoAux(m, typ, origType, name, info)
  981. else:
  982. genTypeInfoAuxBase(m, typ, origType, name, rope("0"), info)
  983. var tmp = getNimNode(m)
  984. if not isImportedType(typ):
  985. genObjectFields(m, typ, origType, typ.n, tmp, info)
  986. addf(m.s[cfsTypeInit3], "$1.node = &$2;$n", [name, tmp])
  987. var t = typ.sons[0]
  988. while t != nil:
  989. t = t.skipTypes(skipPtrs)
  990. t.flags.incl tfObjHasKids
  991. t = t.sons[0]
  992. proc genTupleInfo(m: BModule, typ, origType: PType, name: Rope; info: TLineInfo) =
  993. genTypeInfoAuxBase(m, typ, typ, name, rope("0"), info)
  994. var expr = getNimNode(m)
  995. var length = sonsLen(typ)
  996. if length > 0:
  997. var tmp = getTempName(m)
  998. addf(m.s[cfsTypeInit1], "static TNimNode* $1[$2];$n", [tmp, rope(length)])
  999. for i in countup(0, length - 1):
  1000. var a = typ.sons[i]
  1001. var tmp2 = getNimNode(m)
  1002. addf(m.s[cfsTypeInit3], "$1[$2] = &$3;$n", [tmp, rope(i), tmp2])
  1003. addf(m.s[cfsTypeInit3], "$1.kind = 1;$n" &
  1004. "$1.offset = offsetof($2, Field$3);$n" &
  1005. "$1.typ = $4;$n" &
  1006. "$1.name = \"Field$3\";$n",
  1007. [tmp2, getTypeDesc(m, origType), rope(i), genTypeInfo(m, a, info)])
  1008. addf(m.s[cfsTypeInit3], "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n",
  1009. [expr, rope(length), tmp])
  1010. else:
  1011. addf(m.s[cfsTypeInit3], "$1.len = $2; $1.kind = 2;$n",
  1012. [expr, rope(length)])
  1013. addf(m.s[cfsTypeInit3], "$1.node = &$2;$n", [name, expr])
  1014. proc genEnumInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1015. # Type information for enumerations is quite heavy, so we do some
  1016. # optimizations here: The ``typ`` field is never set, as it is redundant
  1017. # anyway. We generate a cstring array and a loop over it. Exceptional
  1018. # positions will be reset after the loop.
  1019. genTypeInfoAux(m, typ, typ, name, info)
  1020. var nodePtrs = getTempName(m)
  1021. var length = sonsLen(typ.n)
  1022. addf(m.s[cfsTypeInit1], "static TNimNode* $1[$2];$n",
  1023. [nodePtrs, rope(length)])
  1024. var enumNames, specialCases: Rope
  1025. var firstNimNode = m.typeNodes
  1026. var hasHoles = false
  1027. for i in countup(0, length - 1):
  1028. assert(typ.n.sons[i].kind == nkSym)
  1029. var field = typ.n.sons[i].sym
  1030. var elemNode = getNimNode(m)
  1031. if field.ast == nil:
  1032. # no explicit string literal for the enum field, so use field.name:
  1033. add(enumNames, makeCString(field.name.s))
  1034. else:
  1035. add(enumNames, makeCString(field.ast.strVal))
  1036. if i < length - 1: add(enumNames, ", \L")
  1037. if field.position != i or tfEnumHasHoles in typ.flags:
  1038. addf(specialCases, "$1.offset = $2;$n", [elemNode, rope(field.position)])
  1039. hasHoles = true
  1040. var enumArray = getTempName(m)
  1041. var counter = getTempName(m)
  1042. addf(m.s[cfsTypeInit1], "NI $1;$n", [counter])
  1043. addf(m.s[cfsTypeInit1], "static char* NIM_CONST $1[$2] = {$n$3};$n",
  1044. [enumArray, rope(length), enumNames])
  1045. addf(m.s[cfsTypeInit3], "for ($1 = 0; $1 < $2; $1++) {$n" &
  1046. "$3[$1+$4].kind = 1;$n" & "$3[$1+$4].offset = $1;$n" &
  1047. "$3[$1+$4].name = $5[$1];$n" & "$6[$1] = &$3[$1+$4];$n" & "}$n", [counter,
  1048. rope(length), m.typeNodesName, rope(firstNimNode), enumArray, nodePtrs])
  1049. add(m.s[cfsTypeInit3], specialCases)
  1050. addf(m.s[cfsTypeInit3],
  1051. "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n",
  1052. [getNimNode(m), rope(length), nodePtrs, name])
  1053. if hasHoles:
  1054. # 1 << 2 is {ntfEnumHole}
  1055. addf(m.s[cfsTypeInit3], "$1.flags = 1<<2;$n", [name])
  1056. proc genSetInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1057. assert(typ.sons[0] != nil)
  1058. genTypeInfoAux(m, typ, typ, name, info)
  1059. var tmp = getNimNode(m)
  1060. addf(m.s[cfsTypeInit3], "$1.len = $2; $1.kind = 0;$n" & "$3.node = &$1;$n",
  1061. [tmp, rope(firstOrd(m.config, typ)), name])
  1062. proc genArrayInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
  1063. genTypeInfoAuxBase(m, typ, typ, name, genTypeInfo(m, typ.sons[1], info), info)
  1064. proc fakeClosureType(m: BModule; owner: PSym): PType =
  1065. # we generate the same RTTI as for a tuple[pointer, ref tuple[]]
  1066. result = newType(tyTuple, owner)
  1067. result.rawAddSon(newType(tyPointer, owner))
  1068. var r = newType(tyRef, owner)
  1069. let obj = createObj(m.g.graph, owner, owner.info, final=false)
  1070. r.rawAddSon(obj)
  1071. result.rawAddSon(r)
  1072. include ccgtrav
  1073. proc genDeepCopyProc(m: BModule; s: PSym; result: Rope) =
  1074. genProc(m, s)
  1075. addf(m.s[cfsTypeInit3], "$1.deepcopy =(void* (N_RAW_NIMCALL*)(void*))$2;$n",
  1076. [result, s.loc.r])
  1077. proc genTypeInfo(m: BModule, t: PType; info: TLineInfo): Rope =
  1078. let origType = t
  1079. var t = skipTypes(origType, irrelevantForBackend + tyUserTypeClasses)
  1080. let sig = hashType(origType)
  1081. result = m.typeInfoMarker.getOrDefault(sig)
  1082. if result != nil:
  1083. return "(&".rope & result & ")".rope
  1084. result = m.g.typeInfoMarker.getOrDefault(sig)
  1085. if result != nil:
  1086. discard cgsym(m, "TNimType")
  1087. discard cgsym(m, "TNimNode")
  1088. addf(m.s[cfsVars], "extern TNimType $1;$n", [result])
  1089. # also store in local type section:
  1090. m.typeInfoMarker[sig] = result
  1091. return "(&".rope & result & ")".rope
  1092. result = "NTI$1_" % [rope($sig)]
  1093. m.typeInfoMarker[sig] = result
  1094. let owner = t.skipTypes(typedescPtrs).owner.getModule
  1095. if owner != m.module:
  1096. # make sure the type info is created in the owner module
  1097. discard genTypeInfo(m.g.modules[owner.position], origType, info)
  1098. # reference the type info as extern here
  1099. discard cgsym(m, "TNimType")
  1100. discard cgsym(m, "TNimNode")
  1101. addf(m.s[cfsVars], "extern TNimType $1;$n", [result])
  1102. return "(&".rope & result & ")".rope
  1103. m.g.typeInfoMarker[sig] = result
  1104. case t.kind
  1105. of tyEmpty, tyVoid: result = rope"0"
  1106. of tyPointer, tyBool, tyChar, tyCString, tyString, tyInt..tyUInt64, tyVar, tyLent:
  1107. genTypeInfoAuxBase(m, t, t, result, rope"0", info)
  1108. of tyStatic:
  1109. if t.n != nil: result = genTypeInfo(m, lastSon t, info)
  1110. else: internalError(m.config, "genTypeInfo(" & $t.kind & ')')
  1111. of tyUserTypeClasses:
  1112. internalAssert m.config, t.isResolvedUserTypeClass
  1113. return genTypeInfo(m, t.lastSon, info)
  1114. of tyProc:
  1115. if t.callConv != ccClosure:
  1116. genTypeInfoAuxBase(m, t, t, result, rope"0", info)
  1117. else:
  1118. let x = fakeClosureType(m, t.owner)
  1119. genTupleInfo(m, x, x, result, info)
  1120. of tySequence:
  1121. if m.config.selectedGC != gcDestructors:
  1122. genTypeInfoAux(m, t, t, result, info)
  1123. if m.config.selectedGC >= gcMarkAndSweep:
  1124. let markerProc = genTraverseProc(m, origType, sig)
  1125. addf(m.s[cfsTypeInit3], "$1.marker = $2;$n", [result, markerProc])
  1126. of tyRef, tyOptAsRef:
  1127. genTypeInfoAux(m, t, t, result, info)
  1128. if m.config.selectedGC >= gcMarkAndSweep:
  1129. let markerProc = genTraverseProc(m, origType, sig)
  1130. addf(m.s[cfsTypeInit3], "$1.marker = $2;$n", [result, markerProc])
  1131. of tyPtr, tyRange: genTypeInfoAux(m, t, t, result, info)
  1132. of tyArray: genArrayInfo(m, t, result, info)
  1133. of tySet: genSetInfo(m, t, result, info)
  1134. of tyEnum: genEnumInfo(m, t, result, info)
  1135. of tyObject: genObjectInfo(m, t, origType, result, info)
  1136. of tyTuple:
  1137. # if t.n != nil: genObjectInfo(m, t, result)
  1138. # else:
  1139. # BUGFIX: use consistently RTTI without proper field names; otherwise
  1140. # results are not deterministic!
  1141. genTupleInfo(m, t, origType, result, info)
  1142. else: internalError(m.config, "genTypeInfo(" & $t.kind & ')')
  1143. if t.deepCopy != nil:
  1144. genDeepCopyProc(m, t.deepCopy, result)
  1145. elif origType.deepCopy != nil:
  1146. genDeepCopyProc(m, origType.deepCopy, result)
  1147. result = "(&".rope & result & ")".rope
  1148. proc genTypeSection(m: BModule, n: PNode) =
  1149. discard