evaltempl.nim 7.3 KB

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