semmagic.nim 24 KB

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