evaltempl.nim 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Template evaluation engine. Now hygienic.
  10. import
  11. strutils, options, ast, astalgo, msgs, os, idents, wordrecg, renderer,
  12. lineinfos
  13. type
  14. TemplCtx = object
  15. owner, genSymOwner: PSym
  16. instLines: bool # use the instantiation lines numbers
  17. isDeclarative: bool
  18. mapping: TIdTable # every gensym'ed symbol needs to be mapped to some
  19. # new symbol
  20. config: ConfigRef
  21. proc copyNode(ctx: TemplCtx, a, b: PNode): PNode =
  22. result = copyNode(a)
  23. if ctx.instLines: result.info = b.info
  24. proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx, result: PNode) =
  25. template handleParam(param) =
  26. let x = param
  27. if x.kind == nkArgList:
  28. for y in items(x): result.add(y)
  29. else:
  30. result.add copyTree(x)
  31. case templ.kind
  32. of nkSym:
  33. var s = templ.sym
  34. if s.owner.id == c.owner.id:
  35. if s.kind == skParam and sfGenSym notin s.flags:
  36. handleParam actual.sons[s.position]
  37. elif s.kind == skGenericParam or
  38. s.kind == skType and s.typ != nil and s.typ.kind == tyGenericParam:
  39. handleParam actual.sons[s.owner.typ.len + s.position - 1]
  40. else:
  41. internalAssert c.config, sfGenSym in s.flags or s.kind == skType
  42. var x = PSym(idTableGet(c.mapping, s))
  43. if x == nil:
  44. x = copySym(s, false)
  45. x.owner = c.genSymOwner
  46. idTablePut(c.mapping, s, x)
  47. result.add newSymNode(x, if c.instLines: actual.info else: templ.info)
  48. else:
  49. result.add copyNode(c, templ, actual)
  50. of nkNone..nkIdent, nkType..nkNilLit: # atom
  51. result.add copyNode(c, templ, actual)
  52. of nkCommentStmt:
  53. # for the documentation generator we don't keep documentation comments
  54. # in the AST that would confuse it (bug #9432), but only if we are not in a
  55. # "declarative" context (bug #9235).
  56. if c.isDeclarative:
  57. var res = copyNode(c, templ, actual)
  58. for i in countup(0, sonsLen(templ) - 1):
  59. evalTemplateAux(templ.sons[i], actual, c, res)
  60. result.add res
  61. else:
  62. result.add newNodeI(nkEmpty, templ.info)
  63. else:
  64. var isDeclarative = false
  65. if templ.kind in {nkProcDef, nkFuncDef, nkMethodDef, nkIteratorDef,
  66. nkMacroDef, nkTemplateDef, nkConverterDef, nkTypeSection,
  67. nkVarSection, nkLetSection, nkConstSection} and
  68. not c.isDeclarative:
  69. c.isDeclarative = true
  70. isDeclarative = true
  71. var res = copyNode(c, templ, actual)
  72. for i in countup(0, sonsLen(templ) - 1):
  73. evalTemplateAux(templ.sons[i], actual, c, res)
  74. result.add res
  75. if isDeclarative: c.isDeclarative = false
  76. const
  77. errWrongNumberOfArguments = "wrong number of arguments"
  78. errMissingGenericParamsForTemplate = "'$1' has unspecified generic parameters"
  79. errTemplateInstantiationTooNested = "template instantiation too nested"
  80. proc evalTemplateArgs(n: PNode, s: PSym; conf: ConfigRef; fromHlo: bool): PNode =
  81. # if the template has zero arguments, it can be called without ``()``
  82. # `n` is then a nkSym or something similar
  83. var totalParams = case n.kind
  84. of nkCallKinds: n.len-1
  85. else: 0
  86. var
  87. # XXX: Since immediate templates are not subject to the
  88. # standard sigmatching algorithm, they will have a number
  89. # of deficiencies when it comes to generic params:
  90. # Type dependencies between the parameters won't be honoured
  91. # and the bound generic symbols won't be resolvable within
  92. # their bodies. We could try to fix this, but it may be
  93. # wiser to just deprecate immediate templates and macros
  94. # now that we have working untyped parameters.
  95. genericParams = if sfImmediate in s.flags or fromHlo: 0
  96. else: s.ast[genericParamsPos].len
  97. expectedRegularParams = s.typ.len-1
  98. givenRegularParams = totalParams - genericParams
  99. if givenRegularParams < 0: givenRegularParams = 0
  100. if totalParams > expectedRegularParams + genericParams:
  101. globalError(conf, n.info, errWrongNumberOfArguments)
  102. if totalParams < genericParams:
  103. globalError(conf, n.info, errMissingGenericParamsForTemplate %
  104. n.renderTree)
  105. result = newNodeI(nkArgList, n.info)
  106. for i in 1 .. givenRegularParams:
  107. result.addSon n[i]
  108. # handle parameters with default values, which were
  109. # not supplied by the user
  110. for i in givenRegularParams+1 .. expectedRegularParams:
  111. let default = s.typ.n.sons[i].sym.ast
  112. if default.isNil or default.kind == nkEmpty:
  113. localError(conf, n.info, errWrongNumberOfArguments)
  114. addSon(result, newNodeI(nkEmpty, n.info))
  115. else:
  116. addSon(result, default.copyTree)
  117. # add any generic paramaters
  118. for i in 1 .. genericParams:
  119. result.addSon n.sons[givenRegularParams + i]
  120. # to prevent endless recursion in template instantiation
  121. const evalTemplateLimit* = 1000
  122. proc wrapInComesFrom*(info: TLineInfo; sym: PSym; res: PNode): PNode =
  123. when true:
  124. result = res
  125. result.info = info
  126. if result.kind in {nkStmtList, nkStmtListExpr} and result.len > 0:
  127. result.lastSon.info = info
  128. when false:
  129. # this hack is required to
  130. var x = result
  131. while x.kind == nkStmtListExpr: x = x.lastSon
  132. if x.kind in nkCallKinds:
  133. for i in 1..<x.len:
  134. if x[i].kind in nkCallKinds:
  135. x.sons[i].info = info
  136. else:
  137. result = newNodeI(nkStmtListExpr, info)
  138. var d = newNodeI(nkComesFrom, info)
  139. d.add newSymNode(sym, info)
  140. result.add d
  141. result.add res
  142. result.typ = res.typ
  143. proc evalTemplate*(n: PNode, tmpl, genSymOwner: PSym;
  144. conf: ConfigRef; fromHlo=false): PNode =
  145. inc(conf.evalTemplateCounter)
  146. if conf.evalTemplateCounter > evalTemplateLimit:
  147. globalError(conf, n.info, errTemplateInstantiationTooNested)
  148. result = n
  149. # replace each param by the corresponding node:
  150. var args = evalTemplateArgs(n, tmpl, conf, fromHlo)
  151. var ctx: TemplCtx
  152. ctx.owner = tmpl
  153. ctx.genSymOwner = genSymOwner
  154. ctx.config = conf
  155. initIdTable(ctx.mapping)
  156. let body = tmpl.getBody
  157. if isAtom(body):
  158. result = newNodeI(nkPar, body.info)
  159. evalTemplateAux(body, args, ctx, result)
  160. if result.len == 1: result = result.sons[0]
  161. else:
  162. localError(conf, result.info, "illformed AST: " &
  163. renderTree(result, {renderNoComments}))
  164. else:
  165. result = copyNode(body)
  166. #ctx.instLines = body.kind notin {nkStmtList, nkStmtListExpr,
  167. # nkBlockStmt, nkBlockExpr}
  168. #if ctx.instLines: result.info = n.info
  169. for i in countup(0, safeLen(body) - 1):
  170. evalTemplateAux(body.sons[i], args, ctx, result)
  171. result.flags.incl nfFromTemplate
  172. result = wrapInComesFrom(n.info, tmpl, result)
  173. dec(conf.evalTemplateCounter)