summary refs log tree commit diff stats
path: root/compiler/semmagic.nim
blob: 932f36c2f98fefc927ce42febc7d176df85fcdde (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#
#
#           The Nimrod Compiler
#        (c) Copyright 2012 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# This include file implements the semantic checking for magics.

proc semIsPartOf(c: PContext, n: PNode, flags: TExprFlags): PNode =
  var r = isPartOf(n[1], n[2])
  result = newIntNodeT(ord(r), n)
  
proc semSlurp(c: PContext, n: PNode, flags: TExprFlags): PNode = 
  assert sonsLen(n) == 2
  var a = expectStringArg(c, n, 0)
  try:
    var filename = a.strVal.FindFile
    var content = readFile(filename)
    result = newStrNode(nkStrLit, content)
    result.typ = getSysType(tyString)
    result.info = n.info
    c.slurpedFiles.add(filename)
  except EIO:
    GlobalError(a.info, errCannotOpenFile, a.strVal)

proc expectIntLit(c: PContext, n: PNode): int =
  let x = c.semConstExpr(c, n)
  case x.kind
  of nkIntLit..nkInt64Lit: result = int(x.intVal)
  else: GlobalError(n.info, errIntLiteralExpected)

proc semInstantiationInfo(c: PContext, n: PNode): PNode =
  result = newNodeIT(nkPar, n.info, n.typ)
  let idx = expectIntLit(c, n.sons[1])
  let info = getInfoContext(idx)
  var filename = newNodeIT(nkStrLit, n.info, getSysType(tyString))
  filename.strVal = ToFilename(info)
  var line = newNodeIT(nkIntLit, n.info, getSysType(tyInt))
  line.intVal = ToLinenumber(info)
  result.add(filename)
  result.add(line)

proc magicsAfterOverloadResolution(c: PContext, n: PNode, 
                                   flags: TExprFlags): PNode =
  case n[0].sym.magic
  of mSlurp: result = semSlurp(c, n, flags)
  of mIsPartOf: result = semIsPartOf(c, n, flags)
  of mAstToStr:
    result = newStrNodeT(renderTree(n[1], {renderNoComments}), n)
    result.typ = getSysType(tyString)
  of mInstantiationInfo: result = semInstantiationInfo(c, n)
  else: result = n