semtempl.nim 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # included from sem.nim
  10. discard """
  11. hygienic templates:
  12. template `||` (a, b: untyped): untyped =
  13. let aa = a
  14. if aa: aa else: b
  15. var
  16. a, b: T
  17. echo a || b || a
  18. Each evaluation context has to be different and we need to perform
  19. some form of preliminary symbol lookup in template definitions. Hygiene is
  20. a way to achieve lexical scoping at compile time.
  21. """
  22. const
  23. errImplOfXNotAllowed = "implementation of '$1' is not allowed"
  24. type
  25. TSymBinding = enum
  26. spNone, spGenSym, spInject
  27. proc symBinding(n: PNode): TSymBinding =
  28. for i in 0..<n.len:
  29. var it = n[i]
  30. var key = if it.kind == nkExprColonExpr: it[0] else: it
  31. if key.kind == nkIdent:
  32. case whichKeyword(key.ident)
  33. of wGensym: return spGenSym
  34. of wInject: return spInject
  35. else: discard
  36. type
  37. TSymChoiceRule = enum
  38. scClosed, scOpen, scForceOpen
  39. proc symChoice(c: PContext, n: PNode, s: PSym, r: TSymChoiceRule;
  40. isField = false): PNode =
  41. var
  42. a: PSym
  43. o: TOverloadIter
  44. var i = 0
  45. a = initOverloadIter(o, c, n)
  46. while a != nil:
  47. if a.kind != skModule:
  48. inc(i)
  49. if i > 1: break
  50. a = nextOverloadIter(o, c, n)
  51. let info = getCallLineInfo(n)
  52. if i <= 1 and r != scForceOpen:
  53. # XXX this makes more sense but breaks bootstrapping for now:
  54. # (s.kind notin routineKinds or s.magic != mNone):
  55. # for instance 'nextTry' is both in tables.nim and astalgo.nim ...
  56. if not isField or sfGenSym notin s.flags:
  57. result = newSymNode(s, info)
  58. markUsed(c, info, s)
  59. onUse(info, s)
  60. else:
  61. result = n
  62. else:
  63. # semantic checking requires a type; ``fitNode`` deals with it
  64. # appropriately
  65. let kind = if r == scClosed or n.kind == nkDotExpr: nkClosedSymChoice
  66. else: nkOpenSymChoice
  67. result = newNodeIT(kind, info, newTypeS(tyNone, c))
  68. a = initOverloadIter(o, c, n)
  69. while a != nil:
  70. if a.kind != skModule and (not isField or sfGenSym notin s.flags):
  71. incl(a.flags, sfUsed)
  72. markOwnerModuleAsUsed(c, a)
  73. result.add newSymNode(a, info)
  74. onUse(info, a)
  75. a = nextOverloadIter(o, c, n)
  76. proc semBindStmt(c: PContext, n: PNode, toBind: var IntSet): PNode =
  77. for i in 0..<n.len:
  78. var a = n[i]
  79. # If 'a' is an overloaded symbol, we used to use the first symbol
  80. # as a 'witness' and use the fact that subsequent lookups will yield
  81. # the same symbol!
  82. # This is however not true anymore for hygienic templates as semantic
  83. # processing for them changes the symbol table...
  84. let s = qualifiedLookUp(c, a, {checkUndeclared})
  85. if s != nil:
  86. # we need to mark all symbols:
  87. let sc = symChoice(c, n, s, scClosed)
  88. if sc.kind == nkSym:
  89. toBind.incl(sc.sym.id)
  90. else:
  91. for x in items(sc): toBind.incl(x.sym.id)
  92. else:
  93. illFormedAst(a, c.config)
  94. result = newNodeI(nkEmpty, n.info)
  95. proc semMixinStmt(c: PContext, n: PNode, toMixin: var IntSet): PNode =
  96. for i in 0..<n.len:
  97. toMixin.incl(considerQuotedIdent(c, n[i]).id)
  98. result = newNodeI(nkEmpty, n.info)
  99. proc replaceIdentBySym(c: PContext; n: var PNode, s: PNode) =
  100. case n.kind
  101. of nkPostfix: replaceIdentBySym(c, n[1], s)
  102. of nkPragmaExpr: replaceIdentBySym(c, n[0], s)
  103. of nkIdent, nkAccQuoted, nkSym: n = s
  104. else: illFormedAst(n, c.config)
  105. type
  106. TemplCtx = object
  107. c: PContext
  108. toBind, toMixin, toInject: IntSet
  109. owner: PSym
  110. cursorInBody: bool # only for nimsuggest
  111. scopeN: int
  112. noGenSym: int
  113. inTemplateHeader: int
  114. template withBracketExpr(ctx, x, body: untyped) =
  115. body
  116. proc getIdentNode(c: var TemplCtx, n: PNode): PNode =
  117. case n.kind
  118. of nkPostfix: result = getIdentNode(c, n[1])
  119. of nkPragmaExpr: result = getIdentNode(c, n[0])
  120. of nkIdent:
  121. result = n
  122. let s = qualifiedLookUp(c.c, n, {})
  123. if s != nil:
  124. if s.owner == c.owner and s.kind == skParam:
  125. result = newSymNode(s, n.info)
  126. of nkAccQuoted, nkSym: result = n
  127. else:
  128. illFormedAst(n, c.c.config)
  129. result = n
  130. template oldCheck(cx: TemplCtx; cond: bool): bool =
  131. (optNimV019 notin cx.c.config.globalOptions or cond)
  132. proc isTemplParam(c: TemplCtx, n: PNode): bool {.inline.} =
  133. result = n.kind == nkSym and n.sym.kind == skParam and
  134. n.sym.owner == c.owner and sfTemplateParam in n.sym.flags
  135. proc semTemplBody(c: var TemplCtx, n: PNode): PNode
  136. proc openScope(c: var TemplCtx) =
  137. openScope(c.c)
  138. proc closeScope(c: var TemplCtx) =
  139. closeScope(c.c)
  140. proc semTemplBodyScope(c: var TemplCtx, n: PNode): PNode =
  141. openScope(c)
  142. result = semTemplBody(c, n)
  143. closeScope(c)
  144. proc onlyReplaceParams(c: var TemplCtx, n: PNode): PNode =
  145. result = n
  146. if n.kind == nkIdent:
  147. let s = qualifiedLookUp(c.c, n, {})
  148. if s != nil:
  149. if s.owner == c.owner and s.kind == skParam:
  150. incl(s.flags, sfUsed)
  151. result = newSymNode(s, n.info)
  152. onUse(n.info, s)
  153. else:
  154. for i in 0..<n.safeLen:
  155. result[i] = onlyReplaceParams(c, n[i])
  156. proc newGenSym(kind: TSymKind, n: PNode, c: var TemplCtx): PSym =
  157. result = newSym(kind, considerQuotedIdent(c.c, n), c.owner, n.info)
  158. incl(result.flags, sfGenSym)
  159. incl(result.flags, sfShadowed)
  160. proc addLocalDecl(c: var TemplCtx, n: var PNode, k: TSymKind) =
  161. # locals default to 'gensym':
  162. if n.kind == nkPragmaExpr and symBinding(n[1]) == spInject:
  163. # even if injected, don't produce a sym choice here:
  164. #n = semTemplBody(c, n)
  165. var x = n[0]
  166. while true:
  167. case x.kind
  168. of nkPostfix: x = x[1]
  169. of nkPragmaExpr: x = x[0]
  170. of nkIdent: break
  171. of nkAccQuoted:
  172. # consider: type `T TemplParam` {.inject.}
  173. # it suffices to return to treat it like 'inject':
  174. n = onlyReplaceParams(c, n)
  175. return
  176. else:
  177. illFormedAst(x, c.c.config)
  178. let ident = getIdentNode(c, x)
  179. if not isTemplParam(c, ident):
  180. c.toInject.incl(x.ident.id)
  181. else:
  182. replaceIdentBySym(c.c, n, ident)
  183. else:
  184. if (n.kind == nkPragmaExpr and n.len >= 2 and n[1].kind == nkPragma):
  185. let pragmaNode = n[1]
  186. for i in 0..<pragmaNode.len:
  187. openScope(c)
  188. pragmaNode[i] = semTemplBody(c,pragmaNode[i])
  189. closeScope(c)
  190. let ident = getIdentNode(c, n)
  191. if not isTemplParam(c, ident):
  192. # fix #2670, consider:
  193. #
  194. # when b:
  195. # var a = "hi"
  196. # else:
  197. # var a = 5
  198. # echo a
  199. #
  200. # We need to ensure that both 'a' produce the same gensym'ed symbol.
  201. # So we need only check the *current* scope.
  202. let s = localSearchInScope(c.c, considerQuotedIdent(c.c, ident))
  203. if s != nil and s.owner == c.owner and sfGenSym in s.flags:
  204. onUse(n.info, s)
  205. replaceIdentBySym(c.c, n, newSymNode(s, n.info))
  206. elif n.kind != nkSym:
  207. let local = newGenSym(k, ident, c)
  208. addPrelimDecl(c.c, local)
  209. styleCheckDef(c.c.config, n.info, local)
  210. onDef(n.info, local)
  211. replaceIdentBySym(c.c, n, newSymNode(local, n.info))
  212. if k == skParam and c.inTemplateHeader > 0:
  213. local.flags.incl sfTemplateParam
  214. else:
  215. replaceIdentBySym(c.c, n, ident)
  216. proc semTemplSymbol(c: PContext, n: PNode, s: PSym; isField: bool): PNode =
  217. incl(s.flags, sfUsed)
  218. # bug #12885; ideally sem'checking is performed again afterwards marking
  219. # the symbol as used properly, but the nfSem mechanism currently prevents
  220. # that from happening, so we mark the module as used here already:
  221. markOwnerModuleAsUsed(c, s)
  222. # we do not call onUse here, as the identifier is not really
  223. # resolved here. We will fixup the used identifiers later.
  224. case s.kind
  225. of skUnknown:
  226. # Introduced in this pass! Leave it as an identifier.
  227. result = n
  228. of OverloadableSyms:
  229. result = symChoice(c, n, s, scOpen, isField)
  230. of skGenericParam:
  231. if isField and sfGenSym in s.flags: result = n
  232. else: result = newSymNodeTypeDesc(s, n.info)
  233. of skParam:
  234. result = n
  235. of skType:
  236. if isField and sfGenSym in s.flags: result = n
  237. else: result = newSymNodeTypeDesc(s, n.info)
  238. else:
  239. if isField and sfGenSym in s.flags: result = n
  240. else: result = newSymNode(s, n.info)
  241. # Issue #12832
  242. when defined(nimsuggest):
  243. suggestSym(c.config, n.info, s, c.graph.usageSym, false)
  244. if {optStyleHint, optStyleError} * c.config.globalOptions != {}:
  245. styleCheckUse(c.config, n.info, s)
  246. proc semRoutineInTemplName(c: var TemplCtx, n: PNode): PNode =
  247. result = n
  248. if n.kind == nkIdent:
  249. let s = qualifiedLookUp(c.c, n, {})
  250. if s != nil:
  251. if s.owner == c.owner and (s.kind == skParam or sfGenSym in s.flags):
  252. incl(s.flags, sfUsed)
  253. result = newSymNode(s, n.info)
  254. onUse(n.info, s)
  255. else:
  256. for i in 0..<n.safeLen:
  257. result[i] = semRoutineInTemplName(c, n[i])
  258. proc semRoutineInTemplBody(c: var TemplCtx, n: PNode, k: TSymKind): PNode =
  259. result = n
  260. checkSonsLen(n, bodyPos + 1, c.c.config)
  261. # routines default to 'inject':
  262. if n.kind notin nkLambdaKinds and symBinding(n[pragmasPos]) == spGenSym:
  263. let ident = getIdentNode(c, n[namePos])
  264. if not isTemplParam(c, ident):
  265. var s = newGenSym(k, ident, c)
  266. s.ast = n
  267. addPrelimDecl(c.c, s)
  268. styleCheckDef(c.c.config, n.info, s)
  269. onDef(n.info, s)
  270. n[namePos] = newSymNode(s, n[namePos].info)
  271. else:
  272. n[namePos] = ident
  273. else:
  274. n[namePos] = semRoutineInTemplName(c, n[namePos])
  275. # open scope for parameters
  276. openScope(c)
  277. for i in patternPos..paramsPos-1:
  278. n[i] = semTemplBody(c, n[i])
  279. if k == skTemplate: inc(c.inTemplateHeader)
  280. n[paramsPos] = semTemplBody(c, n[paramsPos])
  281. if k == skTemplate: dec(c.inTemplateHeader)
  282. for i in paramsPos+1..miscPos:
  283. n[i] = semTemplBody(c, n[i])
  284. # open scope for locals
  285. inc c.scopeN
  286. openScope(c)
  287. n[bodyPos] = semTemplBody(c, n[bodyPos])
  288. # close scope for locals
  289. closeScope(c)
  290. dec c.scopeN
  291. # close scope for parameters
  292. closeScope(c)
  293. proc semTemplSomeDecl(c: var TemplCtx, n: PNode, symKind: TSymKind; start=0) =
  294. for i in start..<n.len:
  295. var a = n[i]
  296. if a.kind == nkCommentStmt: continue
  297. if (a.kind != nkIdentDefs) and (a.kind != nkVarTuple): illFormedAst(a, c.c.config)
  298. checkMinSonsLen(a, 3, c.c.config)
  299. when defined(nimsuggest):
  300. inc c.c.inTypeContext
  301. a[^2] = semTemplBody(c, a[^2])
  302. when defined(nimsuggest):
  303. dec c.c.inTypeContext
  304. a[^1] = semTemplBody(c, a[^1])
  305. for j in 0..<a.len-2:
  306. addLocalDecl(c, a[j], symKind)
  307. proc semPattern(c: PContext, n: PNode): PNode
  308. proc semTemplBodySons(c: var TemplCtx, n: PNode): PNode =
  309. result = n
  310. for i in 0..<n.len:
  311. result[i] = semTemplBody(c, n[i])
  312. proc semTemplBody(c: var TemplCtx, n: PNode): PNode =
  313. result = n
  314. semIdeForTemplateOrGenericCheck(c.c.config, n, c.cursorInBody)
  315. case n.kind
  316. of nkIdent:
  317. if n.ident.id in c.toInject: return n
  318. let s = qualifiedLookUp(c.c, n, {})
  319. if s != nil:
  320. if s.owner == c.owner and s.kind == skParam and sfTemplateParam in s.flags:
  321. # oldCheck(c, sfGenSym notin s.flags or c.noGenSym == 0):
  322. incl(s.flags, sfUsed)
  323. result = newSymNode(s, n.info)
  324. onUse(n.info, s)
  325. elif contains(c.toBind, s.id):
  326. result = symChoice(c.c, n, s, scClosed, c.noGenSym > 0)
  327. elif contains(c.toMixin, s.name.id):
  328. result = symChoice(c.c, n, s, scForceOpen, c.noGenSym > 0)
  329. elif s.owner == c.owner and sfGenSym in s.flags and c.noGenSym == 0:
  330. # template tmp[T](x: var seq[T]) =
  331. # var yz: T
  332. incl(s.flags, sfUsed)
  333. result = newSymNode(s, n.info)
  334. onUse(n.info, s)
  335. else:
  336. result = semTemplSymbol(c.c, n, s, c.noGenSym > 0)
  337. of nkBind:
  338. result = semTemplBody(c, n[0])
  339. of nkBindStmt:
  340. result = semBindStmt(c.c, n, c.toBind)
  341. of nkMixinStmt:
  342. if c.scopeN > 0: result = semTemplBodySons(c, n)
  343. else: result = semMixinStmt(c.c, n, c.toMixin)
  344. of nkEmpty, nkSym..nkNilLit, nkComesFrom:
  345. discard
  346. of nkIfStmt:
  347. for i in 0..<n.len:
  348. var it = n[i]
  349. if it.len == 2:
  350. openScope(c)
  351. it[0] = semTemplBody(c, it[0])
  352. it[1] = semTemplBody(c, it[1])
  353. closeScope(c)
  354. else:
  355. n[i] = semTemplBodyScope(c, it)
  356. of nkWhileStmt:
  357. openScope(c)
  358. for i in 0..<n.len:
  359. n[i] = semTemplBody(c, n[i])
  360. closeScope(c)
  361. of nkCaseStmt:
  362. openScope(c)
  363. n[0] = semTemplBody(c, n[0])
  364. for i in 1..<n.len:
  365. var a = n[i]
  366. checkMinSonsLen(a, 1, c.c.config)
  367. for j in 0..<a.len-1:
  368. a[j] = semTemplBody(c, a[j])
  369. a[^1] = semTemplBodyScope(c, a[^1])
  370. closeScope(c)
  371. of nkForStmt, nkParForStmt:
  372. openScope(c)
  373. n[^2] = semTemplBody(c, n[^2])
  374. for i in 0..<n.len - 2:
  375. if n[i].kind == nkVarTuple:
  376. for j in 0..<n[i].len-1:
  377. addLocalDecl(c, n[i][j], skForVar)
  378. else:
  379. addLocalDecl(c, n[i], skForVar)
  380. openScope(c)
  381. n[^1] = semTemplBody(c, n[^1])
  382. closeScope(c)
  383. closeScope(c)
  384. of nkBlockStmt, nkBlockExpr, nkBlockType:
  385. checkSonsLen(n, 2, c.c.config)
  386. openScope(c)
  387. if n[0].kind != nkEmpty:
  388. addLocalDecl(c, n[0], skLabel)
  389. when false:
  390. # labels are always 'gensym'ed:
  391. let s = newGenSym(skLabel, n[0], c)
  392. addPrelimDecl(c.c, s)
  393. styleCheckDef(c.c.config, s)
  394. onDef(n[0].info, s)
  395. n[0] = newSymNode(s, n[0].info)
  396. n[1] = semTemplBody(c, n[1])
  397. closeScope(c)
  398. of nkTryStmt, nkHiddenTryStmt:
  399. checkMinSonsLen(n, 2, c.c.config)
  400. n[0] = semTemplBodyScope(c, n[0])
  401. for i in 1..<n.len:
  402. var a = n[i]
  403. checkMinSonsLen(a, 1, c.c.config)
  404. openScope(c)
  405. for j in 0..<a.len-1:
  406. if a[j].isInfixAs():
  407. addLocalDecl(c, a[j][2], skLet)
  408. a[j][1] = semTemplBody(c, a[j][1])
  409. else:
  410. a[j] = semTemplBody(c, a[j])
  411. a[^1] = semTemplBodyScope(c, a[^1])
  412. closeScope(c)
  413. of nkVarSection: semTemplSomeDecl(c, n, skVar)
  414. of nkLetSection: semTemplSomeDecl(c, n, skLet)
  415. of nkFormalParams:
  416. checkMinSonsLen(n, 1, c.c.config)
  417. n[0] = semTemplBody(c, n[0])
  418. semTemplSomeDecl(c, n, skParam, 1)
  419. of nkConstSection:
  420. for i in 0..<n.len:
  421. var a = n[i]
  422. if a.kind == nkCommentStmt: continue
  423. if (a.kind != nkConstDef): illFormedAst(a, c.c.config)
  424. checkSonsLen(a, 3, c.c.config)
  425. addLocalDecl(c, a[0], skConst)
  426. a[1] = semTemplBody(c, a[1])
  427. a[2] = semTemplBody(c, a[2])
  428. of nkTypeSection:
  429. for i in 0..<n.len:
  430. var a = n[i]
  431. if a.kind == nkCommentStmt: continue
  432. if (a.kind != nkTypeDef): illFormedAst(a, c.c.config)
  433. checkSonsLen(a, 3, c.c.config)
  434. addLocalDecl(c, a[0], skType)
  435. for i in 0..<n.len:
  436. var a = n[i]
  437. if a.kind == nkCommentStmt: continue
  438. if (a.kind != nkTypeDef): illFormedAst(a, c.c.config)
  439. checkSonsLen(a, 3, c.c.config)
  440. if a[1].kind != nkEmpty:
  441. openScope(c)
  442. a[1] = semTemplBody(c, a[1])
  443. a[2] = semTemplBody(c, a[2])
  444. closeScope(c)
  445. else:
  446. a[2] = semTemplBody(c, a[2])
  447. of nkProcDef, nkLambdaKinds:
  448. result = semRoutineInTemplBody(c, n, skProc)
  449. of nkFuncDef:
  450. result = semRoutineInTemplBody(c, n, skFunc)
  451. of nkMethodDef:
  452. result = semRoutineInTemplBody(c, n, skMethod)
  453. of nkIteratorDef:
  454. result = semRoutineInTemplBody(c, n, skIterator)
  455. of nkTemplateDef:
  456. result = semRoutineInTemplBody(c, n, skTemplate)
  457. of nkMacroDef:
  458. result = semRoutineInTemplBody(c, n, skMacro)
  459. of nkConverterDef:
  460. result = semRoutineInTemplBody(c, n, skConverter)
  461. of nkPragmaExpr:
  462. result[0] = semTemplBody(c, n[0])
  463. of nkPostfix:
  464. result[1] = semTemplBody(c, n[1])
  465. of nkPragma:
  466. for x in n:
  467. if x.kind == nkExprColonExpr:
  468. x[1] = semTemplBody(c, x[1])
  469. of nkBracketExpr:
  470. result = newNodeI(nkCall, n.info)
  471. result.add newIdentNode(getIdent(c.c.cache, "[]"), n.info)
  472. for i in 0..<n.len: result.add(n[i])
  473. let n0 = semTemplBody(c, n[0])
  474. withBracketExpr c, n0:
  475. result = semTemplBodySons(c, result)
  476. of nkCurlyExpr:
  477. result = newNodeI(nkCall, n.info)
  478. result.add newIdentNode(getIdent(c.c.cache, "{}"), n.info)
  479. for i in 0..<n.len: result.add(n[i])
  480. result = semTemplBodySons(c, result)
  481. of nkAsgn, nkFastAsgn:
  482. checkSonsLen(n, 2, c.c.config)
  483. let a = n[0]
  484. let b = n[1]
  485. let k = a.kind
  486. case k
  487. of nkBracketExpr:
  488. result = newNodeI(nkCall, n.info)
  489. result.add newIdentNode(getIdent(c.c.cache, "[]="), n.info)
  490. for i in 0..<a.len: result.add(a[i])
  491. result.add(b)
  492. let a0 = semTemplBody(c, a[0])
  493. withBracketExpr c, a0:
  494. result = semTemplBodySons(c, result)
  495. of nkCurlyExpr:
  496. result = newNodeI(nkCall, n.info)
  497. result.add newIdentNode(getIdent(c.c.cache, "{}="), n.info)
  498. for i in 0..<a.len: result.add(a[i])
  499. result.add(b)
  500. result = semTemplBodySons(c, result)
  501. else:
  502. result = semTemplBodySons(c, n)
  503. of nkCallKinds-{nkPostfix}:
  504. # do not transform runnableExamples (bug #9143)
  505. if not isRunnableExamples(n[0]):
  506. result = semTemplBodySons(c, n)
  507. of nkDotExpr, nkAccQuoted:
  508. # dotExpr is ambiguous: note that we explicitly allow 'x.TemplateParam',
  509. # so we use the generic code for nkDotExpr too
  510. let s = qualifiedLookUp(c.c, n, {})
  511. if s != nil:
  512. # do not symchoice a quoted template parameter (bug #2390):
  513. if s.owner == c.owner and s.kind == skParam and
  514. n.kind == nkAccQuoted and n.len == 1:
  515. incl(s.flags, sfUsed)
  516. onUse(n.info, s)
  517. return newSymNode(s, n.info)
  518. elif contains(c.toBind, s.id):
  519. return symChoice(c.c, n, s, scClosed, c.noGenSym > 0)
  520. elif contains(c.toMixin, s.name.id):
  521. return symChoice(c.c, n, s, scForceOpen, c.noGenSym > 0)
  522. else:
  523. return symChoice(c.c, n, s, scOpen, c.noGenSym > 0)
  524. if n.kind == nkDotExpr:
  525. result = n
  526. result[0] = semTemplBody(c, n[0])
  527. if optNimV019 notin c.c.config.globalOptions: inc c.noGenSym
  528. result[1] = semTemplBody(c, n[1])
  529. if optNimV019 notin c.c.config.globalOptions: dec c.noGenSym
  530. else:
  531. result = semTemplBodySons(c, n)
  532. of nkExprColonExpr, nkExprEqExpr:
  533. if n.len == 2:
  534. if optNimV019 notin c.c.config.globalOptions: inc c.noGenSym
  535. result[0] = semTemplBody(c, n[0])
  536. if optNimV019 notin c.c.config.globalOptions: dec c.noGenSym
  537. result[1] = semTemplBody(c, n[1])
  538. else:
  539. result = semTemplBodySons(c, n)
  540. else:
  541. result = semTemplBodySons(c, n)
  542. proc semTemplBodyDirty(c: var TemplCtx, n: PNode): PNode =
  543. result = n
  544. semIdeForTemplateOrGenericCheck(c.c.config, n, c.cursorInBody)
  545. case n.kind
  546. of nkIdent:
  547. let s = qualifiedLookUp(c.c, n, {})
  548. if s != nil:
  549. if s.owner == c.owner and s.kind == skParam:
  550. result = newSymNode(s, n.info)
  551. elif contains(c.toBind, s.id):
  552. result = symChoice(c.c, n, s, scClosed)
  553. of nkBind:
  554. result = semTemplBodyDirty(c, n[0])
  555. of nkBindStmt:
  556. result = semBindStmt(c.c, n, c.toBind)
  557. of nkEmpty, nkSym..nkNilLit, nkComesFrom:
  558. discard
  559. else:
  560. # dotExpr is ambiguous: note that we explicitly allow 'x.TemplateParam',
  561. # so we use the generic code for nkDotExpr too
  562. if n.kind == nkDotExpr or n.kind == nkAccQuoted:
  563. let s = qualifiedLookUp(c.c, n, {})
  564. if s != nil and contains(c.toBind, s.id):
  565. return symChoice(c.c, n, s, scClosed)
  566. result = n
  567. for i in 0..<n.len:
  568. result[i] = semTemplBodyDirty(c, n[i])
  569. proc semTemplateDef(c: PContext, n: PNode): PNode =
  570. var s: PSym
  571. if isTopLevel(c):
  572. s = semIdentVis(c, skTemplate, n[0], {sfExported})
  573. incl(s.flags, sfGlobal)
  574. else:
  575. s = semIdentVis(c, skTemplate, n[0], {})
  576. if s.owner != nil:
  577. const names = ["!=", ">=", ">", "incl", "excl", "in", "notin", "isnot"]
  578. if sfSystemModule in s.owner.flags and s.name.s in names or
  579. s.owner.name.s == "vm" and s.name.s == "stackTrace":
  580. incl(s.flags, sfCallsite)
  581. styleCheckDef(c.config, s)
  582. onDef(n[0].info, s)
  583. # check parameter list:
  584. #s.scope = c.currentScope
  585. pushOwner(c, s)
  586. openScope(c)
  587. n[namePos] = newSymNode(s, n[namePos].info)
  588. if n[pragmasPos].kind != nkEmpty:
  589. pragma(c, s, n[pragmasPos], templatePragmas)
  590. var gp: PNode
  591. if n[genericParamsPos].kind != nkEmpty:
  592. n[genericParamsPos] = semGenericParamList(c, n[genericParamsPos])
  593. gp = n[genericParamsPos]
  594. else:
  595. gp = newNodeI(nkGenericParams, n.info)
  596. # process parameters:
  597. var allUntyped = true
  598. if n[paramsPos].kind != nkEmpty:
  599. semParamList(c, n[paramsPos], gp, s)
  600. # a template's parameters are not gensym'ed even if that was originally the
  601. # case as we determine whether it's a template parameter in the template
  602. # body by the absence of the sfGenSym flag:
  603. for i in 1..<s.typ.n.len:
  604. let param = s.typ.n[i].sym
  605. param.flags.incl sfTemplateParam
  606. param.flags.excl sfGenSym
  607. if param.typ.kind != tyUntyped: allUntyped = false
  608. if gp.len > 0:
  609. if n[genericParamsPos].kind == nkEmpty:
  610. # we have a list of implicit type parameters:
  611. n[genericParamsPos] = gp
  612. else:
  613. s.typ = newTypeS(tyProc, c)
  614. # XXX why do we need tyTyped as a return type again?
  615. s.typ.n = newNodeI(nkFormalParams, n.info)
  616. rawAddSon(s.typ, newTypeS(tyTyped, c))
  617. s.typ.n.add newNodeIT(nkType, n.info, s.typ[0])
  618. if allUntyped: incl(s.flags, sfAllUntyped)
  619. if n[patternPos].kind != nkEmpty:
  620. n[patternPos] = semPattern(c, n[patternPos])
  621. var ctx: TemplCtx
  622. ctx.toBind = initIntSet()
  623. ctx.toMixin = initIntSet()
  624. ctx.toInject = initIntSet()
  625. ctx.c = c
  626. ctx.owner = s
  627. if sfDirty in s.flags:
  628. n[bodyPos] = semTemplBodyDirty(ctx, n[bodyPos])
  629. else:
  630. n[bodyPos] = semTemplBody(ctx, n[bodyPos])
  631. # only parameters are resolved, no type checking is performed
  632. semIdeForTemplateOrGeneric(c, n[bodyPos], ctx.cursorInBody)
  633. closeScope(c)
  634. popOwner(c)
  635. s.ast = n
  636. result = n
  637. if sfCustomPragma in s.flags:
  638. if n[bodyPos].kind != nkEmpty:
  639. localError(c.config, n[bodyPos].info, errImplOfXNotAllowed % s.name.s)
  640. elif n[bodyPos].kind == nkEmpty:
  641. localError(c.config, n.info, "implementation of '$1' expected" % s.name.s)
  642. var proto = searchForProc(c, c.currentScope, s)
  643. if proto == nil:
  644. addInterfaceOverloadableSymAt(c, c.currentScope, s)
  645. else:
  646. symTabReplace(c.currentScope.symbols, proto, s)
  647. if n[patternPos].kind != nkEmpty:
  648. c.patterns.add(s)
  649. proc semPatternBody(c: var TemplCtx, n: PNode): PNode =
  650. template templToExpand(s: untyped): untyped =
  651. s.kind == skTemplate and (s.typ.len == 1 or sfAllUntyped in s.flags)
  652. proc newParam(c: var TemplCtx, n: PNode, s: PSym): PNode =
  653. # the param added in the current scope is actually wrong here for
  654. # macros because they have a shadowed param of type 'PNimNode' (see
  655. # semtypes.addParamOrResult). Within the pattern we have to ensure
  656. # to use the param with the proper type though:
  657. incl(s.flags, sfUsed)
  658. onUse(n.info, s)
  659. let x = c.owner.typ.n[s.position+1].sym
  660. assert x.name == s.name
  661. result = newSymNode(x, n.info)
  662. proc handleSym(c: var TemplCtx, n: PNode, s: PSym): PNode =
  663. result = n
  664. if s != nil:
  665. if s.owner == c.owner and s.kind == skParam:
  666. result = newParam(c, n, s)
  667. elif contains(c.toBind, s.id):
  668. result = symChoice(c.c, n, s, scClosed)
  669. elif templToExpand(s):
  670. result = semPatternBody(c, semTemplateExpr(c.c, n, s, {efNoSemCheck}))
  671. else:
  672. discard
  673. # we keep the ident unbound for matching instantiated symbols and
  674. # more flexibility
  675. proc expectParam(c: var TemplCtx, n: PNode): PNode =
  676. let s = qualifiedLookUp(c.c, n, {})
  677. if s != nil and s.owner == c.owner and s.kind == skParam:
  678. result = newParam(c, n, s)
  679. else:
  680. localError(c.c.config, n.info, "invalid expression")
  681. result = n
  682. proc stupidStmtListExpr(n: PNode): bool =
  683. for i in 0..<n.len-1:
  684. if n[i].kind notin {nkEmpty, nkCommentStmt}: return false
  685. result = true
  686. result = n
  687. case n.kind
  688. of nkIdent:
  689. let s = qualifiedLookUp(c.c, n, {})
  690. result = handleSym(c, n, s)
  691. of nkBindStmt:
  692. result = semBindStmt(c.c, n, c.toBind)
  693. of nkEmpty, nkSym..nkNilLit: discard
  694. of nkCurlyExpr:
  695. # we support '(pattern){x}' to bind a subpattern to a parameter 'x';
  696. # '(pattern){|x}' does the same but the matches will be gathered in 'x'
  697. if n.len != 2:
  698. localError(c.c.config, n.info, "invalid expression")
  699. elif n[1].kind == nkIdent:
  700. n[0] = semPatternBody(c, n[0])
  701. n[1] = expectParam(c, n[1])
  702. elif n[1].kind == nkPrefix and n[1][0].kind == nkIdent:
  703. let opr = n[1][0]
  704. if opr.ident.s == "|":
  705. n[0] = semPatternBody(c, n[0])
  706. n[1][1] = expectParam(c, n[1][1])
  707. else:
  708. localError(c.c.config, n.info, "invalid expression")
  709. else:
  710. localError(c.c.config, n.info, "invalid expression")
  711. of nkStmtList, nkStmtListExpr:
  712. if stupidStmtListExpr(n):
  713. result = semPatternBody(c, n.lastSon)
  714. else:
  715. for i in 0..<n.len:
  716. result[i] = semPatternBody(c, n[i])
  717. of nkCallKinds:
  718. let s = qualifiedLookUp(c.c, n[0], {})
  719. if s != nil:
  720. if s.owner == c.owner and s.kind == skParam: discard
  721. elif contains(c.toBind, s.id): discard
  722. elif templToExpand(s):
  723. return semPatternBody(c, semTemplateExpr(c.c, n, s, {efNoSemCheck}))
  724. if n.kind == nkInfix and (let id = considerQuotedIdent(c.c, n[0]); id != nil):
  725. # we interpret `*` and `|` only as pattern operators if they occur in
  726. # infix notation, so that '`*`(a, b)' can be used for verbatim matching:
  727. if id.s == "*" or id.s == "**":
  728. result = newNodeI(nkPattern, n.info, n.len)
  729. result[0] = newIdentNode(id, n.info)
  730. result[1] = semPatternBody(c, n[1])
  731. result[2] = expectParam(c, n[2])
  732. return
  733. elif id.s == "|":
  734. result = newNodeI(nkPattern, n.info, n.len)
  735. result[0] = newIdentNode(id, n.info)
  736. result[1] = semPatternBody(c, n[1])
  737. result[2] = semPatternBody(c, n[2])
  738. return
  739. if n.kind == nkPrefix and (let id = considerQuotedIdent(c.c, n[0]); id != nil):
  740. if id.s == "~":
  741. result = newNodeI(nkPattern, n.info, n.len)
  742. result[0] = newIdentNode(id, n.info)
  743. result[1] = semPatternBody(c, n[1])
  744. return
  745. for i in 0..<n.len:
  746. result[i] = semPatternBody(c, n[i])
  747. else:
  748. # dotExpr is ambiguous: note that we explicitly allow 'x.TemplateParam',
  749. # so we use the generic code for nkDotExpr too
  750. case n.kind
  751. of nkDotExpr, nkAccQuoted:
  752. let s = qualifiedLookUp(c.c, n, {})
  753. if s != nil:
  754. if contains(c.toBind, s.id):
  755. return symChoice(c.c, n, s, scClosed)
  756. else:
  757. return newIdentNode(s.name, n.info)
  758. of nkPar:
  759. if n.len == 1: return semPatternBody(c, n[0])
  760. else: discard
  761. for i in 0..<n.len:
  762. result[i] = semPatternBody(c, n[i])
  763. proc semPattern(c: PContext, n: PNode): PNode =
  764. openScope(c)
  765. var ctx: TemplCtx
  766. ctx.toBind = initIntSet()
  767. ctx.toMixin = initIntSet()
  768. ctx.toInject = initIntSet()
  769. ctx.c = c
  770. ctx.owner = getCurrOwner(c)
  771. result = flattenStmts(semPatternBody(ctx, n))
  772. if result.kind in {nkStmtList, nkStmtListExpr}:
  773. if result.len == 1:
  774. result = result[0]
  775. elif result.len == 0:
  776. localError(c.config, n.info, "a pattern cannot be empty")
  777. closeScope(c)