semmagic.nim 15 KB

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