evaltempl.nim 7.7 KB

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