semmagic.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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(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. let oldBracketExpr = c.p.bracketExpr
  35. result = semSubscript(c, result, flags)
  36. c.p.bracketExpr = oldBracketExpr
  37. if result.isNil:
  38. let x = copyTree(n)
  39. x.sons[0] = newIdentNode(getIdent"[]", n.info)
  40. bracketNotFoundError(c, x)
  41. #localError(n.info, "could not resolve: " & $n)
  42. result = n
  43. proc semArrPut(c: PContext; n: PNode; flags: TExprFlags): PNode =
  44. # rewrite `[]=`(a, i, x) back to ``a[i] = x``.
  45. let b = newNodeI(nkBracketExpr, n.info)
  46. b.add(n[1].skipAddr)
  47. for i in 2..n.len-2: b.add(n[i])
  48. result = newNodeI(nkAsgn, n.info, 2)
  49. result.sons[0] = b
  50. result.sons[1] = n.lastSon
  51. result = semAsgn(c, result, noOverloadedSubscript)
  52. proc semAsgnOpr(c: PContext; n: PNode): PNode =
  53. result = newNodeI(nkAsgn, n.info, 2)
  54. result.sons[0] = n[1]
  55. result.sons[1] = n[2]
  56. result = semAsgn(c, result, noOverloadedAsgn)
  57. proc semIsPartOf(c: PContext, n: PNode, flags: TExprFlags): PNode =
  58. var r = isPartOf(n[1], n[2])
  59. result = newIntNodeT(ord(r), n)
  60. proc expectIntLit(c: PContext, n: PNode): int =
  61. let x = c.semConstExpr(c, n)
  62. case x.kind
  63. of nkIntLit..nkInt64Lit: result = int(x.intVal)
  64. else: localError(n.info, errIntLiteralExpected)
  65. proc semInstantiationInfo(c: PContext, n: PNode): PNode =
  66. result = newNodeIT(nkPar, n.info, n.typ)
  67. let idx = expectIntLit(c, n.sons[1])
  68. let useFullPaths = expectIntLit(c, n.sons[2])
  69. let info = getInfoContext(idx)
  70. var filename = newNodeIT(nkStrLit, n.info, getSysType(tyString))
  71. filename.strVal = if useFullPaths != 0: info.toFullPath else: info.toFilename
  72. var line = newNodeIT(nkIntLit, n.info, getSysType(tyInt))
  73. line.intVal = toLinenumber(info)
  74. result.add(filename)
  75. result.add(line)
  76. proc toNode(t: PType, i: TLineInfo): PNode =
  77. result = newNodeIT(nkType, i, t)
  78. const
  79. # these are types that use the bracket syntax for instantiation
  80. # they can be subjected to the type traits `genericHead` and
  81. # `Uninstantiated`
  82. tyUserDefinedGenerics* = {tyGenericInst, tyGenericInvocation,
  83. tyUserTypeClassInst}
  84. tyMagicGenerics* = {tySet, tySequence, tyArray, tyOpenArray}
  85. tyGenericLike* = tyUserDefinedGenerics +
  86. tyMagicGenerics +
  87. {tyCompositeTypeClass}
  88. proc uninstantiate(t: PType): PType =
  89. result = case t.kind
  90. of tyMagicGenerics: t
  91. of tyUserDefinedGenerics: t.base
  92. of tyCompositeTypeClass: uninstantiate t.sons[1]
  93. else: t
  94. proc evalTypeTrait(traitCall: PNode, operand: PType, context: PSym): PNode =
  95. const skippedTypes = {tyTypeDesc, tyAlias}
  96. let trait = traitCall[0]
  97. internalAssert trait.kind == nkSym
  98. var operand = operand.skipTypes(skippedTypes)
  99. template operand2: PType =
  100. traitCall.sons[2].typ.skipTypes({tyTypeDesc})
  101. template typeWithSonsResult(kind, sons): PNode =
  102. newTypeWithSons(context, kind, sons).toNode(traitCall.info)
  103. case trait.sym.name.s
  104. of "or", "|":
  105. return typeWithSonsResult(tyOr, @[operand, operand2])
  106. of "and":
  107. return typeWithSonsResult(tyAnd, @[operand, operand2])
  108. of "not":
  109. return typeWithSonsResult(tyNot, @[operand])
  110. of "name":
  111. result = newStrNode(nkStrLit, operand.typeToString(preferName))
  112. result.typ = newType(tyString, context)
  113. result.info = traitCall.info
  114. of "arity":
  115. result = newIntNode(nkIntLit, operand.len - ord(operand.kind==tyProc))
  116. result.typ = newType(tyInt, context)
  117. result.info = traitCall.info
  118. of "genericHead":
  119. var res = uninstantiate(operand)
  120. if res == operand and res.kind notin tyMagicGenerics:
  121. localError(traitCall.info,
  122. "genericHead expects a generic type. The given type was " &
  123. typeToString(operand))
  124. return newType(tyError, context).toNode(traitCall.info)
  125. result = res.base.toNode(traitCall.info)
  126. of "stripGenericParams":
  127. result = uninstantiate(operand).toNode(traitCall.info)
  128. else:
  129. internalAssert false
  130. proc semTypeTraits(c: PContext, n: PNode): PNode =
  131. checkMinSonsLen(n, 2)
  132. let t = n.sons[1].typ
  133. internalAssert t != nil and t.kind == tyTypeDesc
  134. if t.sonsLen > 0:
  135. # This is either a type known to sem or a typedesc
  136. # param to a regular proc (again, known at instantiation)
  137. result = evalTypeTrait(n, t, getCurrOwner(c))
  138. else:
  139. # a typedesc variable, pass unmodified to evals
  140. result = n
  141. proc semOrd(c: PContext, n: PNode): PNode =
  142. result = n
  143. let parType = n.sons[1].typ
  144. if isOrdinalType(parType) or parType.kind == tySet:
  145. result.typ = makeRangeType(c, firstOrd(parType), lastOrd(parType), n.info)
  146. else:
  147. localError(n.info, errOrdinalTypeExpected)
  148. result.typ = errorType(c)
  149. proc semBindSym(c: PContext, n: PNode): PNode =
  150. result = copyNode(n)
  151. result.add(n.sons[0])
  152. let sl = semConstExpr(c, n.sons[1])
  153. if sl.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit}:
  154. localError(n.sons[1].info, errStringLiteralExpected)
  155. return errorNode(c, n)
  156. let isMixin = semConstExpr(c, n.sons[2])
  157. if isMixin.kind != nkIntLit or isMixin.intVal < 0 or
  158. isMixin.intVal > high(TSymChoiceRule).int:
  159. localError(n.sons[2].info, errConstExprExpected)
  160. return errorNode(c, n)
  161. let id = newIdentNode(getIdent(sl.strVal), n.info)
  162. let s = qualifiedLookUp(c, id, {checkUndeclared})
  163. if s != nil:
  164. # we need to mark all symbols:
  165. var sc = symChoice(c, id, s, TSymChoiceRule(isMixin.intVal))
  166. result.add(sc)
  167. else:
  168. errorUndeclaredIdentifier(c, n.sons[1].info, sl.strVal)
  169. proc semShallowCopy(c: PContext, n: PNode, flags: TExprFlags): PNode
  170. proc isStrangeArray(t: PType): bool =
  171. let t = t.skipTypes(abstractInst)
  172. result = t.kind == tyArray and t.firstOrd != 0
  173. proc semOf(c: PContext, n: PNode): PNode =
  174. if sonsLen(n) == 3:
  175. n.sons[1] = semExprWithType(c, n.sons[1])
  176. n.sons[2] = semExprWithType(c, n.sons[2], {efDetermineType})
  177. #restoreOldStyleType(n.sons[1])
  178. #restoreOldStyleType(n.sons[2])
  179. let a = skipTypes(n.sons[1].typ, abstractPtrs)
  180. let b = skipTypes(n.sons[2].typ, abstractPtrs)
  181. let x = skipTypes(n.sons[1].typ, abstractPtrs-{tyTypeDesc})
  182. let y = skipTypes(n.sons[2].typ, abstractPtrs-{tyTypeDesc})
  183. if x.kind == tyTypeDesc or y.kind != tyTypeDesc:
  184. localError(n.info, errXExpectsObjectTypes, "of")
  185. elif b.kind != tyObject or a.kind != tyObject:
  186. localError(n.info, errXExpectsObjectTypes, "of")
  187. else:
  188. let diff = inheritanceDiff(a, b)
  189. # | returns: 0 iff `a` == `b`
  190. # | returns: -x iff `a` is the x'th direct superclass of `b`
  191. # | returns: +x iff `a` is the x'th direct subclass of `b`
  192. # | returns: `maxint` iff `a` and `b` are not compatible at all
  193. if diff <= 0:
  194. # optimize to true:
  195. message(n.info, hintConditionAlwaysTrue, renderTree(n))
  196. result = newIntNode(nkIntLit, 1)
  197. result.info = n.info
  198. result.typ = getSysType(tyBool)
  199. return result
  200. elif diff == high(int):
  201. localError(n.info, errXcanNeverBeOfThisSubtype, typeToString(a))
  202. else:
  203. localError(n.info, errXExpectsTwoArguments, "of")
  204. n.typ = getSysType(tyBool)
  205. result = n
  206. proc magicsAfterOverloadResolution(c: PContext, n: PNode,
  207. flags: TExprFlags): PNode =
  208. case n[0].sym.magic
  209. of mAddr:
  210. checkSonsLen(n, 2)
  211. result = semAddr(c, n.sons[1], n[0].sym.name.s == "unsafeAddr")
  212. of mTypeOf:
  213. checkSonsLen(n, 2)
  214. result = semTypeOf(c, n.sons[1])
  215. of mArrGet: result = semArrGet(c, n, flags)
  216. of mArrPut: result = semArrPut(c, n, flags)
  217. of mAsgn: result = semAsgnOpr(c, n)
  218. of mIsPartOf: result = semIsPartOf(c, n, flags)
  219. of mTypeTrait: result = semTypeTraits(c, n)
  220. of mAstToStr:
  221. result = newStrNodeT(renderTree(n[1], {renderNoComments}), n)
  222. result.typ = getSysType(tyString)
  223. of mInstantiationInfo: result = semInstantiationInfo(c, n)
  224. of mOrd: result = semOrd(c, n)
  225. of mOf: result = semOf(c, n)
  226. of mHigh, mLow: result = semLowHigh(c, n, n[0].sym.magic)
  227. of mShallowCopy: result = semShallowCopy(c, n, flags)
  228. of mNBindSym: result = semBindSym(c, n)
  229. of mProcCall:
  230. result = n
  231. result.typ = n[1].typ
  232. of mDotDot:
  233. result = n
  234. of mRoof:
  235. let bracketExpr = if n.len == 3: n.sons[2] else: c.p.bracketExpr
  236. if bracketExpr.isNil:
  237. localError(n.info, "no surrounding array access context for '^'")
  238. result = n.sons[1]
  239. elif bracketExpr.checkForSideEffects != seNoSideEffect:
  240. localError(n.info, "invalid context for '^' as '$#' has side effects" %
  241. renderTree(bracketExpr))
  242. result = n.sons[1]
  243. elif bracketExpr.typ.isStrangeArray:
  244. localError(n.info, "invalid context for '^' as len!=high+1 for '$#'" %
  245. renderTree(bracketExpr))
  246. result = n.sons[1]
  247. else:
  248. # ^x is rewritten to: len(a)-x
  249. let lenExpr = newNodeI(nkCall, n.info)
  250. lenExpr.add newIdentNode(getIdent"len", n.info)
  251. lenExpr.add bracketExpr
  252. let lenExprB = semExprWithType(c, lenExpr)
  253. if lenExprB.typ.isNil or not isOrdinalType(lenExprB.typ):
  254. localError(n.info, "'$#' has to be of an ordinal type for '^'" %
  255. renderTree(lenExpr))
  256. result = n.sons[1]
  257. else:
  258. result = newNodeIT(nkCall, n.info, getSysType(tyInt))
  259. let subi = getSysMagic("-", mSubI)
  260. #echo "got ", typeToString(subi.typ)
  261. result.add newSymNode(subi, n.info)
  262. result.add lenExprB
  263. result.add n.sons[1]
  264. of mPlugin:
  265. let plugin = getPlugin(n[0].sym)
  266. if plugin.isNil:
  267. localError(n.info, "cannot find plugin " & n[0].sym.name.s)
  268. result = n
  269. else:
  270. result = plugin(c, n)
  271. else: result = n