semmagic.nim 26 KB

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