semmagic.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This include file implements the semantic checking for magics.
  10. # included from sem.nim
  11. proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode
  12. proc addDefaultFieldForNew(c: PContext, n: PNode): PNode =
  13. result = n
  14. let typ = result[1].typ # new(x)
  15. if typ.skipTypes({tyGenericInst, tyAlias, tySink}).kind == tyRef and typ.skipTypes({tyGenericInst, tyAlias, tySink})[0].kind == tyObject:
  16. var asgnExpr = newTree(nkObjConstr, newNodeIT(nkType, result[1].info, typ))
  17. asgnExpr.typ = typ
  18. var t = typ.skipTypes({tyGenericInst, tyAlias, tySink})[0]
  19. var id = initIntSet()
  20. while true:
  21. asgnExpr.sons.add defaultFieldsForTheUninitialized(c, t.n, id)
  22. let base = t[0]
  23. if base == nil:
  24. break
  25. t = skipTypes(base, skipPtrs)
  26. if asgnExpr.sons.len > 1:
  27. result = newTree(nkAsgn, result[1], asgnExpr)
  28. proc semAddrArg(c: PContext; n: PNode): PNode =
  29. let x = semExprWithType(c, n)
  30. if x.kind == nkSym:
  31. x.sym.flags.incl(sfAddrTaken)
  32. if isAssignable(c, x) notin {arLValue, arLocalLValue, arAddressableConst, arLentValue}:
  33. localError(c.config, n.info, errExprHasNoAddress)
  34. result = x
  35. proc semTypeOf(c: PContext; n: PNode): PNode =
  36. var m = BiggestInt 1 # typeOfIter
  37. if n.len == 3:
  38. let mode = semConstExpr(c, n[2])
  39. if mode.kind != nkIntLit:
  40. localError(c.config, n.info, "typeof: cannot evaluate 'mode' parameter at compile-time")
  41. else:
  42. m = mode.intVal
  43. result = newNodeI(nkTypeOfExpr, n.info)
  44. let typExpr = semExprWithType(c, n[1], if m == 1: {efInTypeof} else: {})
  45. result.add typExpr
  46. result.typ = makeTypeDesc(c, typExpr.typ)
  47. type
  48. SemAsgnMode = enum asgnNormal, noOverloadedSubscript, noOverloadedAsgn
  49. proc semAsgn(c: PContext, n: PNode; mode=asgnNormal): PNode
  50. proc semSubscript(c: PContext, n: PNode, flags: TExprFlags): PNode
  51. proc semArrGet(c: PContext; n: PNode; flags: TExprFlags): PNode =
  52. result = newNodeI(nkBracketExpr, n.info)
  53. for i in 1..<n.len: result.add(n[i])
  54. result = semSubscript(c, result, flags)
  55. if result.isNil:
  56. let x = copyTree(n)
  57. x[0] = newIdentNode(getIdent(c.cache, "[]"), n.info)
  58. bracketNotFoundError(c, x)
  59. #localError(c.config, n.info, "could not resolve: " & $n)
  60. result = n
  61. proc semArrPut(c: PContext; n: PNode; flags: TExprFlags): PNode =
  62. # rewrite `[]=`(a, i, x) back to ``a[i] = x``.
  63. let b = newNodeI(nkBracketExpr, n.info)
  64. b.add(n[1].skipAddr)
  65. for i in 2..<n.len-1: b.add(n[i])
  66. result = newNodeI(nkAsgn, n.info, 2)
  67. result[0] = b
  68. result[1] = n.lastSon
  69. result = semAsgn(c, result, noOverloadedSubscript)
  70. proc semAsgnOpr(c: PContext; n: PNode; k: TNodeKind): PNode =
  71. result = newNodeI(k, n.info, 2)
  72. result[0] = n[1]
  73. result[1] = n[2]
  74. result = semAsgn(c, result, noOverloadedAsgn)
  75. proc semIsPartOf(c: PContext, n: PNode, flags: TExprFlags): PNode =
  76. var r = isPartOf(n[1], n[2])
  77. result = newIntNodeT(toInt128(ord(r)), n, c.idgen, c.graph)
  78. proc expectIntLit(c: PContext, n: PNode): int =
  79. let x = c.semConstExpr(c, n)
  80. case x.kind
  81. of nkIntLit..nkInt64Lit: result = int(x.intVal)
  82. else: localError(c.config, n.info, errIntLiteralExpected)
  83. proc semInstantiationInfo(c: PContext, n: PNode): PNode =
  84. result = newNodeIT(nkTupleConstr, n.info, n.typ)
  85. let idx = expectIntLit(c, n[1])
  86. let useFullPaths = expectIntLit(c, n[2])
  87. let info = getInfoContext(c.config, idx)
  88. var filename = newNodeIT(nkStrLit, n.info, getSysType(c.graph, n.info, tyString))
  89. filename.strVal = if useFullPaths != 0: toFullPath(c.config, info) else: toFilename(c.config, info)
  90. var line = newNodeIT(nkIntLit, n.info, getSysType(c.graph, n.info, tyInt))
  91. line.intVal = toLinenumber(info)
  92. var column = newNodeIT(nkIntLit, n.info, getSysType(c.graph, n.info, tyInt))
  93. column.intVal = toColumn(info)
  94. # filename: string, line: int, column: int
  95. result.add(newTree(nkExprColonExpr, n.typ.n[0], filename))
  96. result.add(newTree(nkExprColonExpr, n.typ.n[1], line))
  97. result.add(newTree(nkExprColonExpr, n.typ.n[2], column))
  98. proc toNode(t: PType, i: TLineInfo): PNode =
  99. result = newNodeIT(nkType, i, t)
  100. const
  101. # these are types that use the bracket syntax for instantiation
  102. # they can be subjected to the type traits `genericHead` and
  103. # `Uninstantiated`
  104. tyUserDefinedGenerics* = {tyGenericInst, tyGenericInvocation,
  105. tyUserTypeClassInst}
  106. tyMagicGenerics* = {tySet, tySequence, tyArray, tyOpenArray}
  107. tyGenericLike* = tyUserDefinedGenerics +
  108. tyMagicGenerics +
  109. {tyCompositeTypeClass}
  110. proc uninstantiate(t: PType): PType =
  111. result = case t.kind
  112. of tyMagicGenerics: t
  113. of tyUserDefinedGenerics: t.base
  114. of tyCompositeTypeClass: uninstantiate t[1]
  115. else: t
  116. proc getTypeDescNode(c: PContext; typ: PType, sym: PSym, info: TLineInfo): PNode =
  117. var resType = newType(tyTypeDesc, nextTypeId c.idgen, sym)
  118. rawAddSon(resType, typ)
  119. result = toNode(resType, info)
  120. proc evalTypeTrait(c: PContext; traitCall: PNode, operand: PType, context: PSym): PNode =
  121. const skippedTypes = {tyTypeDesc, tyAlias, tySink}
  122. let trait = traitCall[0]
  123. internalAssert c.config, trait.kind == nkSym
  124. var operand = operand.skipTypes(skippedTypes)
  125. template operand2: PType =
  126. traitCall[2].typ.skipTypes({tyTypeDesc})
  127. template typeWithSonsResult(kind, sons): PNode =
  128. newTypeWithSons(context, kind, sons, c.idgen).toNode(traitCall.info)
  129. if operand.kind == tyGenericParam or (traitCall.len > 2 and operand2.kind == tyGenericParam):
  130. return traitCall ## too early to evaluate
  131. let s = trait.sym.name.s
  132. case s
  133. of "or", "|":
  134. return typeWithSonsResult(tyOr, @[operand, operand2])
  135. of "and":
  136. return typeWithSonsResult(tyAnd, @[operand, operand2])
  137. of "not":
  138. return typeWithSonsResult(tyNot, @[operand])
  139. of "typeToString":
  140. var prefer = preferTypeName
  141. if traitCall.len >= 2:
  142. let preferStr = traitCall[2].strVal
  143. prefer = parseEnum[TPreferedDesc](preferStr)
  144. result = newStrNode(nkStrLit, operand.typeToString(prefer))
  145. result.typ = getSysType(c.graph, traitCall[1].info, tyString)
  146. result.info = traitCall.info
  147. of "name", "$":
  148. result = newStrNode(nkStrLit, operand.typeToString(preferTypeName))
  149. result.typ = getSysType(c.graph, traitCall[1].info, tyString)
  150. result.info = traitCall.info
  151. of "arity":
  152. result = newIntNode(nkIntLit, operand.len - ord(operand.kind==tyProc))
  153. result.typ = newType(tyInt, nextTypeId c.idgen, context)
  154. result.info = traitCall.info
  155. of "genericHead":
  156. var arg = operand
  157. case arg.kind
  158. of tyGenericInst:
  159. result = getTypeDescNode(c, arg.base, operand.owner, traitCall.info)
  160. # of tySequence: # this doesn't work
  161. # var resType = newType(tySequence, operand.owner)
  162. # result = toNode(resType, traitCall.info) # doesn't work yet
  163. else:
  164. localError(c.config, traitCall.info, "expected generic type, got: type $2 of kind $1" % [arg.kind.toHumanStr, typeToString(operand)])
  165. result = newType(tyError, nextTypeId c.idgen, context).toNode(traitCall.info)
  166. of "stripGenericParams":
  167. result = uninstantiate(operand).toNode(traitCall.info)
  168. of "supportsCopyMem":
  169. let t = operand.skipTypes({tyVar, tyLent, tyGenericInst, tyAlias, tySink, tyInferred})
  170. let complexObj = containsGarbageCollectedRef(t) or
  171. hasDestructor(t)
  172. result = newIntNodeT(toInt128(ord(not complexObj)), traitCall, c.idgen, c.graph)
  173. of "isNamedTuple":
  174. var operand = operand.skipTypes({tyGenericInst})
  175. let cond = operand.kind == tyTuple and operand.n != nil
  176. result = newIntNodeT(toInt128(ord(cond)), traitCall, c.idgen, c.graph)
  177. of "tupleLen":
  178. var operand = operand.skipTypes({tyGenericInst})
  179. assert operand.kind == tyTuple, $operand.kind
  180. result = newIntNodeT(toInt128(operand.len), traitCall, c.idgen, c.graph)
  181. of "distinctBase":
  182. var arg = operand.skipTypes({tyGenericInst})
  183. let rec = semConstExpr(c, traitCall[2]).intVal != 0
  184. while arg.kind == tyDistinct:
  185. arg = arg.base.skipTypes(skippedTypes + {tyGenericInst})
  186. if not rec: break
  187. result = getTypeDescNode(c, arg, operand.owner, traitCall.info)
  188. else:
  189. localError(c.config, traitCall.info, "unknown trait: " & s)
  190. result = newNodeI(nkEmpty, traitCall.info)
  191. proc semTypeTraits(c: PContext, n: PNode): PNode =
  192. checkMinSonsLen(n, 2, c.config)
  193. let t = n[1].typ
  194. internalAssert c.config, t != nil and t.kind == tyTypeDesc
  195. if t.len > 0:
  196. # This is either a type known to sem or a typedesc
  197. # param to a regular proc (again, known at instantiation)
  198. result = evalTypeTrait(c, n, t, getCurrOwner(c))
  199. else:
  200. # a typedesc variable, pass unmodified to evals
  201. result = n
  202. proc semOrd(c: PContext, n: PNode): PNode =
  203. result = n
  204. let parType = n[1].typ
  205. if isOrdinalType(parType, allowEnumWithHoles=true):
  206. discard
  207. else:
  208. localError(c.config, n.info, errOrdinalTypeExpected % typeToString(parType, preferDesc))
  209. result.typ = errorType(c)
  210. proc semBindSym(c: PContext, n: PNode): PNode =
  211. result = copyNode(n)
  212. result.add(n[0])
  213. let sl = semConstExpr(c, n[1])
  214. if sl.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit}:
  215. return localErrorNode(c, n, n[1].info, errStringLiteralExpected)
  216. let isMixin = semConstExpr(c, n[2])
  217. if isMixin.kind != nkIntLit or isMixin.intVal < 0 or
  218. isMixin.intVal > high(TSymChoiceRule).int:
  219. return localErrorNode(c, n, n[2].info, errConstExprExpected)
  220. let id = newIdentNode(getIdent(c.cache, sl.strVal), n.info)
  221. let s = qualifiedLookUp(c, id, {checkUndeclared})
  222. if s != nil:
  223. # we need to mark all symbols:
  224. var sc = symChoice(c, id, s, TSymChoiceRule(isMixin.intVal))
  225. if not (c.inStaticContext > 0 or getCurrOwner(c).isCompileTimeProc):
  226. # inside regular code, bindSym resolves to the sym-choice
  227. # nodes (see tinspectsymbol)
  228. return sc
  229. result.add(sc)
  230. else:
  231. errorUndeclaredIdentifier(c, n[1].info, sl.strVal)
  232. proc opBindSym(c: PContext, scope: PScope, n: PNode, isMixin: int, info: PNode): PNode =
  233. if n.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit, nkIdent}:
  234. return localErrorNode(c, n, info.info, errStringOrIdentNodeExpected)
  235. if isMixin < 0 or isMixin > high(TSymChoiceRule).int:
  236. return localErrorNode(c, n, info.info, errConstExprExpected)
  237. let id = if n.kind == nkIdent: n
  238. else: newIdentNode(getIdent(c.cache, n.strVal), info.info)
  239. let tmpScope = c.currentScope
  240. c.currentScope = scope
  241. let s = qualifiedLookUp(c, id, {checkUndeclared})
  242. if s != nil:
  243. # we need to mark all symbols:
  244. result = symChoice(c, id, s, TSymChoiceRule(isMixin))
  245. else:
  246. errorUndeclaredIdentifier(c, info.info, if n.kind == nkIdent: n.ident.s
  247. else: n.strVal)
  248. c.currentScope = tmpScope
  249. proc semDynamicBindSym(c: PContext, n: PNode): PNode =
  250. # inside regular code, bindSym resolves to the sym-choice
  251. # nodes (see tinspectsymbol)
  252. if not (c.inStaticContext > 0 or getCurrOwner(c).isCompileTimeProc):
  253. return semBindSym(c, n)
  254. if c.graph.vm.isNil:
  255. setupGlobalCtx(c.module, c.graph, c.idgen)
  256. let
  257. vm = PCtx c.graph.vm
  258. # cache the current scope to
  259. # prevent it lost into oblivion
  260. scope = c.currentScope
  261. # cannot use this
  262. # vm.config.features.incl dynamicBindSym
  263. proc bindSymWrapper(a: VmArgs) =
  264. # capture PContext and currentScope
  265. # param description:
  266. # 0. ident, a string literal / computed string / or ident node
  267. # 1. bindSym rule
  268. # 2. info node
  269. a.setResult opBindSym(c, scope, a.getNode(0), a.getInt(1).int, a.getNode(2))
  270. let
  271. # although we use VM callback here, it is not
  272. # executed like 'normal' VM callback
  273. idx = vm.registerCallback("bindSymImpl", bindSymWrapper)
  274. # dummy node to carry idx information to VM
  275. idxNode = newIntTypeNode(idx, c.graph.getSysType(TLineInfo(), tyInt))
  276. result = copyNode(n)
  277. for x in n: result.add x
  278. result.add n # info node
  279. result.add idxNode
  280. proc semShallowCopy(c: PContext, n: PNode, flags: TExprFlags): PNode
  281. proc semOf(c: PContext, n: PNode): PNode =
  282. if n.len == 3:
  283. n[1] = semExprWithType(c, n[1])
  284. n[2] = semExprWithType(c, n[2], {efDetermineType})
  285. #restoreOldStyleType(n[1])
  286. #restoreOldStyleType(n[2])
  287. let a = skipTypes(n[1].typ, abstractPtrs)
  288. let b = skipTypes(n[2].typ, abstractPtrs)
  289. let x = skipTypes(n[1].typ, abstractPtrs-{tyTypeDesc})
  290. let y = skipTypes(n[2].typ, abstractPtrs-{tyTypeDesc})
  291. if x.kind == tyTypeDesc or y.kind != tyTypeDesc:
  292. localError(c.config, n.info, "'of' takes object types")
  293. elif b.kind != tyObject or a.kind != tyObject:
  294. localError(c.config, n.info, "'of' takes object types")
  295. else:
  296. let diff = inheritanceDiff(a, b)
  297. # | returns: 0 iff `a` == `b`
  298. # | returns: -x iff `a` is the x'th direct superclass of `b`
  299. # | returns: +x iff `a` is the x'th direct subclass of `b`
  300. # | returns: `maxint` iff `a` and `b` are not compatible at all
  301. if diff <= 0:
  302. # optimize to true:
  303. message(c.config, n.info, hintConditionAlwaysTrue, renderTree(n))
  304. result = newIntNode(nkIntLit, 1)
  305. result.info = n.info
  306. result.typ = getSysType(c.graph, n.info, tyBool)
  307. return result
  308. elif diff == high(int):
  309. if commonSuperclass(a, b) == nil:
  310. localError(c.config, n.info, "'$1' cannot be of this subtype" % typeToString(a))
  311. else:
  312. message(c.config, n.info, hintConditionAlwaysFalse, renderTree(n))
  313. result = newIntNode(nkIntLit, 0)
  314. result.info = n.info
  315. result.typ = getSysType(c.graph, n.info, tyBool)
  316. else:
  317. localError(c.config, n.info, "'of' takes 2 arguments")
  318. n.typ = getSysType(c.graph, n.info, tyBool)
  319. result = n
  320. proc semUnown(c: PContext; n: PNode): PNode =
  321. proc unownedType(c: PContext; t: PType): PType =
  322. case t.kind
  323. of tyTuple:
  324. var elems = newSeq[PType](t.len)
  325. var someChange = false
  326. for i in 0..<t.len:
  327. elems[i] = unownedType(c, t[i])
  328. if elems[i] != t[i]: someChange = true
  329. if someChange:
  330. result = newType(tyTuple, nextTypeId c.idgen, t.owner)
  331. # we have to use 'rawAddSon' here so that type flags are
  332. # properly computed:
  333. for e in elems: result.rawAddSon(e)
  334. else:
  335. result = t
  336. of tyOwned: result = t[0]
  337. of tySequence, tyOpenArray, tyArray, tyVarargs, tyVar, tyLent,
  338. tyGenericInst, tyAlias:
  339. let b = unownedType(c, t[^1])
  340. if b != t[^1]:
  341. result = copyType(t, nextTypeId c.idgen, t.owner)
  342. copyTypeProps(c.graph, c.idgen.module, result, t)
  343. result[^1] = b
  344. result.flags.excl tfHasOwned
  345. else:
  346. result = t
  347. else:
  348. result = t
  349. result = copyTree(n[1])
  350. result.typ = unownedType(c, result.typ)
  351. # little hack for injectdestructors.nim (see bug #11350):
  352. #result[0].typ = nil
  353. proc turnFinalizerIntoDestructor(c: PContext; orig: PSym; info: TLineInfo): PSym =
  354. # We need to do 2 things: Replace n.typ which is a 'ref T' by a 'var T' type.
  355. # Replace nkDerefExpr by nkHiddenDeref
  356. # nkDeref is for 'ref T': x[].field
  357. # nkHiddenDeref is for 'var T': x<hidden deref [] here>.field
  358. proc transform(c: PContext; n: PNode; old, fresh: PType; oldParam, newParam: PSym): PNode =
  359. result = shallowCopy(n)
  360. if sameTypeOrNil(n.typ, old):
  361. result.typ = fresh
  362. if n.kind == nkSym and n.sym == oldParam:
  363. result.sym = newParam
  364. for i in 0 ..< safeLen(n):
  365. result[i] = transform(c, n[i], old, fresh, oldParam, newParam)
  366. #if n.kind == nkDerefExpr and sameType(n[0].typ, old):
  367. # result =
  368. result = copySym(orig, nextSymId c.idgen)
  369. result.info = info
  370. result.flags.incl sfFromGeneric
  371. result.owner = orig
  372. let origParamType = orig.typ[1]
  373. let newParamType = makeVarType(result, origParamType.skipTypes(abstractPtrs), c.idgen)
  374. let oldParam = orig.typ.n[1].sym
  375. let newParam = newSym(skParam, oldParam.name, nextSymId c.idgen, result, result.info)
  376. newParam.typ = newParamType
  377. # proc body:
  378. result.ast = transform(c, orig.ast, origParamType, newParamType, oldParam, newParam)
  379. # proc signature:
  380. result.typ = newProcType(result.info, nextTypeId c.idgen, result)
  381. result.typ.addParam newParam
  382. proc semQuantifier(c: PContext; n: PNode): PNode =
  383. checkSonsLen(n, 2, c.config)
  384. openScope(c)
  385. result = newNodeIT(n.kind, n.info, n.typ)
  386. result.add n[0]
  387. let args = n[1]
  388. assert args.kind == nkArgList
  389. for i in 0..args.len-2:
  390. let it = args[i]
  391. var valid = false
  392. if it.kind == nkInfix:
  393. let op = considerQuotedIdent(c, it[0])
  394. if op.id == ord(wIn):
  395. let v = newSymS(skForVar, it[1], c)
  396. styleCheckDef(c, v)
  397. onDef(it[1].info, v)
  398. let domain = semExprWithType(c, it[2], {efWantIterator})
  399. v.typ = domain.typ
  400. valid = true
  401. addDecl(c, v)
  402. result.add newTree(nkInfix, it[0], newSymNode(v), domain)
  403. if not valid:
  404. localError(c.config, n.info, "<quantifier> 'in' <range> expected")
  405. result.add forceBool(c, semExprWithType(c, args[^1]))
  406. closeScope(c)
  407. proc semOld(c: PContext; n: PNode): PNode =
  408. if n[1].kind == nkHiddenDeref:
  409. n[1] = n[1][0]
  410. if n[1].kind != nkSym or n[1].sym.kind != skParam:
  411. localError(c.config, n[1].info, "'old' takes a parameter name")
  412. elif n[1].sym.owner != getCurrOwner(c):
  413. localError(c.config, n[1].info, n[1].sym.name.s & " does not belong to " & getCurrOwner(c).name.s)
  414. result = n
  415. proc semNewFinalize(c: PContext; n: PNode): PNode =
  416. # Make sure the finalizer procedure refers to a procedure
  417. if n[^1].kind == nkSym and n[^1].sym.kind notin {skProc, skFunc}:
  418. localError(c.config, n.info, "finalizer must be a direct reference to a proc")
  419. elif optTinyRtti in c.config.globalOptions:
  420. let nfin = skipConvCastAndClosure(n[^1])
  421. let fin = case nfin.kind
  422. of nkSym: nfin.sym
  423. of nkLambda, nkDo: nfin[namePos].sym
  424. else:
  425. localError(c.config, n.info, "finalizer must be a direct reference to a proc")
  426. nil
  427. if fin != nil:
  428. if fin.kind notin {skProc, skFunc}:
  429. # calling convention is checked in codegen
  430. localError(c.config, n.info, "finalizer must be a direct reference to a proc")
  431. # check if we converted this finalizer into a destructor already:
  432. let t = whereToBindTypeHook(c, fin.typ[1].skipTypes(abstractInst+{tyRef}))
  433. if t != nil and getAttachedOp(c.graph, t, attachedDestructor) != nil and
  434. getAttachedOp(c.graph, t, attachedDestructor).owner == fin:
  435. discard "already turned this one into a finalizer"
  436. else:
  437. let wrapperSym = newSym(skProc, getIdent(c.graph.cache, fin.name.s & "FinalizerWrapper"), nextSymId c.idgen, fin.owner, fin.info)
  438. let selfSymNode = newSymNode(copySym(fin.ast[paramsPos][1][0].sym, nextSymId c.idgen))
  439. selfSymNode.typ = fin.typ[1]
  440. wrapperSym.flags.incl sfUsed
  441. let wrapper = c.semExpr(c, newProcNode(nkProcDef, fin.info, body = newTree(nkCall, newSymNode(fin), selfSymNode),
  442. params = nkFormalParams.newTree(c.graph.emptyNode,
  443. newTree(nkIdentDefs, selfSymNode, newNodeIT(nkType,
  444. fin.ast[paramsPos][1][1].info, fin.typ[1]), c.graph.emptyNode)
  445. ),
  446. name = newSymNode(wrapperSym), pattern = fin.ast[patternPos],
  447. genericParams = fin.ast[genericParamsPos], pragmas = fin.ast[pragmasPos], exceptions = fin.ast[miscPos]), {})
  448. var transFormedSym = turnFinalizerIntoDestructor(c, wrapperSym, wrapper.info)
  449. transFormedSym.owner = fin
  450. if c.config.backend == backendCpp or sfCompileToCpp in c.module.flags:
  451. let origParamType = transFormedSym.ast[bodyPos][1].typ
  452. let selfSymbolType = makePtrType(c, origParamType.skipTypes(abstractPtrs))
  453. let selfPtr = newNodeI(nkHiddenAddr, transFormedSym.ast[bodyPos][1].info)
  454. selfPtr.add transFormedSym.ast[bodyPos][1]
  455. selfPtr.typ = selfSymbolType
  456. transFormedSym.ast[bodyPos][1] = c.semExpr(c, selfPtr)
  457. bindTypeHook(c, transFormedSym, n, attachedDestructor)
  458. result = addDefaultFieldForNew(c, n)
  459. proc semPrivateAccess(c: PContext, n: PNode): PNode =
  460. let t = n[1].typ[0].toObjectFromRefPtrGeneric
  461. c.currentScope.allowPrivateAccess.add t.sym
  462. result = newNodeIT(nkEmpty, n.info, getSysType(c.graph, n.info, tyVoid))
  463. proc checkDefault(c: PContext, n: PNode): PNode =
  464. result = n
  465. c.config.internalAssert result[1].typ.kind == tyTypeDesc
  466. let constructed = result[1].typ.base
  467. if constructed.requiresInit:
  468. message(c.config, n.info, warnUnsafeDefault, typeToString(constructed))
  469. proc magicsAfterOverloadResolution(c: PContext, n: PNode,
  470. flags: TExprFlags): PNode =
  471. ## This is the preferred code point to implement magics.
  472. ## ``c`` the current module, a symbol table to a very good approximation
  473. ## ``n`` the ast like it would be passed to a real macro
  474. ## ``flags`` Some flags for more contextual information on how the
  475. ## "macro" is calld.
  476. case n[0].sym.magic
  477. of mAddr:
  478. checkSonsLen(n, 2, c.config)
  479. result = n
  480. result[1] = semAddrArg(c, n[1])
  481. result.typ = makePtrType(c, result[1].typ)
  482. of mTypeOf:
  483. result = semTypeOf(c, n)
  484. of mSizeOf:
  485. result = foldSizeOf(c.config, n, n)
  486. of mAlignOf:
  487. result = foldAlignOf(c.config, n, n)
  488. of mOffsetOf:
  489. result = foldOffsetOf(c.config, n, n)
  490. of mArrGet:
  491. result = semArrGet(c, n, flags)
  492. of mArrPut:
  493. result = semArrPut(c, n, flags)
  494. of mAsgn:
  495. if n[0].sym.name.s == "=":
  496. result = semAsgnOpr(c, n, nkAsgn)
  497. elif n[0].sym.name.s == "=sink":
  498. result = semAsgnOpr(c, n, nkSinkAsgn)
  499. else:
  500. result = semShallowCopy(c, n, flags)
  501. of mIsPartOf: result = semIsPartOf(c, n, flags)
  502. of mTypeTrait: result = semTypeTraits(c, n)
  503. of mAstToStr:
  504. result = newStrNodeT(renderTree(n[1], {renderNoComments}), n, c.graph)
  505. result.typ = getSysType(c.graph, n.info, tyString)
  506. of mInstantiationInfo: result = semInstantiationInfo(c, n)
  507. of mOrd: result = semOrd(c, n)
  508. of mOf: result = semOf(c, n)
  509. of mHigh, mLow: result = semLowHigh(c, n, n[0].sym.magic)
  510. of mShallowCopy: result = semShallowCopy(c, n, flags)
  511. of mNBindSym:
  512. if dynamicBindSym notin c.features:
  513. result = semBindSym(c, n)
  514. else:
  515. result = semDynamicBindSym(c, n)
  516. of mProcCall:
  517. result = n
  518. result.typ = n[1].typ
  519. of mDotDot:
  520. result = n
  521. of mPlugin:
  522. let plugin = getPlugin(c.cache, n[0].sym)
  523. if plugin.isNil:
  524. localError(c.config, n.info, "cannot find plugin " & n[0].sym.name.s)
  525. result = n
  526. else:
  527. result = plugin(c, n)
  528. of mNew:
  529. if n[0].sym.name.s == "unsafeNew": # special case for unsafeNew
  530. result = n
  531. else:
  532. result = addDefaultFieldForNew(c, n)
  533. of mNewFinalize:
  534. result = semNewFinalize(c, n)
  535. of mDestroy:
  536. result = n
  537. let t = n[1].typ.skipTypes(abstractVar)
  538. let op = getAttachedOp(c.graph, t, attachedDestructor)
  539. if op != nil:
  540. result[0] = newSymNode(op)
  541. of mTrace:
  542. result = n
  543. let t = n[1].typ.skipTypes(abstractVar)
  544. let op = getAttachedOp(c.graph, t, attachedTrace)
  545. if op != nil:
  546. result[0] = newSymNode(op)
  547. of mUnown:
  548. result = semUnown(c, n)
  549. of mExists, mForall:
  550. result = semQuantifier(c, n)
  551. of mOld:
  552. result = semOld(c, n)
  553. of mSetLengthSeq:
  554. result = n
  555. let seqType = result[1].typ.skipTypes({tyPtr, tyRef, # in case we had auto-dereferencing
  556. tyVar, tyGenericInst, tyOwned, tySink,
  557. tyAlias, tyUserTypeClassInst})
  558. if seqType.kind == tySequence and seqType.base.requiresInit:
  559. message(c.config, n.info, warnUnsafeSetLen, typeToString(seqType.base))
  560. of mDefault:
  561. result = checkDefault(c, n)
  562. let typ = result[^1].typ.skipTypes({tyTypeDesc})
  563. let defaultExpr = defaultNodeField(c, result[^1], typ)
  564. if defaultExpr != nil:
  565. result = defaultExpr
  566. of mZeroDefault:
  567. result = checkDefault(c, n)
  568. of mIsolate:
  569. if not checkIsolate(n[1]):
  570. localError(c.config, n.info, "expression cannot be isolated: " & $n[1])
  571. result = n
  572. of mPred:
  573. if n[1].typ.skipTypes(abstractInst).kind in {tyUInt..tyUInt64}:
  574. n[0].sym.magic = mSubU
  575. result = n
  576. of mPrivateAccess:
  577. result = semPrivateAccess(c, n)
  578. else:
  579. result = n