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 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 = errorNode(c, 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:
  82. result = 0
  83. localError(c.config, n.info, errIntLiteralExpected)
  84. proc semInstantiationInfo(c: PContext, n: PNode): PNode =
  85. result = newNodeIT(nkTupleConstr, n.info, n.typ)
  86. let idx = expectIntLit(c, n[1])
  87. let useFullPaths = expectIntLit(c, n[2])
  88. let info = getInfoContext(c.config, idx)
  89. var filename = newNodeIT(nkStrLit, n.info, getSysType(c.graph, n.info, tyString))
  90. filename.strVal = if useFullPaths != 0: toFullPath(c.config, info) else: toFilename(c.config, info)
  91. var line = newNodeIT(nkIntLit, n.info, getSysType(c.graph, n.info, tyInt))
  92. line.intVal = toLinenumber(info)
  93. var column = newNodeIT(nkIntLit, n.info, getSysType(c.graph, n.info, tyInt))
  94. column.intVal = toColumn(info)
  95. # filename: string, line: int, column: int
  96. result.add(newTree(nkExprColonExpr, n.typ.n[0], filename))
  97. result.add(newTree(nkExprColonExpr, n.typ.n[1], line))
  98. result.add(newTree(nkExprColonExpr, n.typ.n[2], column))
  99. proc toNode(t: PType, i: TLineInfo): PNode =
  100. result = newNodeIT(nkType, i, t)
  101. const
  102. # these are types that use the bracket syntax for instantiation
  103. # they can be subjected to the type traits `genericHead` and
  104. # `Uninstantiated`
  105. tyUserDefinedGenerics* = {tyGenericInst, tyGenericInvocation,
  106. tyUserTypeClassInst}
  107. tyMagicGenerics* = {tySet, tySequence, tyArray, tyOpenArray}
  108. tyGenericLike* = tyUserDefinedGenerics +
  109. tyMagicGenerics +
  110. {tyCompositeTypeClass}
  111. proc uninstantiate(t: PType): PType =
  112. result = case t.kind
  113. of tyMagicGenerics: t
  114. of tyUserDefinedGenerics: t.base
  115. of tyCompositeTypeClass: uninstantiate t.firstGenericParam
  116. else: t
  117. proc getTypeDescNode(c: PContext; typ: PType, sym: PSym, info: TLineInfo): PNode =
  118. var resType = newType(tyTypeDesc, c.idgen, sym)
  119. rawAddSon(resType, typ)
  120. result = toNode(resType, info)
  121. proc buildBinaryPredicate(kind: TTypeKind; c: PContext; context: PSym; a, b: sink PType): PType =
  122. result = newType(kind, c.idgen, context)
  123. result.rawAddSon a
  124. result.rawAddSon b
  125. proc buildNotPredicate(c: PContext; context: PSym; a: sink PType): PType =
  126. result = newType(tyNot, c.idgen, context, a)
  127. proc evalTypeTrait(c: PContext; traitCall: PNode, operand: PType, context: PSym): PNode =
  128. const skippedTypes = {tyTypeDesc, tyAlias, tySink}
  129. let trait = traitCall[0]
  130. internalAssert c.config, trait.kind == nkSym
  131. var operand = operand.skipTypes(skippedTypes)
  132. template operand2: PType =
  133. traitCall[2].typ.skipTypes({tyTypeDesc})
  134. if operand.kind == tyGenericParam or (traitCall.len > 2 and operand2.kind == tyGenericParam):
  135. return traitCall ## too early to evaluate
  136. let s = trait.sym.name.s
  137. case s
  138. of "or", "|":
  139. return buildBinaryPredicate(tyOr, c, context, operand, operand2).toNode(traitCall.info)
  140. of "and":
  141. return buildBinaryPredicate(tyAnd, c, context, operand, operand2).toNode(traitCall.info)
  142. of "not":
  143. return buildNotPredicate(c, context, operand).toNode(traitCall.info)
  144. of "typeToString":
  145. var prefer = preferTypeName
  146. if traitCall.len >= 2:
  147. let preferStr = traitCall[2].strVal
  148. prefer = parseEnum[TPreferedDesc](preferStr)
  149. result = newStrNode(nkStrLit, operand.typeToString(prefer))
  150. result.typ = getSysType(c.graph, traitCall[1].info, tyString)
  151. result.info = traitCall.info
  152. of "name", "$":
  153. result = newStrNode(nkStrLit, operand.typeToString(preferTypeName))
  154. result.typ = getSysType(c.graph, traitCall[1].info, tyString)
  155. result.info = traitCall.info
  156. of "arity":
  157. result = newIntNode(nkIntLit, operand.len - ord(operand.kind==tyProc))
  158. result.typ = newType(tyInt, c.idgen, context)
  159. result.info = traitCall.info
  160. of "genericHead":
  161. var arg = operand
  162. case arg.kind
  163. of tyGenericInst:
  164. result = getTypeDescNode(c, arg.base, operand.owner, traitCall.info)
  165. # of tySequence: # this doesn't work
  166. # var resType = newType(tySequence, operand.owner)
  167. # result = toNode(resType, traitCall.info) # doesn't work yet
  168. else:
  169. localError(c.config, traitCall.info, "expected generic type, got: type $2 of kind $1" % [arg.kind.toHumanStr, typeToString(operand)])
  170. result = newType(tyError, c.idgen, context).toNode(traitCall.info)
  171. of "stripGenericParams":
  172. result = uninstantiate(operand).toNode(traitCall.info)
  173. of "supportsCopyMem":
  174. let t = operand.skipTypes({tyVar, tyLent, tyGenericInst, tyAlias, tySink, tyInferred})
  175. let complexObj = containsGarbageCollectedRef(t) or
  176. hasDestructor(t)
  177. result = newIntNodeT(toInt128(ord(not complexObj)), traitCall, c.idgen, c.graph)
  178. of "hasDefaultValue":
  179. result = newIntNodeT(toInt128(ord(not operand.requiresInit)), traitCall, c.idgen, c.graph)
  180. of "isNamedTuple":
  181. var operand = operand.skipTypes({tyGenericInst})
  182. let cond = operand.kind == tyTuple and operand.n != nil
  183. result = newIntNodeT(toInt128(ord(cond)), traitCall, c.idgen, c.graph)
  184. of "tupleLen":
  185. var operand = operand.skipTypes({tyGenericInst})
  186. assert operand.kind == tyTuple, $operand.kind
  187. result = newIntNodeT(toInt128(operand.len), traitCall, c.idgen, c.graph)
  188. of "distinctBase":
  189. var arg = operand.skipTypes({tyGenericInst})
  190. let rec = semConstExpr(c, traitCall[2]).intVal != 0
  191. while arg.kind == tyDistinct:
  192. arg = arg.base.skipTypes(skippedTypes + {tyGenericInst})
  193. if not rec: break
  194. result = getTypeDescNode(c, arg, operand.owner, traitCall.info)
  195. of "rangeBase":
  196. # return the base type of a range type
  197. var arg = operand.skipTypes({tyGenericInst})
  198. assert arg.kind == tyRange
  199. result = getTypeDescNode(c, arg.base, operand.owner, traitCall.info)
  200. of "isCyclic":
  201. var operand = operand.skipTypes({tyGenericInst})
  202. let isCyclic = canFormAcycle(c.graph, operand)
  203. result = newIntNodeT(toInt128(ord(isCyclic)), traitCall, c.idgen, c.graph)
  204. else:
  205. localError(c.config, traitCall.info, "unknown trait: " & s)
  206. result = newNodeI(nkEmpty, traitCall.info)
  207. proc semTypeTraits(c: PContext, n: PNode): PNode =
  208. checkMinSonsLen(n, 2, c.config)
  209. let t = n[1].typ
  210. internalAssert c.config, t != nil and t.kind == tyTypeDesc
  211. if t.len > 0:
  212. # This is either a type known to sem or a typedesc
  213. # param to a regular proc (again, known at instantiation)
  214. result = evalTypeTrait(c, n, t, getCurrOwner(c))
  215. else:
  216. # a typedesc variable, pass unmodified to evals
  217. result = n
  218. proc semOrd(c: PContext, n: PNode): PNode =
  219. result = n
  220. let parType = n[1].typ
  221. if isOrdinalType(parType, allowEnumWithHoles=true):
  222. discard
  223. else:
  224. localError(c.config, n.info, errOrdinalTypeExpected % typeToString(parType, preferDesc))
  225. result.typ = errorType(c)
  226. proc semBindSym(c: PContext, n: PNode): PNode =
  227. result = copyNode(n)
  228. result.add(n[0])
  229. let sl = semConstExpr(c, n[1])
  230. if sl.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit}:
  231. return localErrorNode(c, n, n[1].info, errStringLiteralExpected)
  232. let isMixin = semConstExpr(c, n[2])
  233. if isMixin.kind != nkIntLit or isMixin.intVal < 0 or
  234. isMixin.intVal > high(TSymChoiceRule).int:
  235. return localErrorNode(c, n, n[2].info, errConstExprExpected)
  236. let id = newIdentNode(getIdent(c.cache, sl.strVal), n.info)
  237. let s = qualifiedLookUp(c, id, {checkUndeclared})
  238. if s != nil:
  239. # we need to mark all symbols:
  240. var sc = symChoice(c, id, s, TSymChoiceRule(isMixin.intVal))
  241. if not (c.inStaticContext > 0 or getCurrOwner(c).isCompileTimeProc):
  242. # inside regular code, bindSym resolves to the sym-choice
  243. # nodes (see tinspectsymbol)
  244. return sc
  245. result.add(sc)
  246. else:
  247. errorUndeclaredIdentifier(c, n[1].info, sl.strVal)
  248. proc opBindSym(c: PContext, scope: PScope, n: PNode, isMixin: int, info: PNode): PNode =
  249. if n.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit, nkIdent}:
  250. return localErrorNode(c, n, info.info, errStringOrIdentNodeExpected)
  251. if isMixin < 0 or isMixin > high(TSymChoiceRule).int:
  252. return localErrorNode(c, n, info.info, errConstExprExpected)
  253. let id = if n.kind == nkIdent: n
  254. else: newIdentNode(getIdent(c.cache, n.strVal), info.info)
  255. let tmpScope = c.currentScope
  256. c.currentScope = scope
  257. let s = qualifiedLookUp(c, id, {checkUndeclared})
  258. if s != nil:
  259. # we need to mark all symbols:
  260. result = symChoice(c, id, s, TSymChoiceRule(isMixin))
  261. else:
  262. result = nil
  263. errorUndeclaredIdentifier(c, info.info, if n.kind == nkIdent: n.ident.s
  264. else: n.strVal)
  265. c.currentScope = tmpScope
  266. proc semDynamicBindSym(c: PContext, n: PNode): PNode =
  267. # inside regular code, bindSym resolves to the sym-choice
  268. # nodes (see tinspectsymbol)
  269. if not (c.inStaticContext > 0 or getCurrOwner(c).isCompileTimeProc):
  270. return semBindSym(c, n)
  271. if c.graph.vm.isNil:
  272. setupGlobalCtx(c.module, c.graph, c.idgen)
  273. let
  274. vm = PCtx c.graph.vm
  275. # cache the current scope to
  276. # prevent it lost into oblivion
  277. scope = c.currentScope
  278. # cannot use this
  279. # vm.config.features.incl dynamicBindSym
  280. proc bindSymWrapper(a: VmArgs) =
  281. # capture PContext and currentScope
  282. # param description:
  283. # 0. ident, a string literal / computed string / or ident node
  284. # 1. bindSym rule
  285. # 2. info node
  286. a.setResult opBindSym(c, scope, a.getNode(0), a.getInt(1).int, a.getNode(2))
  287. let
  288. # although we use VM callback here, it is not
  289. # executed like 'normal' VM callback
  290. idx = vm.registerCallback("bindSymImpl", bindSymWrapper)
  291. # dummy node to carry idx information to VM
  292. idxNode = newIntTypeNode(idx, c.graph.getSysType(TLineInfo(), tyInt))
  293. result = copyNode(n)
  294. for x in n: result.add x
  295. result.add n # info node
  296. result.add idxNode
  297. proc semShallowCopy(c: PContext, n: PNode, flags: TExprFlags): PNode
  298. proc semOf(c: PContext, n: PNode): PNode =
  299. if n.len == 3:
  300. n[1] = semExprWithType(c, n[1])
  301. n[2] = semExprWithType(c, n[2], {efDetermineType})
  302. #restoreOldStyleType(n[1])
  303. #restoreOldStyleType(n[2])
  304. let a = skipTypes(n[1].typ, abstractPtrs)
  305. let b = skipTypes(n[2].typ, abstractPtrs)
  306. let x = skipTypes(n[1].typ, abstractPtrs-{tyTypeDesc})
  307. let y = skipTypes(n[2].typ, abstractPtrs-{tyTypeDesc})
  308. if x.kind == tyTypeDesc or y.kind != tyTypeDesc:
  309. localError(c.config, n.info, "'of' takes object types")
  310. elif b.kind != tyObject or a.kind != tyObject:
  311. localError(c.config, n.info, "'of' takes object types")
  312. else:
  313. let diff = inheritanceDiff(a, b)
  314. # | returns: 0 iff `a` == `b`
  315. # | returns: -x iff `a` is the x'th direct superclass of `b`
  316. # | returns: +x iff `a` is the x'th direct subclass of `b`
  317. # | returns: `maxint` iff `a` and `b` are not compatible at all
  318. if diff <= 0:
  319. # optimize to true:
  320. message(c.config, n.info, hintConditionAlwaysTrue, renderTree(n))
  321. result = newIntNode(nkIntLit, 1)
  322. result.info = n.info
  323. result.typ = getSysType(c.graph, n.info, tyBool)
  324. return result
  325. elif diff == high(int):
  326. if commonSuperclass(a, b) == nil:
  327. localError(c.config, n.info, "'$1' cannot be of this subtype" % typeToString(a))
  328. else:
  329. message(c.config, n.info, hintConditionAlwaysFalse, renderTree(n))
  330. result = newIntNode(nkIntLit, 0)
  331. result.info = n.info
  332. result.typ = getSysType(c.graph, n.info, tyBool)
  333. else:
  334. localError(c.config, n.info, "'of' takes 2 arguments")
  335. n.typ = getSysType(c.graph, n.info, tyBool)
  336. result = n
  337. proc semUnown(c: PContext; n: PNode): PNode =
  338. proc unownedType(c: PContext; t: PType): PType =
  339. case t.kind
  340. of tyTuple:
  341. var elems = newSeq[PType](t.len)
  342. var someChange = false
  343. for i in 0..<t.len:
  344. elems[i] = unownedType(c, t[i])
  345. if elems[i] != t[i]: someChange = true
  346. if someChange:
  347. result = newType(tyTuple, c.idgen, t.owner)
  348. # we have to use 'rawAddSon' here so that type flags are
  349. # properly computed:
  350. for e in elems: result.rawAddSon(e)
  351. else:
  352. result = t
  353. of tyOwned: result = t.elementType
  354. of tySequence, tyOpenArray, tyArray, tyVarargs, tyVar, tyLent,
  355. tyGenericInst, tyAlias:
  356. let b = unownedType(c, t[^1])
  357. if b != t[^1]:
  358. result = copyType(t, c.idgen, t.owner)
  359. copyTypeProps(c.graph, c.idgen.module, result, t)
  360. result[^1] = b
  361. result.flags.excl tfHasOwned
  362. else:
  363. result = t
  364. else:
  365. result = t
  366. result = copyTree(n[1])
  367. result.typ = unownedType(c, result.typ)
  368. # little hack for injectdestructors.nim (see bug #11350):
  369. #result[0].typ = nil
  370. proc turnFinalizerIntoDestructor(c: PContext; orig: PSym; info: TLineInfo): PSym =
  371. # We need to do 2 things: Replace n.typ which is a 'ref T' by a 'var T' type.
  372. # Replace nkDerefExpr by nkHiddenDeref
  373. # nkDeref is for 'ref T': x[].field
  374. # nkHiddenDeref is for 'var T': x<hidden deref [] here>.field
  375. proc transform(c: PContext; n: PNode; old, fresh: PType; oldParam, newParam: PSym): PNode =
  376. result = shallowCopy(n)
  377. if sameTypeOrNil(n.typ, old):
  378. result.typ = fresh
  379. if n.kind == nkSym and n.sym == oldParam:
  380. result.sym = newParam
  381. for i in 0 ..< safeLen(n):
  382. result[i] = transform(c, n[i], old, fresh, oldParam, newParam)
  383. #if n.kind == nkDerefExpr and sameType(n[0].typ, old):
  384. # result =
  385. result = copySym(orig, c.idgen)
  386. result.info = info
  387. result.flags.incl sfFromGeneric
  388. result.owner = orig
  389. let origParamType = orig.typ.firstParamType
  390. let newParamType = makeVarType(result, origParamType.skipTypes(abstractPtrs), c.idgen)
  391. let oldParam = orig.typ.n[1].sym
  392. let newParam = newSym(skParam, oldParam.name, c.idgen, result, result.info)
  393. newParam.typ = newParamType
  394. # proc body:
  395. result.ast = transform(c, orig.ast, origParamType, newParamType, oldParam, newParam)
  396. # proc signature:
  397. result.typ = newProcType(result.info, c.idgen, result)
  398. result.typ.addParam newParam
  399. proc semQuantifier(c: PContext; n: PNode): PNode =
  400. checkSonsLen(n, 2, c.config)
  401. openScope(c)
  402. result = newNodeIT(n.kind, n.info, n.typ)
  403. result.add n[0]
  404. let args = n[1]
  405. assert args.kind == nkArgList
  406. for i in 0..args.len-2:
  407. let it = args[i]
  408. var valid = false
  409. if it.kind == nkInfix:
  410. let op = considerQuotedIdent(c, it[0])
  411. if op.id == ord(wIn):
  412. let v = newSymS(skForVar, it[1], c)
  413. styleCheckDef(c, v)
  414. onDef(it[1].info, v)
  415. let domain = semExprWithType(c, it[2], {efWantIterator})
  416. v.typ = domain.typ
  417. valid = true
  418. addDecl(c, v)
  419. result.add newTree(nkInfix, it[0], newSymNode(v), domain)
  420. if not valid:
  421. localError(c.config, n.info, "<quantifier> 'in' <range> expected")
  422. result.add forceBool(c, semExprWithType(c, args[^1]))
  423. closeScope(c)
  424. proc semOld(c: PContext; n: PNode): PNode =
  425. if n[1].kind == nkHiddenDeref:
  426. n[1] = n[1][0]
  427. if n[1].kind != nkSym or n[1].sym.kind != skParam:
  428. localError(c.config, n[1].info, "'old' takes a parameter name")
  429. elif n[1].sym.owner != getCurrOwner(c):
  430. localError(c.config, n[1].info, n[1].sym.name.s & " does not belong to " & getCurrOwner(c).name.s)
  431. result = n
  432. proc semNewFinalize(c: PContext; n: PNode): PNode =
  433. # Make sure the finalizer procedure refers to a procedure
  434. if n[^1].kind == nkSym and n[^1].sym.kind notin {skProc, skFunc}:
  435. localError(c.config, n.info, "finalizer must be a direct reference to a proc")
  436. elif optTinyRtti in c.config.globalOptions:
  437. let nfin = skipConvCastAndClosure(n[^1])
  438. let fin = case nfin.kind
  439. of nkSym: nfin.sym
  440. of nkLambda, nkDo: nfin[namePos].sym
  441. else:
  442. localError(c.config, n.info, "finalizer must be a direct reference to a proc")
  443. nil
  444. if fin != nil:
  445. if fin.kind notin {skProc, skFunc}:
  446. # calling convention is checked in codegen
  447. localError(c.config, n.info, "finalizer must be a direct reference to a proc")
  448. # check if we converted this finalizer into a destructor already:
  449. let t = whereToBindTypeHook(c, fin.typ.firstParamType.skipTypes(abstractInst+{tyRef}))
  450. if t != nil and getAttachedOp(c.graph, t, attachedDestructor) != nil and
  451. getAttachedOp(c.graph, t, attachedDestructor).owner == fin:
  452. discard "already turned this one into a finalizer"
  453. else:
  454. if fin.instantiatedFrom != nil and fin.instantiatedFrom != fin.owner: #undo move
  455. fin.owner = fin.instantiatedFrom
  456. let wrapperSym = newSym(skProc, getIdent(c.graph.cache, fin.name.s & "FinalizerWrapper"), c.idgen, fin.owner, fin.info)
  457. let selfSymNode = newSymNode(copySym(fin.ast[paramsPos][1][0].sym, c.idgen))
  458. selfSymNode.typ = fin.typ.firstParamType
  459. wrapperSym.flags.incl sfUsed
  460. let wrapper = c.semExpr(c, newProcNode(nkProcDef, fin.info, body = newTree(nkCall, newSymNode(fin), selfSymNode),
  461. params = nkFormalParams.newTree(c.graph.emptyNode,
  462. newTree(nkIdentDefs, selfSymNode, newNodeIT(nkType,
  463. fin.ast[paramsPos][1][1].info, fin.typ.firstParamType), c.graph.emptyNode)
  464. ),
  465. name = newSymNode(wrapperSym), pattern = fin.ast[patternPos],
  466. genericParams = fin.ast[genericParamsPos], pragmas = fin.ast[pragmasPos], exceptions = fin.ast[miscPos]), {})
  467. var transFormedSym = turnFinalizerIntoDestructor(c, wrapperSym, wrapper.info)
  468. transFormedSym.owner = fin
  469. if c.config.backend == backendCpp or sfCompileToCpp in c.module.flags:
  470. let origParamType = transFormedSym.ast[bodyPos][1].typ
  471. let selfSymbolType = makePtrType(c, origParamType.skipTypes(abstractPtrs))
  472. let selfPtr = newNodeI(nkHiddenAddr, transFormedSym.ast[bodyPos][1].info)
  473. selfPtr.add transFormedSym.ast[bodyPos][1]
  474. selfPtr.typ = selfSymbolType
  475. transFormedSym.ast[bodyPos][1] = c.semExpr(c, selfPtr)
  476. # TODO: suppress var destructor warnings; if newFinalizer is not
  477. # TODO: deprecated, try to implement plain T destructor
  478. bindTypeHook(c, transFormedSym, n, attachedDestructor, suppressVarDestructorWarning = true)
  479. result = addDefaultFieldForNew(c, n)
  480. proc semPrivateAccess(c: PContext, n: PNode): PNode =
  481. let t = n[1].typ.elementType.toObjectFromRefPtrGeneric
  482. if t.kind == tyObject:
  483. assert t.sym != nil
  484. c.currentScope.allowPrivateAccess.add t.sym
  485. result = newNodeIT(nkEmpty, n.info, getSysType(c.graph, n.info, tyVoid))
  486. proc checkDefault(c: PContext, n: PNode): PNode =
  487. result = n
  488. c.config.internalAssert result[1].typ.kind == tyTypeDesc
  489. let constructed = result[1].typ.base
  490. if constructed.requiresInit:
  491. message(c.config, n.info, warnUnsafeDefault, typeToString(constructed))
  492. proc magicsAfterOverloadResolution(c: PContext, n: PNode,
  493. flags: TExprFlags; expectedType: PType = nil): PNode =
  494. ## This is the preferred code point to implement magics.
  495. ## ``c`` the current module, a symbol table to a very good approximation
  496. ## ``n`` the ast like it would be passed to a real macro
  497. ## ``flags`` Some flags for more contextual information on how the
  498. ## "macro" is calld.
  499. case n[0].sym.magic
  500. of mAddr:
  501. checkSonsLen(n, 2, c.config)
  502. result = n
  503. result[1] = semAddrArg(c, n[1])
  504. result.typ = makePtrType(c, result[1].typ)
  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