ccgtypes.nim 55 KB

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