ccgtypes.nim 54 KB

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