semmagic.nim 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 semAddr(c: PContext; n: PNode; isUnsafeAddr=false): PNode =
  12. result = newNodeI(nkAddr, n.info)
  13. let x = semExprWithType(c, n)
  14. if x.kind == nkSym:
  15. x.sym.flags.incl(sfAddrTaken)
  16. if isAssignable(c, x, isUnsafeAddr) notin {arLValue, arLocalLValue}:
  17. localError(c.config, n.info, errExprHasNoAddress)
  18. result.add x
  19. result.typ = makePtrType(c, x.typ)
  20. proc semTypeOf(c: PContext; n: PNode): PNode =
  21. result = newNodeI(nkTypeOfExpr, n.info)
  22. let typExpr = semExprWithType(c, n, {efInTypeof})
  23. result.add typExpr
  24. result.typ = makeTypeDesc(c, typExpr.typ)
  25. type
  26. SemAsgnMode = enum asgnNormal, noOverloadedSubscript, noOverloadedAsgn
  27. proc semAsgn(c: PContext, n: PNode; mode=asgnNormal): PNode
  28. proc semSubscript(c: PContext, n: PNode, flags: TExprFlags): PNode
  29. proc skipAddr(n: PNode): PNode {.inline.} =
  30. (if n.kind == nkHiddenAddr: n.sons[0] else: n)
  31. proc semArrGet(c: PContext; n: PNode; flags: TExprFlags): PNode =
  32. result = newNodeI(nkBracketExpr, n.info)
  33. for i in 1..<n.len: result.add(n[i])
  34. result = semSubscript(c, result, flags)
  35. if result.isNil:
  36. let x = copyTree(n)
  37. x.sons[0] = newIdentNode(getIdent(c.cache, "[]"), n.info)
  38. bracketNotFoundError(c, x)
  39. #localError(c.config, n.info, "could not resolve: " & $n)
  40. result = n
  41. proc semArrPut(c: PContext; n: PNode; flags: TExprFlags): PNode =
  42. # rewrite `[]=`(a, i, x) back to ``a[i] = x``.
  43. let b = newNodeI(nkBracketExpr, n.info)
  44. b.add(n[1].skipAddr)
  45. for i in 2..n.len-2: b.add(n[i])
  46. result = newNodeI(nkAsgn, n.info, 2)
  47. result.sons[0] = b
  48. result.sons[1] = n.lastSon
  49. result = semAsgn(c, result, noOverloadedSubscript)
  50. proc semAsgnOpr(c: PContext; n: PNode): PNode =
  51. result = newNodeI(nkAsgn, n.info, 2)
  52. result.sons[0] = n[1]
  53. result.sons[1] = n[2]
  54. result = semAsgn(c, result, noOverloadedAsgn)
  55. proc semIsPartOf(c: PContext, n: PNode, flags: TExprFlags): PNode =
  56. var r = isPartOf(n[1], n[2])
  57. result = newIntNodeT(ord(r), n, c.graph)
  58. proc expectIntLit(c: PContext, n: PNode): int =
  59. let x = c.semConstExpr(c, n)
  60. case x.kind
  61. of nkIntLit..nkInt64Lit: result = int(x.intVal)
  62. else: localError(c.config, n.info, errIntLiteralExpected)
  63. proc semInstantiationInfo(c: PContext, n: PNode): PNode =
  64. result = newNodeIT(nkTupleConstr, n.info, n.typ)
  65. let idx = expectIntLit(c, n.sons[1])
  66. let useFullPaths = expectIntLit(c, n.sons[2])
  67. let info = getInfoContext(c.config, idx)
  68. var filename = newNodeIT(nkStrLit, n.info, getSysType(c.graph, n.info, tyString))
  69. filename.strVal = if useFullPaths != 0: toFullPath(c.config, info) else: toFilename(c.config, info)
  70. var line = newNodeIT(nkIntLit, n.info, getSysType(c.graph, n.info, tyInt))
  71. line.intVal = toLinenumber(info)
  72. var column = newNodeIT(nkIntLit, n.info, getSysType(c.graph, n.info, tyInt))
  73. column.intVal = toColumn(info)
  74. result.add(filename)
  75. result.add(line)
  76. result.add(column)
  77. proc toNode(t: PType, i: TLineInfo): PNode =
  78. result = newNodeIT(nkType, i, t)
  79. const
  80. # these are types that use the bracket syntax for instantiation
  81. # they can be subjected to the type traits `genericHead` and
  82. # `Uninstantiated`
  83. tyUserDefinedGenerics* = {tyGenericInst, tyGenericInvocation,
  84. tyUserTypeClassInst}
  85. tyMagicGenerics* = {tySet, tySequence, tyArray, tyOpenArray}
  86. tyGenericLike* = tyUserDefinedGenerics +
  87. tyMagicGenerics +
  88. {tyCompositeTypeClass}
  89. proc uninstantiate(t: PType): PType =
  90. result = case t.kind
  91. of tyMagicGenerics: t
  92. of tyUserDefinedGenerics: t.base
  93. of tyCompositeTypeClass: uninstantiate t.sons[1]
  94. else: t
  95. proc evalTypeTrait(c: PContext; traitCall: PNode, operand: PType, context: PSym): PNode =
  96. const skippedTypes = {tyTypeDesc, tyAlias, tySink}
  97. let trait = traitCall[0]
  98. internalAssert c.config, trait.kind == nkSym
  99. var operand = operand.skipTypes(skippedTypes)
  100. template operand2: PType =
  101. traitCall.sons[2].typ.skipTypes({tyTypeDesc})
  102. template typeWithSonsResult(kind, sons): PNode =
  103. newTypeWithSons(context, kind, sons).toNode(traitCall.info)
  104. case trait.sym.name.s
  105. of "or", "|":
  106. return typeWithSonsResult(tyOr, @[operand, operand2])
  107. of "and":
  108. return typeWithSonsResult(tyAnd, @[operand, operand2])
  109. of "not":
  110. return typeWithSonsResult(tyNot, @[operand])
  111. of "name":
  112. result = newStrNode(nkStrLit, operand.typeToString(preferTypeName))
  113. result.typ = newType(tyString, context)
  114. result.info = traitCall.info
  115. of "arity":
  116. result = newIntNode(nkIntLit, operand.len - ord(operand.kind==tyProc))
  117. result.typ = newType(tyInt, context)
  118. result.info = traitCall.info
  119. of "genericHead":
  120. var res = uninstantiate(operand)
  121. if res == operand and res.kind notin tyMagicGenerics:
  122. localError(c.config, traitCall.info,
  123. "genericHead expects a generic type. The given type was " &
  124. typeToString(operand))
  125. return newType(tyError, context).toNode(traitCall.info)
  126. result = res.base.toNode(traitCall.info)
  127. of "stripGenericParams":
  128. result = uninstantiate(operand).toNode(traitCall.info)
  129. of "supportsCopyMem":
  130. let t = operand.skipTypes({tyVar, tyLent, tyGenericInst, tyAlias, tySink, tyInferred})
  131. let complexObj = containsGarbageCollectedRef(t) or
  132. hasDestructor(t)
  133. result = newIntNodeT(ord(not complexObj), traitCall, c.graph)
  134. else:
  135. localError(c.config, traitCall.info, "unknown trait")
  136. result = newNodeI(nkEmpty, traitCall.info)
  137. proc semTypeTraits(c: PContext, n: PNode): PNode =
  138. checkMinSonsLen(n, 2, c.config)
  139. let t = n.sons[1].typ
  140. internalAssert c.config, t != nil and t.kind == tyTypeDesc
  141. if t.sonsLen > 0:
  142. # This is either a type known to sem or a typedesc
  143. # param to a regular proc (again, known at instantiation)
  144. result = evalTypeTrait(c, n, t, getCurrOwner(c))
  145. else:
  146. # a typedesc variable, pass unmodified to evals
  147. result = n
  148. proc semOrd(c: PContext, n: PNode): PNode =
  149. result = n
  150. let parType = n.sons[1].typ
  151. if isOrdinalType(parType, allowEnumWithHoles=true):
  152. discard
  153. elif parType.kind == tySet:
  154. result.typ = makeRangeType(c, firstOrd(c.config, parType), lastOrd(c.config, parType), n.info)
  155. else:
  156. localError(c.config, n.info, errOrdinalTypeExpected)
  157. result.typ = errorType(c)
  158. proc semBindSym(c: PContext, n: PNode): PNode =
  159. result = copyNode(n)
  160. result.add(n.sons[0])
  161. let sl = semConstExpr(c, n.sons[1])
  162. if sl.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit}:
  163. localError(c.config, n.sons[1].info, errStringLiteralExpected)
  164. return errorNode(c, n)
  165. let isMixin = semConstExpr(c, n.sons[2])
  166. if isMixin.kind != nkIntLit or isMixin.intVal < 0 or
  167. isMixin.intVal > high(TSymChoiceRule).int:
  168. localError(c.config, n.sons[2].info, errConstExprExpected)
  169. return errorNode(c, n)
  170. let id = newIdentNode(getIdent(c.cache, sl.strVal), n.info)
  171. let s = qualifiedLookUp(c, id, {checkUndeclared})
  172. if s != nil:
  173. # we need to mark all symbols:
  174. var sc = symChoice(c, id, s, TSymChoiceRule(isMixin.intVal))
  175. if not (c.inStaticContext > 0 or getCurrOwner(c).isCompileTimeProc):
  176. # inside regular code, bindSym resolves to the sym-choice
  177. # nodes (see tinspectsymbol)
  178. return sc
  179. result.add(sc)
  180. else:
  181. errorUndeclaredIdentifier(c, n.sons[1].info, sl.strVal)
  182. proc opBindSym(c: PContext, scope: PScope, n: PNode, isMixin: int, info: PNode): PNode =
  183. if n.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit, nkIdent}:
  184. localError(c.config, info.info, errStringOrIdentNodeExpected)
  185. return errorNode(c, n)
  186. if isMixin < 0 or isMixin > high(TSymChoiceRule).int:
  187. localError(c.config, info.info, errConstExprExpected)
  188. return errorNode(c, n)
  189. let id = if n.kind == nkIdent: n
  190. else: newIdentNode(getIdent(c.cache, n.strVal), info.info)
  191. let tmpScope = c.currentScope
  192. c.currentScope = scope
  193. let s = qualifiedLookUp(c, id, {checkUndeclared})
  194. if s != nil:
  195. # we need to mark all symbols:
  196. result = symChoice(c, id, s, TSymChoiceRule(isMixin))
  197. else:
  198. errorUndeclaredIdentifier(c, info.info, if n.kind == nkIdent: n.ident.s
  199. else: n.strVal)
  200. c.currentScope = tmpScope
  201. proc semDynamicBindSym(c: PContext, n: PNode): PNode =
  202. # inside regular code, bindSym resolves to the sym-choice
  203. # nodes (see tinspectsymbol)
  204. if not (c.inStaticContext > 0 or getCurrOwner(c).isCompileTimeProc):
  205. return semBindSym(c, n)
  206. if c.graph.vm.isNil:
  207. setupGlobalCtx(c.module, c.graph)
  208. let
  209. vm = PCtx c.graph.vm
  210. # cache the current scope to
  211. # prevent it lost into oblivion
  212. scope = c.currentScope
  213. # cannot use this
  214. # vm.config.features.incl dynamicBindSym
  215. proc bindSymWrapper(a: VmArgs) =
  216. # capture PContext and currentScope
  217. # param description:
  218. # 0. ident, a string literal / computed string / or ident node
  219. # 1. bindSym rule
  220. # 2. info node
  221. a.setResult opBindSym(c, scope, a.getNode(0), a.getInt(1).int, a.getNode(2))
  222. let
  223. # altough we use VM callback here, it is not
  224. # executed like 'normal' VM callback
  225. idx = vm.registerCallback("bindSymImpl", bindSymWrapper)
  226. # dummy node to carry idx information to VM
  227. idxNode = newIntTypeNode(nkIntLit, idx, c.graph.getSysType(TLineInfo(), tyInt))
  228. result = copyNode(n)
  229. for x in n: result.add x
  230. result.add n # info node
  231. result.add idxNode
  232. proc semShallowCopy(c: PContext, n: PNode, flags: TExprFlags): PNode
  233. proc semOf(c: PContext, n: PNode): PNode =
  234. if sonsLen(n) == 3:
  235. n.sons[1] = semExprWithType(c, n.sons[1])
  236. n.sons[2] = semExprWithType(c, n.sons[2], {efDetermineType})
  237. #restoreOldStyleType(n.sons[1])
  238. #restoreOldStyleType(n.sons[2])
  239. let a = skipTypes(n.sons[1].typ, abstractPtrs)
  240. let b = skipTypes(n.sons[2].typ, abstractPtrs)
  241. let x = skipTypes(n.sons[1].typ, abstractPtrs-{tyTypeDesc})
  242. let y = skipTypes(n.sons[2].typ, abstractPtrs-{tyTypeDesc})
  243. if x.kind == tyTypeDesc or y.kind != tyTypeDesc:
  244. localError(c.config, n.info, "'of' takes object types")
  245. elif b.kind != tyObject or a.kind != tyObject:
  246. localError(c.config, n.info, "'of' takes object types")
  247. else:
  248. let diff = inheritanceDiff(a, b)
  249. # | returns: 0 iff `a` == `b`
  250. # | returns: -x iff `a` is the x'th direct superclass of `b`
  251. # | returns: +x iff `a` is the x'th direct subclass of `b`
  252. # | returns: `maxint` iff `a` and `b` are not compatible at all
  253. if diff <= 0:
  254. # optimize to true:
  255. message(c.config, n.info, hintConditionAlwaysTrue, renderTree(n))
  256. result = newIntNode(nkIntLit, 1)
  257. result.info = n.info
  258. result.typ = getSysType(c.graph, n.info, tyBool)
  259. return result
  260. elif diff == high(int):
  261. localError(c.config, n.info, "'$1' cannot be of this subtype" % typeToString(a))
  262. else:
  263. localError(c.config, n.info, "'of' takes 2 arguments")
  264. n.typ = getSysType(c.graph, n.info, tyBool)
  265. result = n
  266. proc magicsAfterOverloadResolution(c: PContext, n: PNode,
  267. flags: TExprFlags): PNode =
  268. case n[0].sym.magic
  269. of mAddr:
  270. checkSonsLen(n, 2, c.config)
  271. result = semAddr(c, n.sons[1], n[0].sym.name.s == "unsafeAddr")
  272. of mTypeOf:
  273. checkSonsLen(n, 2, c.config)
  274. result = semTypeOf(c, n.sons[1])
  275. of mArrGet: result = semArrGet(c, n, flags)
  276. of mArrPut: result = semArrPut(c, n, flags)
  277. of mAsgn:
  278. if n[0].sym.name.s == "=":
  279. result = semAsgnOpr(c, n)
  280. else:
  281. result = n
  282. of mIsPartOf: result = semIsPartOf(c, n, flags)
  283. of mTypeTrait: result = semTypeTraits(c, n)
  284. of mAstToStr:
  285. result = newStrNodeT(renderTree(n[1], {renderNoComments}), n, c.graph)
  286. result.typ = getSysType(c.graph, n.info, tyString)
  287. of mInstantiationInfo: result = semInstantiationInfo(c, n)
  288. of mOrd: result = semOrd(c, n)
  289. of mOf: result = semOf(c, n)
  290. of mHigh, mLow: result = semLowHigh(c, n, n[0].sym.magic)
  291. of mShallowCopy: result = semShallowCopy(c, n, flags)
  292. of mNBindSym:
  293. if dynamicBindSym notin c.features:
  294. result = semBindSym(c, n)
  295. else:
  296. result = semDynamicBindSym(c, n)
  297. of mProcCall:
  298. result = n
  299. result.typ = n[1].typ
  300. of mDotDot:
  301. result = n
  302. of mRoof:
  303. localError(c.config, n.info, "builtin roof operator is not supported anymore")
  304. of mPlugin:
  305. let plugin = getPlugin(c.cache, n[0].sym)
  306. if plugin.isNil:
  307. localError(c.config, n.info, "cannot find plugin " & n[0].sym.name.s)
  308. result = n
  309. else:
  310. result = plugin(c, n)
  311. else: result = n