semmagic.nim 26 KB

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