semmagic.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. of "supportsCopyMem":
  129. let t = operand.skipTypes({tyVar, tyGenericInst, tyAlias, tyInferred})
  130. let complexObj = containsGarbageCollectedRef(t) or
  131. hasDestructor(t)
  132. result = newIntNodeT(ord(not complexObj), traitCall)
  133. else:
  134. localError(traitCall.info, "unknown trait")
  135. result = emptyNode
  136. proc semTypeTraits(c: PContext, n: PNode): PNode =
  137. checkMinSonsLen(n, 2)
  138. let t = n.sons[1].typ
  139. internalAssert t != nil and t.kind == tyTypeDesc
  140. if t.sonsLen > 0:
  141. # This is either a type known to sem or a typedesc
  142. # param to a regular proc (again, known at instantiation)
  143. result = evalTypeTrait(n, t, getCurrOwner(c))
  144. else:
  145. # a typedesc variable, pass unmodified to evals
  146. result = n
  147. proc semOrd(c: PContext, n: PNode): PNode =
  148. result = n
  149. let parType = n.sons[1].typ
  150. if isOrdinalType(parType) or parType.kind == tySet:
  151. result.typ = makeRangeType(c, firstOrd(parType), lastOrd(parType), n.info)
  152. else:
  153. localError(n.info, errOrdinalTypeExpected)
  154. result.typ = errorType(c)
  155. proc semBindSym(c: PContext, n: PNode): PNode =
  156. result = copyNode(n)
  157. result.add(n.sons[0])
  158. let sl = semConstExpr(c, n.sons[1])
  159. if sl.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit}:
  160. localError(n.sons[1].info, errStringLiteralExpected)
  161. return errorNode(c, n)
  162. let isMixin = semConstExpr(c, n.sons[2])
  163. if isMixin.kind != nkIntLit or isMixin.intVal < 0 or
  164. isMixin.intVal > high(TSymChoiceRule).int:
  165. localError(n.sons[2].info, errConstExprExpected)
  166. return errorNode(c, n)
  167. let id = newIdentNode(getIdent(sl.strVal), n.info)
  168. let s = qualifiedLookUp(c, id, {checkUndeclared})
  169. if s != nil:
  170. # we need to mark all symbols:
  171. var sc = symChoice(c, id, s, TSymChoiceRule(isMixin.intVal))
  172. result.add(sc)
  173. else:
  174. errorUndeclaredIdentifier(c, n.sons[1].info, sl.strVal)
  175. proc semShallowCopy(c: PContext, n: PNode, flags: TExprFlags): PNode
  176. proc isStrangeArray(t: PType): bool =
  177. let t = t.skipTypes(abstractInst)
  178. result = t.kind == tyArray and t.firstOrd != 0
  179. proc semOf(c: PContext, n: PNode): PNode =
  180. if sonsLen(n) == 3:
  181. n.sons[1] = semExprWithType(c, n.sons[1])
  182. n.sons[2] = semExprWithType(c, n.sons[2], {efDetermineType})
  183. #restoreOldStyleType(n.sons[1])
  184. #restoreOldStyleType(n.sons[2])
  185. let a = skipTypes(n.sons[1].typ, abstractPtrs)
  186. let b = skipTypes(n.sons[2].typ, abstractPtrs)
  187. let x = skipTypes(n.sons[1].typ, abstractPtrs-{tyTypeDesc})
  188. let y = skipTypes(n.sons[2].typ, abstractPtrs-{tyTypeDesc})
  189. if x.kind == tyTypeDesc or y.kind != tyTypeDesc:
  190. localError(n.info, errXExpectsObjectTypes, "of")
  191. elif b.kind != tyObject or a.kind != tyObject:
  192. localError(n.info, errXExpectsObjectTypes, "of")
  193. else:
  194. let diff = inheritanceDiff(a, b)
  195. # | returns: 0 iff `a` == `b`
  196. # | returns: -x iff `a` is the x'th direct superclass of `b`
  197. # | returns: +x iff `a` is the x'th direct subclass of `b`
  198. # | returns: `maxint` iff `a` and `b` are not compatible at all
  199. if diff <= 0:
  200. # optimize to true:
  201. message(n.info, hintConditionAlwaysTrue, renderTree(n))
  202. result = newIntNode(nkIntLit, 1)
  203. result.info = n.info
  204. result.typ = getSysType(tyBool)
  205. return result
  206. elif diff == high(int):
  207. localError(n.info, errXcanNeverBeOfThisSubtype, typeToString(a))
  208. else:
  209. localError(n.info, errXExpectsTwoArguments, "of")
  210. n.typ = getSysType(tyBool)
  211. result = n
  212. proc magicsAfterOverloadResolution(c: PContext, n: PNode,
  213. flags: TExprFlags): PNode =
  214. case n[0].sym.magic
  215. of mAddr:
  216. checkSonsLen(n, 2)
  217. result = semAddr(c, n.sons[1], n[0].sym.name.s == "unsafeAddr")
  218. of mTypeOf:
  219. checkSonsLen(n, 2)
  220. result = semTypeOf(c, n.sons[1])
  221. of mArrGet: result = semArrGet(c, n, flags)
  222. of mArrPut: result = semArrPut(c, n, flags)
  223. of mAsgn:
  224. if n[0].sym.name.s == "=":
  225. result = semAsgnOpr(c, n)
  226. else:
  227. result = n
  228. of mIsPartOf: result = semIsPartOf(c, n, flags)
  229. of mTypeTrait: result = semTypeTraits(c, n)
  230. of mAstToStr:
  231. result = newStrNodeT(renderTree(n[1], {renderNoComments}), n)
  232. result.typ = getSysType(tyString)
  233. of mInstantiationInfo: result = semInstantiationInfo(c, n)
  234. of mOrd: result = semOrd(c, n)
  235. of mOf: result = semOf(c, n)
  236. of mHigh, mLow: result = semLowHigh(c, n, n[0].sym.magic)
  237. of mShallowCopy: result = semShallowCopy(c, n, flags)
  238. of mNBindSym: result = semBindSym(c, n)
  239. of mProcCall:
  240. result = n
  241. result.typ = n[1].typ
  242. of mDotDot:
  243. result = n
  244. of mRoof:
  245. let bracketExpr = if n.len == 3: n.sons[2] else: c.p.bracketExpr
  246. if bracketExpr.isNil:
  247. localError(n.info, "no surrounding array access context for '^'")
  248. result = n.sons[1]
  249. elif bracketExpr.checkForSideEffects != seNoSideEffect:
  250. localError(n.info, "invalid context for '^' as '$#' has side effects" %
  251. renderTree(bracketExpr))
  252. result = n.sons[1]
  253. elif bracketExpr.typ.isStrangeArray:
  254. localError(n.info, "invalid context for '^' as len!=high+1 for '$#'" %
  255. renderTree(bracketExpr))
  256. result = n.sons[1]
  257. else:
  258. # ^x is rewritten to: len(a)-x
  259. let lenExpr = newNodeI(nkCall, n.info)
  260. lenExpr.add newIdentNode(getIdent"len", n.info)
  261. lenExpr.add bracketExpr
  262. let lenExprB = semExprWithType(c, lenExpr)
  263. if lenExprB.typ.isNil or not isOrdinalType(lenExprB.typ):
  264. localError(n.info, "'$#' has to be of an ordinal type for '^'" %
  265. renderTree(lenExpr))
  266. result = n.sons[1]
  267. else:
  268. result = newNodeIT(nkCall, n.info, getSysType(tyInt))
  269. let subi = getSysMagic("-", mSubI)
  270. #echo "got ", typeToString(subi.typ)
  271. result.add newSymNode(subi, n.info)
  272. result.add lenExprB
  273. result.add n.sons[1]
  274. of mPlugin:
  275. let plugin = getPlugin(n[0].sym)
  276. if plugin.isNil:
  277. localError(n.info, "cannot find plugin " & n[0].sym.name.s)
  278. result = n
  279. else:
  280. result = plugin(c, n)
  281. else: result = n