semmagic.nim 27 KB

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