semmagic.nim 14 KB

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