evaltempl.nim 7.4 KB

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