semmagic.nim 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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 semAddrArg(c: PContext; n: PNode; isUnsafeAddr = false): PNode =
  12. let x = semExprWithType(c, n)
  13. if x.kind == nkSym:
  14. x.sym.flags.incl(sfAddrTaken)
  15. if isAssignable(c, x, isUnsafeAddr) notin {arLValue, arLocalLValue}:
  16. # Do not suggest the use of unsafeAddr if this expression already is a
  17. # unsafeAddr
  18. if isUnsafeAddr:
  19. localError(c.config, n.info, errExprHasNoAddress)
  20. else:
  21. localError(c.config, n.info, errExprHasNoAddress & "; maybe use 'unsafeAddr'")
  22. result = x
  23. proc semTypeOf(c: PContext; n: PNode): PNode =
  24. var m = BiggestInt 1 # typeOfIter
  25. if n.len == 3:
  26. let mode = semConstExpr(c, n[2])
  27. if mode.kind != nkIntLit:
  28. localError(c.config, n.info, "typeof: cannot evaluate 'mode' parameter at compile-time")
  29. else:
  30. m = mode.intVal
  31. result = newNodeI(nkTypeOfExpr, n.info)
  32. let typExpr = semExprWithType(c, n[1], if m == 1: {efInTypeof} else: {})
  33. result.add typExpr
  34. result.typ = makeTypeDesc(c, typExpr.typ)
  35. type
  36. SemAsgnMode = enum asgnNormal, noOverloadedSubscript, noOverloadedAsgn
  37. proc semAsgn(c: PContext, n: PNode; mode=asgnNormal): PNode
  38. proc semSubscript(c: PContext, n: PNode, flags: TExprFlags): PNode
  39. proc skipAddr(n: PNode): PNode {.inline.} =
  40. (if n.kind == nkHiddenAddr: n.sons[0] else: n)
  41. proc semArrGet(c: PContext; n: PNode; flags: TExprFlags): PNode =
  42. result = newNodeI(nkBracketExpr, n.info)
  43. for i in 1..<n.len: result.add(n[i])
  44. result = semSubscript(c, result, flags)
  45. if result.isNil:
  46. let x = copyTree(n)
  47. x.sons[0] = newIdentNode(getIdent(c.cache, "[]"), n.info)
  48. bracketNotFoundError(c, x)
  49. #localError(c.config, n.info, "could not resolve: " & $n)
  50. result = n
  51. proc semArrPut(c: PContext; n: PNode; flags: TExprFlags): PNode =
  52. # rewrite `[]=`(a, i, x) back to ``a[i] = x``.
  53. let b = newNodeI(nkBracketExpr, n.info)
  54. b.add(n[1].skipAddr)
  55. for i in 2..n.len-2: b.add(n[i])
  56. result = newNodeI(nkAsgn, n.info, 2)
  57. result.sons[0] = b
  58. result.sons[1] = n.lastSon
  59. result = semAsgn(c, result, noOverloadedSubscript)
  60. proc semAsgnOpr(c: PContext; n: PNode): PNode =
  61. result = newNodeI(nkAsgn, n.info, 2)
  62. result.sons[0] = n[1]
  63. result.sons[1] = n[2]
  64. result = semAsgn(c, result, noOverloadedAsgn)
  65. proc semIsPartOf(c: PContext, n: PNode, flags: TExprFlags): PNode =
  66. var r = isPartOf(n[1], n[2])
  67. result = newIntNodeT(ord(r), n, c.graph)
  68. proc expectIntLit(c: PContext, n: PNode): int =
  69. let x = c.semConstExpr(c, n)
  70. case x.kind
  71. of nkIntLit..nkInt64Lit: result = int(x.intVal)
  72. else: localError(c.config, n.info, errIntLiteralExpected)
  73. proc semInstantiationInfo(c: PContext, n: PNode): PNode =
  74. result = newNodeIT(nkTupleConstr, n.info, n.typ)
  75. let idx = expectIntLit(c, n.sons[1])
  76. let useFullPaths = expectIntLit(c, n.sons[2])
  77. let info = getInfoContext(c.config, idx)
  78. var filename = newNodeIT(nkStrLit, n.info, getSysType(c.graph, n.info, tyString))
  79. filename.strVal = if useFullPaths != 0: toFullPath(c.config, info) else: toFilename(c.config, info)
  80. var line = newNodeIT(nkIntLit, n.info, getSysType(c.graph, n.info, tyInt))
  81. line.intVal = toLinenumber(info)
  82. var column = newNodeIT(nkIntLit, n.info, getSysType(c.graph, n.info, tyInt))
  83. column.intVal = toColumn(info)
  84. # filename: string, line: int, column: int
  85. result.add(newTree(nkExprColonExpr, n.typ.n[0], filename))
  86. result.add(newTree(nkExprColonExpr, n.typ.n[1], line))
  87. result.add(newTree(nkExprColonExpr, n.typ.n[2], column))
  88. proc toNode(t: PType, i: TLineInfo): PNode =
  89. result = newNodeIT(nkType, i, t)
  90. const
  91. # these are types that use the bracket syntax for instantiation
  92. # they can be subjected to the type traits `genericHead` and
  93. # `Uninstantiated`
  94. tyUserDefinedGenerics* = {tyGenericInst, tyGenericInvocation,
  95. tyUserTypeClassInst}
  96. tyMagicGenerics* = {tySet, tySequence, tyArray, tyOpenArray}
  97. tyGenericLike* = tyUserDefinedGenerics +
  98. tyMagicGenerics +
  99. {tyCompositeTypeClass}
  100. proc uninstantiate(t: PType): PType =
  101. result = case t.kind
  102. of tyMagicGenerics: t
  103. of tyUserDefinedGenerics: t.base
  104. of tyCompositeTypeClass: uninstantiate t.sons[1]
  105. else: t
  106. proc evalTypeTrait(c: PContext; traitCall: PNode, operand: PType, context: PSym): PNode =
  107. const skippedTypes = {tyTypeDesc, tyAlias, tySink}
  108. let trait = traitCall[0]
  109. internalAssert c.config, trait.kind == nkSym
  110. var operand = operand.skipTypes(skippedTypes)
  111. template operand2: PType =
  112. traitCall.sons[2].typ.skipTypes({tyTypeDesc})
  113. template typeWithSonsResult(kind, sons): PNode =
  114. newTypeWithSons(context, kind, sons).toNode(traitCall.info)
  115. let s = trait.sym.name.s
  116. case s
  117. of "or", "|":
  118. return typeWithSonsResult(tyOr, @[operand, operand2])
  119. of "and":
  120. return typeWithSonsResult(tyAnd, @[operand, operand2])
  121. of "not":
  122. return typeWithSonsResult(tyNot, @[operand])
  123. of "typeToString":
  124. var prefer = preferTypeName
  125. if traitCall.sons.len >= 2:
  126. let preferStr = traitCall.sons[2].strVal
  127. prefer = parseEnum[TPreferedDesc](preferStr)
  128. result = newStrNode(nkStrLit, operand.typeToString(prefer))
  129. result.typ = newType(tyString, context)
  130. result.info = traitCall.info
  131. of "name", "$":
  132. result = newStrNode(nkStrLit, operand.typeToString(preferTypeName))
  133. result.typ = newType(tyString, context)
  134. result.info = traitCall.info
  135. of "arity":
  136. result = newIntNode(nkIntLit, operand.len - ord(operand.kind==tyProc))
  137. result.typ = newType(tyInt, context)
  138. result.info = traitCall.info
  139. of "genericHead":
  140. var res = uninstantiate(operand)
  141. if res == operand and res.kind notin tyMagicGenerics:
  142. localError(c.config, traitCall.info,
  143. "genericHead expects a generic type. The given type was " &
  144. typeToString(operand))
  145. return newType(tyError, context).toNode(traitCall.info)
  146. result = res.base.toNode(traitCall.info)
  147. of "stripGenericParams":
  148. result = uninstantiate(operand).toNode(traitCall.info)
  149. of "supportsCopyMem":
  150. let t = operand.skipTypes({tyVar, tyLent, tyGenericInst, tyAlias, tySink, tyInferred})
  151. let complexObj = containsGarbageCollectedRef(t) or
  152. hasDestructor(t)
  153. result = newIntNodeT(ord(not complexObj), traitCall, c.graph)
  154. else:
  155. localError(c.config, traitCall.info, "unknown trait: " & s)
  156. result = newNodeI(nkEmpty, traitCall.info)
  157. proc semTypeTraits(c: PContext, n: PNode): PNode =
  158. checkMinSonsLen(n, 2, c.config)
  159. let t = n.sons[1].typ
  160. internalAssert c.config, t != nil and t.kind == tyTypeDesc
  161. if t.len > 0:
  162. # This is either a type known to sem or a typedesc
  163. # param to a regular proc (again, known at instantiation)
  164. result = evalTypeTrait(c, n, t, getCurrOwner(c))
  165. else:
  166. # a typedesc variable, pass unmodified to evals
  167. result = n
  168. proc semOrd(c: PContext, n: PNode): PNode =
  169. result = n
  170. let parType = n.sons[1].typ
  171. if isOrdinalType(parType, allowEnumWithHoles=true):
  172. discard
  173. elif parType.kind == tySet:
  174. let a = toInt64(firstOrd(c.config, parType))
  175. let b = toInt64(lastOrd(c.config, parType))
  176. result.typ = makeRangeType(c, a, b, n.info)
  177. else:
  178. localError(c.config, n.info, errOrdinalTypeExpected)
  179. result.typ = errorType(c)
  180. proc semBindSym(c: PContext, n: PNode): PNode =
  181. result = copyNode(n)
  182. result.add(n.sons[0])
  183. let sl = semConstExpr(c, n.sons[1])
  184. if sl.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit}:
  185. localError(c.config, n.sons[1].info, errStringLiteralExpected)
  186. return errorNode(c, n)
  187. let isMixin = semConstExpr(c, n.sons[2])
  188. if isMixin.kind != nkIntLit or isMixin.intVal < 0 or
  189. isMixin.intVal > high(TSymChoiceRule).int:
  190. localError(c.config, n.sons[2].info, errConstExprExpected)
  191. return errorNode(c, n)
  192. let id = newIdentNode(getIdent(c.cache, sl.strVal), n.info)
  193. let s = qualifiedLookUp(c, id, {checkUndeclared})
  194. if s != nil:
  195. # we need to mark all symbols:
  196. var sc = symChoice(c, id, s, TSymChoiceRule(isMixin.intVal))
  197. if not (c.inStaticContext > 0 or getCurrOwner(c).isCompileTimeProc):
  198. # inside regular code, bindSym resolves to the sym-choice
  199. # nodes (see tinspectsymbol)
  200. return sc
  201. result.add(sc)
  202. else:
  203. errorUndeclaredIdentifier(c, n.sons[1].info, sl.strVal)
  204. proc opBindSym(c: PContext, scope: PScope, n: PNode, isMixin: int, info: PNode): PNode =
  205. if n.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit, nkIdent}:
  206. localError(c.config, info.info, errStringOrIdentNodeExpected)
  207. return errorNode(c, n)
  208. if isMixin < 0 or isMixin > high(TSymChoiceRule).int:
  209. localError(c.config, info.info, errConstExprExpected)
  210. return errorNode(c, n)
  211. let id = if n.kind == nkIdent: n
  212. else: newIdentNode(getIdent(c.cache, n.strVal), info.info)
  213. let tmpScope = c.currentScope
  214. c.currentScope = scope
  215. let s = qualifiedLookUp(c, id, {checkUndeclared})
  216. if s != nil:
  217. # we need to mark all symbols:
  218. result = symChoice(c, id, s, TSymChoiceRule(isMixin))
  219. else:
  220. errorUndeclaredIdentifier(c, info.info, if n.kind == nkIdent: n.ident.s
  221. else: n.strVal)
  222. c.currentScope = tmpScope
  223. proc semDynamicBindSym(c: PContext, n: PNode): PNode =
  224. # inside regular code, bindSym resolves to the sym-choice
  225. # nodes (see tinspectsymbol)
  226. if not (c.inStaticContext > 0 or getCurrOwner(c).isCompileTimeProc):
  227. return semBindSym(c, n)
  228. if c.graph.vm.isNil:
  229. setupGlobalCtx(c.module, c.graph)
  230. let
  231. vm = PCtx c.graph.vm
  232. # cache the current scope to
  233. # prevent it lost into oblivion
  234. scope = c.currentScope
  235. # cannot use this
  236. # vm.config.features.incl dynamicBindSym
  237. proc bindSymWrapper(a: VmArgs) =
  238. # capture PContext and currentScope
  239. # param description:
  240. # 0. ident, a string literal / computed string / or ident node
  241. # 1. bindSym rule
  242. # 2. info node
  243. a.setResult opBindSym(c, scope, a.getNode(0), a.getInt(1).int, a.getNode(2))
  244. let
  245. # although we use VM callback here, it is not
  246. # executed like 'normal' VM callback
  247. idx = vm.registerCallback("bindSymImpl", bindSymWrapper)
  248. # dummy node to carry idx information to VM
  249. idxNode = newIntTypeNode(idx, c.graph.getSysType(TLineInfo(), tyInt))
  250. result = copyNode(n)
  251. for x in n: result.add x
  252. result.add n # info node
  253. result.add idxNode
  254. proc semShallowCopy(c: PContext, n: PNode, flags: TExprFlags): PNode
  255. proc semOf(c: PContext, n: PNode): PNode =
  256. if len(n) == 3:
  257. n.sons[1] = semExprWithType(c, n.sons[1])
  258. n.sons[2] = semExprWithType(c, n.sons[2], {efDetermineType})
  259. #restoreOldStyleType(n.sons[1])
  260. #restoreOldStyleType(n.sons[2])
  261. let a = skipTypes(n.sons[1].typ, abstractPtrs)
  262. let b = skipTypes(n.sons[2].typ, abstractPtrs)
  263. let x = skipTypes(n.sons[1].typ, abstractPtrs-{tyTypeDesc})
  264. let y = skipTypes(n.sons[2].typ, abstractPtrs-{tyTypeDesc})
  265. if x.kind == tyTypeDesc or y.kind != tyTypeDesc:
  266. localError(c.config, n.info, "'of' takes object types")
  267. elif b.kind != tyObject or a.kind != tyObject:
  268. localError(c.config, n.info, "'of' takes object types")
  269. else:
  270. let diff = inheritanceDiff(a, b)
  271. # | returns: 0 iff `a` == `b`
  272. # | returns: -x iff `a` is the x'th direct superclass of `b`
  273. # | returns: +x iff `a` is the x'th direct subclass of `b`
  274. # | returns: `maxint` iff `a` and `b` are not compatible at all
  275. if diff <= 0:
  276. # optimize to true:
  277. message(c.config, n.info, hintConditionAlwaysTrue, renderTree(n))
  278. result = newIntNode(nkIntLit, 1)
  279. result.info = n.info
  280. result.typ = getSysType(c.graph, n.info, tyBool)
  281. return result
  282. elif diff == high(int):
  283. if commonSuperclass(a, b) == nil:
  284. localError(c.config, n.info, "'$1' cannot be of this subtype" % typeToString(a))
  285. else:
  286. message(c.config, n.info, hintConditionAlwaysFalse, renderTree(n))
  287. result = newIntNode(nkIntLit, 0)
  288. result.info = n.info
  289. result.typ = getSysType(c.graph, n.info, tyBool)
  290. else:
  291. localError(c.config, n.info, "'of' takes 2 arguments")
  292. n.typ = getSysType(c.graph, n.info, tyBool)
  293. result = n
  294. proc semUnown(c: PContext; n: PNode): PNode =
  295. proc unownedType(c: PContext; t: PType): PType =
  296. case t.kind
  297. of tyTuple:
  298. var elems = newSeq[PType](t.len)
  299. var someChange = false
  300. for i in 0..<t.len:
  301. elems[i] = unownedType(c, t[i])
  302. if elems[i] != t[i]: someChange = true
  303. if someChange:
  304. result = newType(tyTuple, t.owner)
  305. # we have to use 'rawAddSon' here so that type flags are
  306. # properly computed:
  307. for e in elems: result.rawAddSon(e)
  308. else:
  309. result = t
  310. of tyOwned: result = t.sons[0]
  311. of tySequence, tyOpenArray, tyArray, tyVarargs, tyVar, tyLent,
  312. tyGenericInst, tyAlias:
  313. let L = t.len-1
  314. let b = unownedType(c, t[L])
  315. if b != t[L]:
  316. result = copyType(t, t.owner, keepId = false)
  317. result[L] = b
  318. result.flags.excl tfHasOwned
  319. else:
  320. result = t
  321. else:
  322. result = t
  323. result = copyTree(n[1])
  324. result.typ = unownedType(c, result.typ)
  325. # little hack for injectdestructors.nim (see bug #11350):
  326. #result.sons[0].typ = nil
  327. proc magicsAfterOverloadResolution(c: PContext, n: PNode,
  328. flags: TExprFlags): PNode =
  329. ## This is the preferred code point to implement magics.
  330. ## ``c`` the current module, a symbol table to a very good approximation
  331. ## ``n`` the ast like it would be passed to a real macro
  332. ## ``flags`` Some flags for more contextual information on how the
  333. ## "macro" is calld.
  334. case n[0].sym.magic
  335. of mAddr:
  336. checkSonsLen(n, 2, c.config)
  337. result = n
  338. result[1] = semAddrArg(c, n[1], n[0].sym.name.s == "unsafeAddr")
  339. result.typ = makePtrType(c, result[1].typ)
  340. of mTypeOf:
  341. result = semTypeOf(c, n)
  342. of mSizeOf:
  343. result = foldSizeOf(c.config, n, n)
  344. of mAlignOf:
  345. result = foldAlignOf(c.config, n, n)
  346. of mOffsetOf:
  347. result = foldOffsetOf(c.config, n, n)
  348. of mArrGet:
  349. result = semArrGet(c, n, flags)
  350. of mArrPut:
  351. result = semArrPut(c, n, flags)
  352. of mAsgn:
  353. if n[0].sym.name.s == "=":
  354. result = semAsgnOpr(c, n)
  355. else:
  356. result = semShallowCopy(c, n, flags)
  357. of mIsPartOf: result = semIsPartOf(c, n, flags)
  358. of mTypeTrait: result = semTypeTraits(c, n)
  359. of mAstToStr:
  360. result = newStrNodeT(renderTree(n[1], {renderNoComments}), n, c.graph)
  361. result.typ = getSysType(c.graph, n.info, tyString)
  362. of mInstantiationInfo: result = semInstantiationInfo(c, n)
  363. of mOrd: result = semOrd(c, n)
  364. of mOf: result = semOf(c, n)
  365. of mHigh, mLow: result = semLowHigh(c, n, n[0].sym.magic)
  366. of mShallowCopy: result = semShallowCopy(c, n, flags)
  367. of mNBindSym:
  368. if dynamicBindSym notin c.features:
  369. result = semBindSym(c, n)
  370. else:
  371. result = semDynamicBindSym(c, n)
  372. of mProcCall:
  373. result = n
  374. result.typ = n[1].typ
  375. of mDotDot:
  376. result = n
  377. of mRoof:
  378. localError(c.config, n.info, "builtin roof operator is not supported anymore")
  379. of mPlugin:
  380. let plugin = getPlugin(c.cache, n[0].sym)
  381. if plugin.isNil:
  382. localError(c.config, n.info, "cannot find plugin " & n[0].sym.name.s)
  383. result = n
  384. else:
  385. result = plugin(c, n)
  386. of mNewFinalize:
  387. # Make sure the finalizer procedure refers to a procedure
  388. if n[^1].kind == nkSym and n[^1].sym.kind notin {skProc, skFunc}:
  389. localError(c.config, n.info, "finalizer must be a direct reference to a procedure")
  390. result = n
  391. of mDestroy:
  392. result = n
  393. let t = n[1].typ.skipTypes(abstractVar)
  394. if t.destructor != nil:
  395. result.sons[0] = newSymNode(t.destructor)
  396. of mUnown:
  397. result = semUnown(c, n)
  398. else: result = n