semmagic.nim 28 KB

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