evaltempl.nim 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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, trees
  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: setInfoRecursive(result, 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, 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. if (not c.isDeclarative) and templ.kind in nkCallKinds and isRunnableExamples(templ[0]):
  81. # fixes bug #16993, bug #18054
  82. discard
  83. else:
  84. var res = copyNode(c, templ, actual)
  85. for i in 0..<templ.len:
  86. evalTemplateAux(templ[i], actual, c, res)
  87. result.add res
  88. if isDeclarative: c.isDeclarative = false
  89. const
  90. errWrongNumberOfArguments = "wrong number of arguments"
  91. errMissingGenericParamsForTemplate = "'$1' has unspecified generic parameters"
  92. errTemplateInstantiationTooNested = "template instantiation too nested"
  93. proc evalTemplateArgs(n: PNode, s: PSym; conf: ConfigRef; fromHlo: bool): PNode =
  94. # if the template has zero arguments, it can be called without ``()``
  95. # `n` is then a nkSym or something similar
  96. var totalParams = case n.kind
  97. of nkCallKinds: n.len-1
  98. else: 0
  99. var
  100. # XXX: Since immediate templates are not subject to the
  101. # standard sigmatching algorithm, they will have a number
  102. # of deficiencies when it comes to generic params:
  103. # Type dependencies between the parameters won't be honoured
  104. # and the bound generic symbols won't be resolvable within
  105. # their bodies. We could try to fix this, but it may be
  106. # wiser to just deprecate immediate templates and macros
  107. # now that we have working untyped parameters.
  108. genericParams = if fromHlo: 0
  109. else: s.ast[genericParamsPos].len
  110. expectedRegularParams = s.typ.len-1
  111. givenRegularParams = totalParams - genericParams
  112. if givenRegularParams < 0: givenRegularParams = 0
  113. if totalParams > expectedRegularParams + genericParams:
  114. globalError(conf, n.info, errWrongNumberOfArguments)
  115. if totalParams < genericParams:
  116. globalError(conf, n.info, errMissingGenericParamsForTemplate %
  117. n.renderTree)
  118. result = newNodeI(nkArgList, n.info)
  119. for i in 1..givenRegularParams:
  120. result.add n[i]
  121. # handle parameters with default values, which were
  122. # not supplied by the user
  123. for i in givenRegularParams+1..expectedRegularParams:
  124. let default = s.typ.n[i].sym.ast
  125. if default.isNil or default.kind == nkEmpty:
  126. localError(conf, n.info, errWrongNumberOfArguments)
  127. result.add newNodeI(nkEmpty, n.info)
  128. else:
  129. result.add default.copyTree
  130. # add any generic parameters
  131. for i in 1..genericParams:
  132. result.add n[givenRegularParams + i]
  133. # to prevent endless recursion in template instantiation
  134. const evalTemplateLimit* = 1000
  135. proc wrapInComesFrom*(info: TLineInfo; sym: PSym; res: PNode): PNode =
  136. when true:
  137. result = res
  138. result.info = info
  139. if result.kind in {nkStmtList, nkStmtListExpr} and result.len > 0:
  140. result.lastSon.info = info
  141. when false:
  142. # this hack is required to
  143. var x = result
  144. while x.kind == nkStmtListExpr: x = x.lastSon
  145. if x.kind in nkCallKinds:
  146. for i in 1..<x.len:
  147. if x[i].kind in nkCallKinds:
  148. x[i].info = info
  149. else:
  150. result = newNodeI(nkStmtListExpr, info)
  151. var d = newNodeI(nkComesFrom, info)
  152. d.add newSymNode(sym, info)
  153. result.add d
  154. result.add res
  155. result.typ = res.typ
  156. proc evalTemplate*(n: PNode, tmpl, genSymOwner: PSym;
  157. conf: ConfigRef;
  158. ic: IdentCache; instID: ref int;
  159. idgen: IdGenerator;
  160. fromHlo=false): PNode =
  161. inc(conf.evalTemplateCounter)
  162. if conf.evalTemplateCounter > evalTemplateLimit:
  163. globalError(conf, n.info, errTemplateInstantiationTooNested)
  164. result = n
  165. # replace each param by the corresponding node:
  166. var args = evalTemplateArgs(n, tmpl, conf, fromHlo)
  167. var ctx: TemplCtx
  168. ctx.owner = tmpl
  169. ctx.genSymOwner = genSymOwner
  170. ctx.config = conf
  171. ctx.ic = ic
  172. ctx.mapping = initIdTable()
  173. ctx.instID = instID[]
  174. ctx.idgen = idgen
  175. let body = tmpl.ast[bodyPos]
  176. #echo "instantion of ", renderTree(body, {renderIds})
  177. if isAtom(body):
  178. result = newNodeI(nkPar, body.info)
  179. evalTemplateAux(body, args, ctx, result)
  180. if result.len == 1: result = result[0]
  181. else:
  182. localError(conf, result.info, "illformed AST: " &
  183. renderTree(result, {renderNoComments}))
  184. else:
  185. result = copyNode(body)
  186. ctx.instLines = sfCallsite in tmpl.flags
  187. if ctx.instLines:
  188. setInfoRecursive(result, n.info)
  189. for i in 0..<body.safeLen:
  190. evalTemplateAux(body[i], args, ctx, result)
  191. result.flags.incl nfFromTemplate
  192. result = wrapInComesFrom(n.info, tmpl, result)
  193. #if ctx.debugActive:
  194. # echo "instantion of ", renderTree(result, {renderIds})
  195. dec(conf.evalTemplateCounter)
  196. # The instID must be unique for every template instantiation, so we increment it here
  197. inc instID[]