semmagic.nim 17 KB

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