semmagic.nim 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. let s = trait.sym.name.s
  112. case s
  113. of "or", "|":
  114. return typeWithSonsResult(tyOr, @[operand, operand2])
  115. of "and":
  116. return typeWithSonsResult(tyAnd, @[operand, operand2])
  117. of "not":
  118. return typeWithSonsResult(tyNot, @[operand])
  119. of "name", "$":
  120. result = newStrNode(nkStrLit, operand.typeToString(preferTypeName))
  121. result.typ = newType(tyString, context)
  122. result.info = traitCall.info
  123. of "arity":
  124. result = newIntNode(nkIntLit, operand.len - ord(operand.kind==tyProc))
  125. result.typ = newType(tyInt, context)
  126. result.info = traitCall.info
  127. of "genericHead":
  128. var res = uninstantiate(operand)
  129. if res == operand and res.kind notin tyMagicGenerics:
  130. localError(c.config, traitCall.info,
  131. "genericHead expects a generic type. The given type was " &
  132. typeToString(operand))
  133. return newType(tyError, context).toNode(traitCall.info)
  134. result = res.base.toNode(traitCall.info)
  135. of "stripGenericParams":
  136. result = uninstantiate(operand).toNode(traitCall.info)
  137. of "supportsCopyMem":
  138. let t = operand.skipTypes({tyVar, tyLent, tyGenericInst, tyAlias, tySink, tyInferred})
  139. let complexObj = containsGarbageCollectedRef(t) or
  140. hasDestructor(t)
  141. result = newIntNodeT(ord(not complexObj), traitCall, c.graph)
  142. else:
  143. localError(c.config, traitCall.info, "unknown trait: " & s)
  144. result = newNodeI(nkEmpty, traitCall.info)
  145. proc semTypeTraits(c: PContext, n: PNode): PNode =
  146. checkMinSonsLen(n, 2, c.config)
  147. let t = n.sons[1].typ
  148. internalAssert c.config, t != nil and t.kind == tyTypeDesc
  149. if t.sonsLen > 0:
  150. # This is either a type known to sem or a typedesc
  151. # param to a regular proc (again, known at instantiation)
  152. result = evalTypeTrait(c, n, t, getCurrOwner(c))
  153. else:
  154. # a typedesc variable, pass unmodified to evals
  155. result = n
  156. proc semOrd(c: PContext, n: PNode): PNode =
  157. result = n
  158. let parType = n.sons[1].typ
  159. if isOrdinalType(parType, allowEnumWithHoles=true):
  160. discard
  161. elif parType.kind == tySet:
  162. result.typ = makeRangeType(c, firstOrd(c.config, parType), lastOrd(c.config, parType), n.info)
  163. else:
  164. localError(c.config, n.info, errOrdinalTypeExpected)
  165. result.typ = errorType(c)
  166. proc semBindSym(c: PContext, n: PNode): PNode =
  167. result = copyNode(n)
  168. result.add(n.sons[0])
  169. let sl = semConstExpr(c, n.sons[1])
  170. if sl.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit}:
  171. localError(c.config, n.sons[1].info, errStringLiteralExpected)
  172. return errorNode(c, n)
  173. let isMixin = semConstExpr(c, n.sons[2])
  174. if isMixin.kind != nkIntLit or isMixin.intVal < 0 or
  175. isMixin.intVal > high(TSymChoiceRule).int:
  176. localError(c.config, n.sons[2].info, errConstExprExpected)
  177. return errorNode(c, n)
  178. let id = newIdentNode(getIdent(c.cache, sl.strVal), n.info)
  179. let s = qualifiedLookUp(c, id, {checkUndeclared})
  180. if s != nil:
  181. # we need to mark all symbols:
  182. var sc = symChoice(c, id, s, TSymChoiceRule(isMixin.intVal))
  183. if not (c.inStaticContext > 0 or getCurrOwner(c).isCompileTimeProc):
  184. # inside regular code, bindSym resolves to the sym-choice
  185. # nodes (see tinspectsymbol)
  186. return sc
  187. result.add(sc)
  188. else:
  189. errorUndeclaredIdentifier(c, n.sons[1].info, sl.strVal)
  190. proc opBindSym(c: PContext, scope: PScope, n: PNode, isMixin: int, info: PNode): PNode =
  191. if n.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit, nkIdent}:
  192. localError(c.config, info.info, errStringOrIdentNodeExpected)
  193. return errorNode(c, n)
  194. if isMixin < 0 or isMixin > high(TSymChoiceRule).int:
  195. localError(c.config, info.info, errConstExprExpected)
  196. return errorNode(c, n)
  197. let id = if n.kind == nkIdent: n
  198. else: newIdentNode(getIdent(c.cache, n.strVal), info.info)
  199. let tmpScope = c.currentScope
  200. c.currentScope = scope
  201. let s = qualifiedLookUp(c, id, {checkUndeclared})
  202. if s != nil:
  203. # we need to mark all symbols:
  204. result = symChoice(c, id, s, TSymChoiceRule(isMixin))
  205. else:
  206. errorUndeclaredIdentifier(c, info.info, if n.kind == nkIdent: n.ident.s
  207. else: n.strVal)
  208. c.currentScope = tmpScope
  209. proc semDynamicBindSym(c: PContext, n: PNode): PNode =
  210. # inside regular code, bindSym resolves to the sym-choice
  211. # nodes (see tinspectsymbol)
  212. if not (c.inStaticContext > 0 or getCurrOwner(c).isCompileTimeProc):
  213. return semBindSym(c, n)
  214. if c.graph.vm.isNil:
  215. setupGlobalCtx(c.module, c.graph)
  216. let
  217. vm = PCtx c.graph.vm
  218. # cache the current scope to
  219. # prevent it lost into oblivion
  220. scope = c.currentScope
  221. # cannot use this
  222. # vm.config.features.incl dynamicBindSym
  223. proc bindSymWrapper(a: VmArgs) =
  224. # capture PContext and currentScope
  225. # param description:
  226. # 0. ident, a string literal / computed string / or ident node
  227. # 1. bindSym rule
  228. # 2. info node
  229. a.setResult opBindSym(c, scope, a.getNode(0), a.getInt(1).int, a.getNode(2))
  230. let
  231. # altough we use VM callback here, it is not
  232. # executed like 'normal' VM callback
  233. idx = vm.registerCallback("bindSymImpl", bindSymWrapper)
  234. # dummy node to carry idx information to VM
  235. idxNode = newIntTypeNode(nkIntLit, idx, c.graph.getSysType(TLineInfo(), tyInt))
  236. result = copyNode(n)
  237. for x in n: result.add x
  238. result.add n # info node
  239. result.add idxNode
  240. proc semShallowCopy(c: PContext, n: PNode, flags: TExprFlags): PNode
  241. proc semOf(c: PContext, n: PNode): PNode =
  242. if sonsLen(n) == 3:
  243. n.sons[1] = semExprWithType(c, n.sons[1])
  244. n.sons[2] = semExprWithType(c, n.sons[2], {efDetermineType})
  245. #restoreOldStyleType(n.sons[1])
  246. #restoreOldStyleType(n.sons[2])
  247. let a = skipTypes(n.sons[1].typ, abstractPtrs)
  248. let b = skipTypes(n.sons[2].typ, abstractPtrs)
  249. let x = skipTypes(n.sons[1].typ, abstractPtrs-{tyTypeDesc})
  250. let y = skipTypes(n.sons[2].typ, abstractPtrs-{tyTypeDesc})
  251. if x.kind == tyTypeDesc or y.kind != tyTypeDesc:
  252. localError(c.config, n.info, "'of' takes object types")
  253. elif b.kind != tyObject or a.kind != tyObject:
  254. localError(c.config, n.info, "'of' takes object types")
  255. else:
  256. let diff = inheritanceDiff(a, b)
  257. # | returns: 0 iff `a` == `b`
  258. # | returns: -x iff `a` is the x'th direct superclass of `b`
  259. # | returns: +x iff `a` is the x'th direct subclass of `b`
  260. # | returns: `maxint` iff `a` and `b` are not compatible at all
  261. if diff <= 0:
  262. # optimize to true:
  263. message(c.config, n.info, hintConditionAlwaysTrue, renderTree(n))
  264. result = newIntNode(nkIntLit, 1)
  265. result.info = n.info
  266. result.typ = getSysType(c.graph, n.info, tyBool)
  267. return result
  268. elif diff == high(int):
  269. if commonSuperclass(a, b) == nil:
  270. localError(c.config, n.info, "'$1' cannot be of this subtype" % typeToString(a))
  271. else:
  272. message(c.config, n.info, hintConditionAlwaysFalse, renderTree(n))
  273. result = newIntNode(nkIntLit, 0)
  274. result.info = n.info
  275. result.typ = getSysType(c.graph, n.info, tyBool)
  276. else:
  277. localError(c.config, n.info, "'of' takes 2 arguments")
  278. n.typ = getSysType(c.graph, n.info, tyBool)
  279. result = n
  280. proc magicsAfterOverloadResolution(c: PContext, n: PNode,
  281. flags: TExprFlags): PNode =
  282. ## This is the preferred code point to implement magics.
  283. ## ``c`` the current module, a symbol table to a very good approximation
  284. ## ``n`` the ast like it would be passed to a real macro
  285. ## ``flags`` Some flags for more contextual information on how the
  286. ## "macro" is calld.
  287. case n[0].sym.magic
  288. of mAddr:
  289. checkSonsLen(n, 2, c.config)
  290. result = semAddr(c, n.sons[1], n[0].sym.name.s == "unsafeAddr")
  291. of mTypeOf:
  292. result = semTypeOf(c, n)
  293. of mSizeOf:
  294. # TODO there is no proper way to find out if a type cannot be queried for the size.
  295. let size = getSize(c.config, n[1].typ)
  296. # We just assume here that the type might come from the c backend
  297. if size == szUnknownSize:
  298. # Forward to the c code generation to emit a `sizeof` in the C code.
  299. result = n
  300. elif size >= 0:
  301. result = newIntNode(nkIntLit, size)
  302. result.info = n.info
  303. result.typ = n.typ
  304. else:
  305. localError(c.config, n.info, "cannot evaluate 'sizeof' because its type is not defined completely, type: " & n[1].typ.typeToString)
  306. result = n
  307. of mAlignOf:
  308. result = newIntNode(nkIntLit, getAlign(c.config, n[1].typ))
  309. result.info = n.info
  310. result.typ = n.typ
  311. of mOffsetOf:
  312. var dotExpr: PNode
  313. block findDotExpr:
  314. if n[1].kind == nkDotExpr:
  315. dotExpr = n[1]
  316. elif n[1].kind == nkCheckedFieldExpr:
  317. dotExpr = n[1][0]
  318. else:
  319. illFormedAst(n, c.config)
  320. assert dotExpr != nil
  321. let value = dotExpr[0]
  322. let member = dotExpr[1]
  323. discard computeSize(c.config, value.typ)
  324. result = newIntNode(nkIntLit, member.sym.offset)
  325. result.info = n.info
  326. result.typ = n.typ
  327. of mArrGet:
  328. result = semArrGet(c, n, flags)
  329. of mArrPut:
  330. result = semArrPut(c, n, flags)
  331. of mAsgn:
  332. if n[0].sym.name.s == "=":
  333. result = semAsgnOpr(c, n)
  334. else:
  335. result = semShallowCopy(c, n, flags)
  336. of mIsPartOf: result = semIsPartOf(c, n, flags)
  337. of mTypeTrait: result = semTypeTraits(c, n)
  338. of mAstToStr:
  339. result = newStrNodeT(renderTree(n[1], {renderNoComments}), n, c.graph)
  340. result.typ = getSysType(c.graph, n.info, tyString)
  341. of mInstantiationInfo: result = semInstantiationInfo(c, n)
  342. of mOrd: result = semOrd(c, n)
  343. of mOf: result = semOf(c, n)
  344. of mHigh, mLow: result = semLowHigh(c, n, n[0].sym.magic)
  345. of mShallowCopy: result = semShallowCopy(c, n, flags)
  346. of mNBindSym:
  347. if dynamicBindSym notin c.features:
  348. result = semBindSym(c, n)
  349. else:
  350. result = semDynamicBindSym(c, n)
  351. of mProcCall:
  352. result = n
  353. result.typ = n[1].typ
  354. of mDotDot:
  355. result = n
  356. of mRoof:
  357. localError(c.config, n.info, "builtin roof operator is not supported anymore")
  358. of mPlugin:
  359. let plugin = getPlugin(c.cache, n[0].sym)
  360. if plugin.isNil:
  361. localError(c.config, n.info, "cannot find plugin " & n[0].sym.name.s)
  362. result = n
  363. else:
  364. result = plugin(c, n)
  365. else: result = n