evaltempl.nim 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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, renderer, lineinfos, idents
  12. type
  13. TemplCtx = object
  14. owner, genSymOwner: PSym
  15. instLines: bool # use the instantiation lines numbers
  16. isDeclarative: bool
  17. mapping: TIdTable # every gensym'ed symbol needs to be mapped to some
  18. # new symbol
  19. config: ConfigRef
  20. ic: IdentCache
  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 == nil and s.kind == skParam) or s.owner == c.owner:
  35. if s.kind == skParam and {sfGenSym, sfTemplateParam} * s.flags == {sfTemplateParam}:
  36. handleParam actual[s.position]
  37. elif (s.owner != nil) and (s.kind == skGenericParam or
  38. s.kind == skType and s.typ != nil and s.typ.kind == tyGenericParam):
  39. handleParam actual[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)
  45. # sem'check needs to set the owner properly later, see bug #9476
  46. x.owner = nil # c.genSymOwner
  47. #if x.kind == skParam and x.owner.kind == skModule:
  48. # internalAssert c.config, false
  49. idTablePut(c.mapping, s, x)
  50. if sfGenSym in s.flags and optNimV019 notin c.config.globalOptions:
  51. result.add newIdentNode(getIdent(c.ic, x.name.s & "`gensym" & $x.id),
  52. if c.instLines: actual.info else: templ.info)
  53. else:
  54. result.add newSymNode(x, if c.instLines: actual.info else: templ.info)
  55. else:
  56. result.add copyNode(c, templ, actual)
  57. of nkNone..nkIdent, nkType..nkNilLit: # atom
  58. result.add copyNode(c, templ, actual)
  59. of nkCommentStmt:
  60. # for the documentation generator we don't keep documentation comments
  61. # in the AST that would confuse it (bug #9432), but only if we are not in a
  62. # "declarative" context (bug #9235).
  63. if c.isDeclarative:
  64. var res = copyNode(c, templ, actual)
  65. for i in 0..<templ.len:
  66. evalTemplateAux(templ[i], actual, c, res)
  67. result.add res
  68. else:
  69. result.add newNodeI(nkEmpty, templ.info)
  70. else:
  71. var isDeclarative = false
  72. if templ.kind in {nkProcDef, nkFuncDef, nkMethodDef, nkIteratorDef,
  73. nkMacroDef, nkTemplateDef, nkConverterDef, nkTypeSection,
  74. nkVarSection, nkLetSection, nkConstSection} and
  75. not c.isDeclarative:
  76. c.isDeclarative = true
  77. isDeclarative = true
  78. var res = copyNode(c, templ, actual)
  79. for i in 0..<templ.len:
  80. evalTemplateAux(templ[i], actual, c, res)
  81. result.add res
  82. if isDeclarative: c.isDeclarative = false
  83. const
  84. errWrongNumberOfArguments = "wrong number of arguments"
  85. errMissingGenericParamsForTemplate = "'$1' has unspecified generic parameters"
  86. errTemplateInstantiationTooNested = "template instantiation too nested"
  87. proc evalTemplateArgs(n: PNode, s: PSym; conf: ConfigRef; fromHlo: bool): PNode =
  88. # if the template has zero arguments, it can be called without ``()``
  89. # `n` is then a nkSym or something similar
  90. var totalParams = case n.kind
  91. of nkCallKinds: n.len-1
  92. else: 0
  93. var
  94. # XXX: Since immediate templates are not subject to the
  95. # standard sigmatching algorithm, they will have a number
  96. # of deficiencies when it comes to generic params:
  97. # Type dependencies between the parameters won't be honoured
  98. # and the bound generic symbols won't be resolvable within
  99. # their bodies. We could try to fix this, but it may be
  100. # wiser to just deprecate immediate templates and macros
  101. # now that we have working untyped parameters.
  102. genericParams = if fromHlo: 0
  103. else: s.ast[genericParamsPos].len
  104. expectedRegularParams = s.typ.len-1
  105. givenRegularParams = totalParams - genericParams
  106. if givenRegularParams < 0: givenRegularParams = 0
  107. if totalParams > expectedRegularParams + genericParams:
  108. globalError(conf, n.info, errWrongNumberOfArguments)
  109. if totalParams < genericParams:
  110. globalError(conf, n.info, errMissingGenericParamsForTemplate %
  111. n.renderTree)
  112. result = newNodeI(nkArgList, n.info)
  113. for i in 1..givenRegularParams:
  114. result.add n[i]
  115. # handle parameters with default values, which were
  116. # not supplied by the user
  117. for i in givenRegularParams+1..expectedRegularParams:
  118. let default = s.typ.n[i].sym.ast
  119. if default.isNil or default.kind == nkEmpty:
  120. localError(conf, n.info, errWrongNumberOfArguments)
  121. result.add newNodeI(nkEmpty, n.info)
  122. else:
  123. result.add default.copyTree
  124. # add any generic parameters
  125. for i in 1..genericParams:
  126. result.add n[givenRegularParams + i]
  127. # to prevent endless recursion in template instantiation
  128. const evalTemplateLimit* = 1000
  129. proc wrapInComesFrom*(info: TLineInfo; sym: PSym; res: PNode): PNode =
  130. when true:
  131. result = res
  132. result.info = info
  133. if result.kind in {nkStmtList, nkStmtListExpr} and result.len > 0:
  134. result.lastSon.info = info
  135. when false:
  136. # this hack is required to
  137. var x = result
  138. while x.kind == nkStmtListExpr: x = x.lastSon
  139. if x.kind in nkCallKinds:
  140. for i in 1..<x.len:
  141. if x[i].kind in nkCallKinds:
  142. x[i].info = info
  143. else:
  144. result = newNodeI(nkStmtListExpr, info)
  145. var d = newNodeI(nkComesFrom, info)
  146. d.add newSymNode(sym, info)
  147. result.add d
  148. result.add res
  149. result.typ = res.typ
  150. proc evalTemplate*(n: PNode, tmpl, genSymOwner: PSym;
  151. conf: ConfigRef;
  152. ic: IdentCache;
  153. fromHlo=false): PNode =
  154. inc(conf.evalTemplateCounter)
  155. if conf.evalTemplateCounter > evalTemplateLimit:
  156. globalError(conf, n.info, errTemplateInstantiationTooNested)
  157. result = n
  158. # replace each param by the corresponding node:
  159. var args = evalTemplateArgs(n, tmpl, conf, fromHlo)
  160. var ctx: TemplCtx
  161. ctx.owner = tmpl
  162. ctx.genSymOwner = genSymOwner
  163. ctx.config = conf
  164. ctx.ic = ic
  165. initIdTable(ctx.mapping)
  166. let body = tmpl.getBody
  167. #echo "instantion of ", renderTree(body, {renderIds})
  168. if isAtom(body):
  169. result = newNodeI(nkPar, body.info)
  170. evalTemplateAux(body, args, ctx, result)
  171. if result.len == 1: result = result[0]
  172. else:
  173. localError(conf, result.info, "illformed AST: " &
  174. renderTree(result, {renderNoComments}))
  175. else:
  176. result = copyNode(body)
  177. ctx.instLines = sfCallsite in tmpl.flags
  178. if ctx.instLines:
  179. result.info = n.info
  180. for i in 0..<body.safeLen:
  181. evalTemplateAux(body[i], args, ctx, result)
  182. result.flags.incl nfFromTemplate
  183. result = wrapInComesFrom(n.info, tmpl, result)
  184. #if ctx.debugActive:
  185. # echo "instantion of ", renderTree(result, {renderIds})
  186. dec(conf.evalTemplateCounter)