summary refs log tree commit diff stats
path: root/compiler/semtempl.nim
blob: 26216ab4c64848d290cff9f325a9781364db59fc (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#
#
#           The Nimrod Compiler
#        (c) Copyright 2011 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

proc isExpr(n: PNode): bool = 
  # returns true if ``n`` looks like an expression
  case n.kind
  of nkIdent..nkNilLit: 
    result = true
  of nkCall..pred(nkAsgn): 
    for i in countup(0, sonsLen(n) - 1): 
      if not isExpr(n.sons[i]): 
        return false
    result = true
  else: result = false
  
proc isTypeDesc(n: PNode): bool = 
  # returns true if ``n`` looks like a type desc
  case n.kind
  of nkIdent, nkSym, nkType: 
    result = true
  of nkDotExpr, nkBracketExpr: 
    for i in countup(0, sonsLen(n) - 1): 
      if not isTypeDesc(n.sons[i]): 
        return false
    result = true
  of nkTypeOfExpr..nkEnumTy: 
    result = true
  else: result = false
  
var evalTemplateCounter: int = 0
  # to prevend endless recursion in templates instantation

proc evalTemplateArgs(c: PContext, n: PNode, s: PSym): PNode = 
  var 
    f, a: int
    arg: PNode
  f = sonsLen(s.typ) 
  # if the template has zero arguments, it can be called without ``()``
  # `n` is then a nkSym or something similar
  case n.kind
  of nkCall, nkInfix, nkPrefix, nkPostfix, nkCommand, nkCallStrLit: 
    a = sonsLen(n)
  else: a = 0
  if a > f: LocalError(n.info, errWrongNumberOfArguments)
  result = copyNode(n)
  for i in countup(1, f - 1): 
    if i < a: arg = n.sons[i]
    else: arg = copyTree(s.typ.n.sons[i].sym.ast)
    if arg == nil or arg.kind == nkEmpty: 
      LocalError(n.info, errWrongNumberOfArguments)
    elif not (s.typ.sons[i].kind in {tyTypeDesc, tyStmt, tyExpr}): 
      # concrete type means semantic checking for argument:
      # XXX This is horrible! Better make semantic checking use some kind
      # of fixpoint iteration ...
      arg = fitNode(c, s.typ.sons[i], semExprWithType(c, arg))
    addSon(result, arg)

proc evalTemplate*(c: PContext, n: PNode, sym: PSym): PNode = 
  var args: PNode
  inc(evalTemplateCounter)
  if evalTemplateCounter <= 100: 
    # replace each param by the corresponding node:
    args = evalTemplateArgs(c, n, sym)
    result = evalTemplateAux(sym.getBody, args, sym)
    dec(evalTemplateCounter)
  else:
    GlobalError(n.info, errTemplateInstantiationTooNested)
    result = n

proc symChoice(c: PContext, n: PNode, s: PSym): PNode = 
  var 
    a: PSym
    o: TOverloadIter
    i: int
  i = 0
  a = initOverloadIter(o, c, n)
  while a != nil: 
    a = nextOverloadIter(o, c, n)
    inc(i)
  if i <= 1: 
    result = newSymNode(s)
    result.info = n.info
    markUsed(n, s)
  else: 
    # semantic checking requires a type; ``fitNode`` deals with it
    # appropriately
    result = newNodeIT(nkSymChoice, n.info, newTypeS(tyNone, c))
    a = initOverloadIter(o, c, n)
    while a != nil:
      incl(a.flags, sfUsed)
      addSon(result, newSymNode(a))
      a = nextOverloadIter(o, c, n)

proc semBindStmt(c: PContext, n: PNode, toBind: var TIntSet): PNode =
  for i in 0 .. < n.len:
    var a = n.sons[i]
    if a.kind == nkIdent:
      var s = SymtabGet(c.Tab, a.ident)
      if s != nil:
        toBind.incl(s.name.id)
      else:
        localError(a.info, errUndeclaredIdentifier, a.ident.s)
    else: 
      illFormedAst(a)
  result = newNodeI(nkEmpty, n.info)

proc resolveTemplateParams(c: PContext, n: PNode, withinBind: bool, 
                           toBind: var TIntSet): PNode = 
  var s: PSym
  case n.kind
  of nkIdent: 
    if not withinBind and not Contains(toBind, n.ident.id): 
      s = SymTabLocalGet(c.Tab, n.ident)
      if s != nil: 
        result = newSymNode(s)
        result.info = n.info
      else: 
        result = n
    else: 
      Incl(toBind, n.ident.id)
      result = symChoice(c, n, lookup(c, n))
  of nkEmpty, nkSym..nkNilLit:         # atom
    result = n
  of nkBind: 
    result = resolveTemplateParams(c, n.sons[0], true, toBind)
  of nkBindStmt:
    result = semBindStmt(c, n, toBind)
  else: 
    result = n
    for i in countup(0, sonsLen(n) - 1): 
      result.sons[i] = resolveTemplateParams(c, n.sons[i], withinBind, toBind)
  
proc transformToExpr(n: PNode): PNode = 
  var realStmt: int
  result = n
  case n.kind
  of nkStmtList: 
    realStmt = - 1
    for i in countup(0, sonsLen(n) - 1): 
      case n.sons[i].kind
      of nkCommentStmt, nkEmpty, nkNilLit: 
        nil
      else: 
        if realStmt == - 1: realStmt = i
        else: realStmt = - 2
    if realStmt >= 0: result = transformToExpr(n.sons[realStmt])
    else: n.kind = nkStmtListExpr
  of nkBlockStmt: 
    n.kind = nkBlockExpr
    #nkIfStmt: n.kind := nkIfExpr; // this is not correct!
  else: 
    nil

proc semTemplateDef(c: PContext, n: PNode): PNode = 
  var s: PSym
  if c.p.owner.kind == skModule: 
    s = semIdentVis(c, skTemplate, n.sons[0], {sfExported})
    incl(s.flags, sfGlobal)
  else:
    s = semIdentVis(c, skTemplate, n.sons[0], {})
  # check parameter list:
  pushOwner(s)
  openScope(c.tab)
  n.sons[namePos] = newSymNode(s) # check that no pragmas exist:
  if n.sons[pragmasPos].kind != nkEmpty: 
    LocalError(n.info, errNoPragmasAllowedForX, "template") 
  # check that no generic parameters exist:
  if n.sons[genericParamsPos].kind != nkEmpty: 
    LocalError(n.info, errNoGenericParamsAllowedForX, "template")
  if n.sons[paramsPos].kind == nkEmpty: 
    # use ``stmt`` as implicit result type
    s.typ = newTypeS(tyProc, c)
    s.typ.n = newNodeI(nkFormalParams, n.info)
    addSon(s.typ, newTypeS(tyStmt, c))
    addSon(s.typ.n, newNodeIT(nkType, n.info, s.typ.sons[0]))
  else: 
    semParamList(c, n.sons[ParamsPos], nil, s)
    if n.sons[paramsPos].sons[0].kind == nkEmpty: 
      # use ``stmt`` as implicit result type
      s.typ.sons[0] = newTypeS(tyStmt, c)
      s.typ.n.sons[0] = newNodeIT(nkType, n.info, s.typ.sons[0])
  # XXX: obsoleted - happens in semParamList # 
  # addParams(c, s.typ.n)       # resolve parameters:
  var toBind = initIntSet()
  n.sons[bodyPos] = resolveTemplateParams(c, n.sons[bodyPos], false, toBind)
  if s.typ.sons[0].kind notin {tyStmt, tyTypeDesc}:
    n.sons[bodyPos] = transformToExpr(n.sons[bodyPos]) 
    # only parameters are resolved, no type checking is performed
  closeScope(c.tab)
  popOwner()
  s.ast = n
  result = n
  if n.sons[bodyPos].kind == nkEmpty: 
    LocalError(n.info, errImplOfXexpected, s.name.s)
  # add identifier of template as a last step to not allow recursive templates:
  addInterfaceDecl(c, s)