semtempl.nim 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  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. result = spNone
  29. for i in 0..<n.len:
  30. var it = n[i]
  31. var key = if it.kind == nkExprColonExpr: it[0] else: it
  32. if key.kind == nkIdent:
  33. case whichKeyword(key.ident)
  34. of wGensym: return spGenSym
  35. of wInject: return spInject
  36. else: discard
  37. type
  38. TSymChoiceRule = enum
  39. scClosed, scOpen, scForceOpen
  40. proc symChoice(c: PContext, n: PNode, s: PSym, r: TSymChoiceRule;
  41. isField = false): PNode =
  42. var
  43. a: PSym
  44. o: TOverloadIter = default(TOverloadIter)
  45. var i = 0
  46. a = initOverloadIter(o, c, n)
  47. while a != nil:
  48. if a.kind != skModule:
  49. inc(i)
  50. if i > 1: break
  51. a = nextOverloadIter(o, c, n)
  52. let info = getCallLineInfo(n)
  53. if i <= 1 and r != scForceOpen:
  54. # XXX this makes more sense but breaks bootstrapping for now:
  55. # (s.kind notin routineKinds or s.magic != mNone):
  56. # for instance 'nextTry' is both in tables.nim and astalgo.nim ...
  57. if not isField or sfGenSym notin s.flags:
  58. result = newSymNode(s, info)
  59. # possibly not final field sym
  60. incl(s.flags, sfUsed)
  61. markOwnerModuleAsUsed(c, s)
  62. onUse(info, s)
  63. else:
  64. result = n
  65. elif i == 0:
  66. # forced open but symbol not in scope, retain information
  67. result = n
  68. else:
  69. # semantic checking requires a type; ``fitNode`` deals with it
  70. # appropriately
  71. let kind = if r == scClosed or n.kind == nkDotExpr: nkClosedSymChoice
  72. else: nkOpenSymChoice
  73. result = newNodeIT(kind, info, newTypeS(tyNone, c))
  74. a = initOverloadIter(o, c, n)
  75. while a != nil:
  76. if a.kind != skModule and (not isField or sfGenSym notin a.flags):
  77. incl(a.flags, sfUsed)
  78. markOwnerModuleAsUsed(c, a)
  79. result.add newSymNode(a, info)
  80. onUse(info, a)
  81. a = nextOverloadIter(o, c, n)
  82. proc semBindStmt(c: PContext, n: PNode, toBind: var IntSet): PNode =
  83. result = copyNode(n)
  84. for i in 0..<n.len:
  85. var a = n[i]
  86. # If 'a' is an overloaded symbol, we used to use the first symbol
  87. # as a 'witness' and use the fact that subsequent lookups will yield
  88. # the same symbol!
  89. # This is however not true anymore for hygienic templates as semantic
  90. # processing for them changes the symbol table...
  91. let s = qualifiedLookUp(c, a, {checkUndeclared})
  92. if s != nil:
  93. # we need to mark all symbols:
  94. let sc = symChoice(c, n, s, scClosed)
  95. if sc.kind == nkSym:
  96. toBind.incl(sc.sym.id)
  97. result.add sc
  98. else:
  99. for x in items(sc):
  100. toBind.incl(x.sym.id)
  101. result.add x
  102. else:
  103. illFormedAst(a, c.config)
  104. proc semMixinStmt(c: PContext, n: PNode, toMixin: var IntSet): PNode =
  105. result = copyNode(n)
  106. for i in 0..<n.len:
  107. toMixin.incl(considerQuotedIdent(c, n[i]).id)
  108. let x = symChoice(c, n[i], nil, scForceOpen)
  109. result.add x
  110. proc replaceIdentBySym(c: PContext; n: var PNode, s: PNode) =
  111. case n.kind
  112. of nkPostfix: replaceIdentBySym(c, n[1], s)
  113. of nkPragmaExpr: replaceIdentBySym(c, n[0], s)
  114. of nkIdent, nkAccQuoted, nkSym: n = s
  115. else: illFormedAst(n, c.config)
  116. type
  117. TemplCtx = object
  118. c: PContext
  119. toBind, toMixin, toInject: IntSet
  120. owner: PSym
  121. cursorInBody: bool # only for nimsuggest
  122. scopeN: int
  123. noGenSym: int
  124. inTemplateHeader: int
  125. proc isTemplParam(c: TemplCtx, s: PSym): bool {.inline.} =
  126. result = s.kind == skParam and
  127. s.owner == c.owner and sfTemplateParam in s.flags
  128. proc getIdentReplaceParams(c: var TemplCtx, n: var PNode): tuple[node: PNode, hasParam: bool] =
  129. case n.kind
  130. of nkPostfix: result = getIdentReplaceParams(c, n[1])
  131. of nkPragmaExpr: result = getIdentReplaceParams(c, n[0])
  132. of nkIdent:
  133. result = (n, false)
  134. let s = qualifiedLookUp(c.c, n, {})
  135. if s != nil and isTemplParam(c, s):
  136. n = newSymNode(s, n.info)
  137. result = (n, true)
  138. of nkSym:
  139. result = (n, isTemplParam(c, n.sym))
  140. of nkAccQuoted:
  141. result = (n, false)
  142. for i in 0..<n.safeLen:
  143. let (ident, hasParam) = getIdentReplaceParams(c, n[i])
  144. if hasParam:
  145. result.node[i] = ident
  146. result.hasParam = true
  147. else:
  148. illFormedAst(n, c.c.config)
  149. result = (n, false)
  150. proc semTemplBody(c: var TemplCtx, n: PNode): PNode
  151. proc openScope(c: var TemplCtx) =
  152. openScope(c.c)
  153. proc closeScope(c: var TemplCtx) =
  154. closeScope(c.c)
  155. proc semTemplBodyScope(c: var TemplCtx, n: PNode): PNode =
  156. openScope(c)
  157. result = semTemplBody(c, n)
  158. closeScope(c)
  159. proc newGenSym(kind: TSymKind, n: PNode, c: var TemplCtx): PSym =
  160. result = newSym(kind, considerQuotedIdent(c.c, n), c.c.idgen, c.owner, n.info)
  161. incl(result.flags, sfGenSym)
  162. incl(result.flags, sfShadowed)
  163. proc addLocalDecl(c: var TemplCtx, n: var PNode, k: TSymKind) =
  164. # locals default to 'gensym', fields default to 'inject':
  165. if (n.kind == nkPragmaExpr and symBinding(n[1]) == spInject) or
  166. k == skField:
  167. # even if injected, don't produce a sym choice here:
  168. #n = semTemplBody(c, n)
  169. let (ident, hasParam) = getIdentReplaceParams(c, n)
  170. if not hasParam:
  171. if k != skField:
  172. c.toInject.incl(considerQuotedIdent(c.c, ident).id)
  173. else:
  174. if (n.kind == nkPragmaExpr and n.len >= 2 and n[1].kind == nkPragma):
  175. let pragmaNode = n[1]
  176. for i in 0..<pragmaNode.len:
  177. let ni = pragmaNode[i]
  178. # see D20210801T100514
  179. var found = false
  180. if ni.kind == nkIdent:
  181. for a in templatePragmas:
  182. if ni.ident.id == ord(a):
  183. found = true
  184. break
  185. if not found:
  186. openScope(c)
  187. pragmaNode[i] = semTemplBody(c, pragmaNode[i])
  188. closeScope(c)
  189. let (ident, hasParam) = getIdentReplaceParams(c, n)
  190. if not hasParam:
  191. if n.kind != nkSym and not (n.kind == nkIdent and n.ident.id == ord(wUnderscore)):
  192. let local = newGenSym(k, ident, c)
  193. addPrelimDecl(c.c, local)
  194. styleCheckDef(c.c, n.info, local)
  195. onDef(n.info, local)
  196. replaceIdentBySym(c.c, n, newSymNode(local, n.info))
  197. if k == skParam and c.inTemplateHeader > 0:
  198. local.flags.incl sfTemplateParam
  199. proc semTemplSymbol(c: var TemplCtx, n: PNode, s: PSym; isField, isAmbiguous: bool): PNode =
  200. incl(s.flags, sfUsed)
  201. # bug #12885; ideally sem'checking is performed again afterwards marking
  202. # the symbol as used properly, but the nfSem mechanism currently prevents
  203. # that from happening, so we mark the module as used here already:
  204. markOwnerModuleAsUsed(c.c, s)
  205. # we do not call onUse here, as the identifier is not really
  206. # resolved here. We will fixup the used identifiers later.
  207. case s.kind
  208. of skUnknown:
  209. # Introduced in this pass! Leave it as an identifier.
  210. result = n
  211. of OverloadableSyms:
  212. result = symChoice(c.c, n, s, scOpen, isField)
  213. if not isField and result.kind in {nkSym, nkOpenSymChoice}:
  214. if openSym in c.c.features:
  215. if result.kind == nkSym:
  216. result = newOpenSym(result)
  217. else:
  218. result.typ() = nil
  219. else:
  220. result.flags.incl nfDisabledOpenSym
  221. result.typ() = nil
  222. of skGenericParam:
  223. if isField and sfGenSym in s.flags: result = n
  224. else:
  225. result = newSymNodeTypeDesc(s, c.c.idgen, n.info)
  226. if not isField and s.owner != c.owner:
  227. if openSym in c.c.features:
  228. result = newOpenSym(result)
  229. else:
  230. result.flags.incl nfDisabledOpenSym
  231. result.typ() = nil
  232. of skParam:
  233. result = n
  234. of skType:
  235. if isField and sfGenSym in s.flags: result = n
  236. else:
  237. if isAmbiguous:
  238. # ambiguous types should be symchoices since lookup behaves
  239. # differently for them in regular expressions
  240. result = symChoice(c.c, n, s, scOpen, isField)
  241. else: result = newSymNodeTypeDesc(s, c.c.idgen, n.info)
  242. if not isField and not (s.owner == c.owner and
  243. s.typ != nil and s.typ.kind == tyGenericParam) and
  244. result.kind in {nkSym, nkOpenSymChoice}:
  245. if openSym in c.c.features:
  246. if result.kind == nkSym:
  247. result = newOpenSym(result)
  248. else:
  249. result.typ() = nil
  250. else:
  251. result.flags.incl nfDisabledOpenSym
  252. result.typ() = nil
  253. else:
  254. if isField and sfGenSym in s.flags: result = n
  255. else:
  256. result = newSymNode(s, n.info)
  257. if not isField:
  258. if openSym in c.c.features:
  259. result = newOpenSym(result)
  260. else:
  261. result.flags.incl nfDisabledOpenSym
  262. result.typ() = nil
  263. # Issue #12832
  264. when defined(nimsuggest):
  265. suggestSym(c.c.graph, n.info, s, c.c.graph.usageSym, false)
  266. # field access (dot expr) will be handled by builtinFieldAccess
  267. if not isField:
  268. styleCheckUse(c.c, n.info, s)
  269. proc semRoutineInTemplName(c: var TemplCtx, n: PNode, explicitInject: bool): PNode =
  270. result = n
  271. if n.kind == nkIdent:
  272. let s = qualifiedLookUp(c.c, n, {})
  273. if s != nil:
  274. if s.owner == c.owner and (s.kind == skParam or
  275. (sfGenSym in s.flags and not explicitInject)):
  276. incl(s.flags, sfUsed)
  277. result = newSymNode(s, n.info)
  278. onUse(n.info, s)
  279. else:
  280. for i in 0..<n.safeLen:
  281. result[i] = semRoutineInTemplName(c, n[i], explicitInject)
  282. proc semRoutineInTemplBody(c: var TemplCtx, n: PNode, k: TSymKind): PNode =
  283. result = n
  284. checkSonsLen(n, bodyPos + 1, c.c.config)
  285. if n.kind notin nkLambdaKinds:
  286. # routines default to 'inject':
  287. let binding = symBinding(n[pragmasPos])
  288. if binding == spGenSym:
  289. let (ident, hasParam) = getIdentReplaceParams(c, n[namePos])
  290. if not hasParam:
  291. var s = newGenSym(k, ident, c)
  292. s.ast = n
  293. addPrelimDecl(c.c, s)
  294. styleCheckDef(c.c, n.info, s)
  295. onDef(n.info, s)
  296. n[namePos] = newSymNode(s, n[namePos].info)
  297. else:
  298. n[namePos] = ident
  299. else:
  300. n[namePos] = semRoutineInTemplName(c, n[namePos], binding == spInject)
  301. # open scope for parameters
  302. openScope(c)
  303. for i in patternPos..paramsPos-1:
  304. n[i] = semTemplBody(c, n[i])
  305. if k == skTemplate: inc(c.inTemplateHeader)
  306. n[paramsPos] = semTemplBody(c, n[paramsPos])
  307. if k == skTemplate: dec(c.inTemplateHeader)
  308. for i in paramsPos+1..miscPos:
  309. n[i] = semTemplBody(c, n[i])
  310. # open scope for locals
  311. inc c.scopeN
  312. openScope(c)
  313. n[bodyPos] = semTemplBody(c, n[bodyPos])
  314. # close scope for locals
  315. closeScope(c)
  316. dec c.scopeN
  317. # close scope for parameters
  318. closeScope(c)
  319. proc semTemplIdentDef(c: var TemplCtx, a: PNode, symKind: TSymKind) =
  320. checkMinSonsLen(a, 3, c.c.config)
  321. when defined(nimsuggest):
  322. inc c.c.inTypeContext
  323. a[^2] = semTemplBody(c, a[^2])
  324. when defined(nimsuggest):
  325. dec c.c.inTypeContext
  326. a[^1] = semTemplBody(c, a[^1])
  327. for j in 0..<a.len-2:
  328. addLocalDecl(c, a[j], symKind)
  329. proc semTemplSomeDecl(c: var TemplCtx, n: PNode, symKind: TSymKind; start = 0) =
  330. for i in start..<n.len:
  331. var a = n[i]
  332. case a.kind:
  333. of nkCommentStmt: continue
  334. of nkIdentDefs, nkVarTuple, nkConstDef:
  335. semTemplIdentDef(c, a, symKind)
  336. else:
  337. illFormedAst(a, c.c.config)
  338. proc semPattern(c: PContext, n: PNode; s: PSym): PNode
  339. proc semTemplBodySons(c: var TemplCtx, n: PNode): PNode =
  340. result = n
  341. for i in 0..<n.len:
  342. result[i] = semTemplBody(c, n[i])
  343. proc semTemplBody(c: var TemplCtx, n: PNode): PNode =
  344. result = n
  345. semIdeForTemplateOrGenericCheck(c.c.config, n, c.cursorInBody)
  346. case n.kind
  347. of nkIdent:
  348. if n.ident.id in c.toInject: return n
  349. c.c.isAmbiguous = false
  350. let s = qualifiedLookUp(c.c, n, {})
  351. if s != nil:
  352. if s.owner == c.owner and s.kind == skParam and sfTemplateParam in s.flags:
  353. incl(s.flags, sfUsed)
  354. result = newSymNode(s, n.info)
  355. onUse(n.info, s)
  356. elif contains(c.toBind, s.id):
  357. result = symChoice(c.c, n, s, scClosed, c.noGenSym > 0)
  358. elif contains(c.toMixin, s.name.id):
  359. result = symChoice(c.c, n, s, scForceOpen, c.noGenSym > 0)
  360. elif s.owner == c.owner and sfGenSym in s.flags and c.noGenSym == 0:
  361. # template tmp[T](x: var seq[T]) =
  362. # var yz: T
  363. incl(s.flags, sfUsed)
  364. result = newSymNode(s, n.info)
  365. onUse(n.info, s)
  366. else:
  367. if s.kind in {skVar, skLet, skConst}:
  368. discard qualifiedLookUp(c.c, n, {checkAmbiguity, checkModule})
  369. result = semTemplSymbol(c, n, s, c.noGenSym > 0, c.c.isAmbiguous)
  370. of nkBind:
  371. result = semTemplBody(c, n[0])
  372. of nkBindStmt:
  373. result = semBindStmt(c.c, n, c.toBind)
  374. of nkMixinStmt:
  375. if c.scopeN > 0: result = semTemplBodySons(c, n)
  376. else: result = semMixinStmt(c.c, n, c.toMixin)
  377. of nkEmpty, nkSym..nkNilLit, nkComesFrom:
  378. discard
  379. of nkIfStmt:
  380. for i in 0..<n.len:
  381. var it = n[i]
  382. if it.len == 2:
  383. openScope(c)
  384. it[0] = semTemplBody(c, it[0])
  385. it[1] = semTemplBody(c, it[1])
  386. closeScope(c)
  387. else:
  388. n[i] = semTemplBodyScope(c, it)
  389. of nkWhileStmt:
  390. openScope(c)
  391. for i in 0..<n.len:
  392. n[i] = semTemplBody(c, n[i])
  393. closeScope(c)
  394. of nkCaseStmt:
  395. openScope(c)
  396. n[0] = semTemplBody(c, n[0])
  397. for i in 1..<n.len:
  398. var a = n[i]
  399. checkMinSonsLen(a, 1, c.c.config)
  400. for j in 0..<a.len-1:
  401. a[j] = semTemplBody(c, a[j])
  402. a[^1] = semTemplBodyScope(c, a[^1])
  403. closeScope(c)
  404. of nkForStmt, nkParForStmt:
  405. openScope(c)
  406. n[^2] = semTemplBody(c, n[^2])
  407. for i in 0..<n.len - 2:
  408. if n[i].kind == nkVarTuple:
  409. for j in 0..<n[i].len-1:
  410. addLocalDecl(c, n[i][j], skForVar)
  411. else:
  412. addLocalDecl(c, n[i], skForVar)
  413. openScope(c)
  414. n[^1] = semTemplBody(c, n[^1])
  415. closeScope(c)
  416. closeScope(c)
  417. of nkBlockStmt, nkBlockExpr, nkBlockType:
  418. checkSonsLen(n, 2, c.c.config)
  419. openScope(c)
  420. if n[0].kind != nkEmpty:
  421. addLocalDecl(c, n[0], skLabel)
  422. when false:
  423. # labels are always 'gensym'ed:
  424. let s = newGenSym(skLabel, n[0], c)
  425. addPrelimDecl(c.c, s)
  426. styleCheckDef(c.c, s)
  427. onDef(n[0].info, s)
  428. n[0] = newSymNode(s, n[0].info)
  429. n[1] = semTemplBody(c, n[1])
  430. closeScope(c)
  431. of nkTryStmt, nkHiddenTryStmt:
  432. checkMinSonsLen(n, 2, c.c.config)
  433. n[0] = semTemplBodyScope(c, n[0])
  434. for i in 1..<n.len:
  435. var a = n[i]
  436. checkMinSonsLen(a, 1, c.c.config)
  437. openScope(c)
  438. for j in 0..<a.len-1:
  439. if a[j].isInfixAs():
  440. addLocalDecl(c, a[j][2], skLet)
  441. a[j][1] = semTemplBody(c, a[j][1])
  442. else:
  443. a[j] = semTemplBody(c, a[j])
  444. a[^1] = semTemplBodyScope(c, a[^1])
  445. closeScope(c)
  446. of nkVarSection: semTemplSomeDecl(c, n, skVar)
  447. of nkLetSection: semTemplSomeDecl(c, n, skLet)
  448. of nkFormalParams:
  449. checkMinSonsLen(n, 1, c.c.config)
  450. semTemplSomeDecl(c, n, skParam, 1)
  451. n[0] = semTemplBody(c, n[0])
  452. of nkConstSection: semTemplSomeDecl(c, n, skConst)
  453. of nkTypeSection:
  454. for i in 0..<n.len:
  455. var a = n[i]
  456. if a.kind == nkCommentStmt: continue
  457. if (a.kind != nkTypeDef): illFormedAst(a, c.c.config)
  458. checkSonsLen(a, 3, c.c.config)
  459. addLocalDecl(c, a[0], skType)
  460. for i in 0..<n.len:
  461. var a = n[i]
  462. if a.kind == nkCommentStmt: continue
  463. if (a.kind != nkTypeDef): illFormedAst(a, c.c.config)
  464. checkSonsLen(a, 3, c.c.config)
  465. if a[1].kind != nkEmpty:
  466. openScope(c)
  467. a[1] = semTemplBody(c, a[1])
  468. a[2] = semTemplBody(c, a[2])
  469. closeScope(c)
  470. else:
  471. a[2] = semTemplBody(c, a[2])
  472. of nkObjectTy:
  473. openScope(c)
  474. result = semTemplBodySons(c, n)
  475. closeScope(c)
  476. of nkRecList:
  477. for i in 0..<n.len:
  478. var a = n[i]
  479. case a.kind:
  480. of nkCommentStmt, nkNilLit, nkSym, nkEmpty: continue
  481. of nkIdentDefs:
  482. semTemplIdentDef(c, a, skField)
  483. of nkRecCase, nkRecWhen:
  484. n[i] = semTemplBody(c, a)
  485. else:
  486. illFormedAst(a, c.c.config)
  487. of nkRecCase:
  488. semTemplIdentDef(c, n[0], skField)
  489. for i in 1..<n.len:
  490. n[i] = semTemplBody(c, n[i])
  491. of nkProcDef, nkLambdaKinds:
  492. result = semRoutineInTemplBody(c, n, skProc)
  493. of nkFuncDef:
  494. result = semRoutineInTemplBody(c, n, skFunc)
  495. of nkMethodDef:
  496. result = semRoutineInTemplBody(c, n, skMethod)
  497. of nkIteratorDef:
  498. result = semRoutineInTemplBody(c, n, skIterator)
  499. of nkTemplateDef:
  500. result = semRoutineInTemplBody(c, n, skTemplate)
  501. of nkMacroDef:
  502. result = semRoutineInTemplBody(c, n, skMacro)
  503. of nkConverterDef:
  504. result = semRoutineInTemplBody(c, n, skConverter)
  505. of nkPragmaExpr:
  506. result = semTemplBodySons(c, n)
  507. of nkPostfix:
  508. result[1] = semTemplBody(c, n[1])
  509. of nkPragma:
  510. for i in 0 ..< n.len:
  511. let x = n[i]
  512. let prag = whichPragma(x)
  513. if prag == wInvalid:
  514. # only sem if not a language-level pragma
  515. result[i] = semTemplBody(c, x)
  516. elif x.kind in nkPragmaCallKinds:
  517. # is pragma, but value still needs to be checked
  518. for j in 1 ..< x.len:
  519. x[j] = semTemplBody(c, x[j])
  520. of nkBracketExpr:
  521. if n.typ == nil:
  522. # if a[b] is nested inside a typed expression, don't convert it
  523. # back to `[]`(a, b), prepareOperand will not typecheck it again
  524. # and so `[]` will not be resolved
  525. # checking if a[b] is typed should be enough to cover this case
  526. result = newNodeI(nkCall, n.info)
  527. result.add newIdentNode(getIdent(c.c.cache, "[]"), n.info)
  528. for i in 0..<n.len: result.add(n[i])
  529. result = semTemplBodySons(c, result)
  530. of nkCurlyExpr:
  531. if n.typ == nil:
  532. # see nkBracketExpr case for explanation
  533. result = newNodeI(nkCall, n.info)
  534. result.add newIdentNode(getIdent(c.c.cache, "{}"), n.info)
  535. for i in 0..<n.len: result.add(n[i])
  536. result = semTemplBodySons(c, result)
  537. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  538. checkSonsLen(n, 2, c.c.config)
  539. let a = n[0]
  540. let b = n[1]
  541. let k = a.kind
  542. case k
  543. of nkBracketExpr:
  544. if a.typ == nil:
  545. # see nkBracketExpr case above for explanation
  546. result = newNodeI(nkCall, n.info)
  547. result.add newIdentNode(getIdent(c.c.cache, "[]="), n.info)
  548. for i in 0..<a.len: result.add(a[i])
  549. result.add(b)
  550. let a0 = semTemplBody(c, a[0])
  551. result = semTemplBodySons(c, result)
  552. of nkCurlyExpr:
  553. if a.typ == nil:
  554. # see nkBracketExpr case above for explanation
  555. result = newNodeI(nkCall, n.info)
  556. result.add newIdentNode(getIdent(c.c.cache, "{}="), n.info)
  557. for i in 0..<a.len: result.add(a[i])
  558. result.add(b)
  559. result = semTemplBodySons(c, result)
  560. else:
  561. result = semTemplBodySons(c, n)
  562. of nkCallKinds-{nkPostfix}:
  563. # do not transform runnableExamples (bug #9143)
  564. if not isRunnableExamples(n[0]):
  565. result = semTemplBodySons(c, n)
  566. of nkDotExpr, nkAccQuoted:
  567. # dotExpr is ambiguous: note that we explicitly allow 'x.TemplateParam',
  568. # so we use the generic code for nkDotExpr too
  569. c.c.isAmbiguous = false
  570. let s = qualifiedLookUp(c.c, n, {})
  571. if s != nil:
  572. # mirror the nkIdent case
  573. # do not symchoice a quoted template parameter (bug #2390):
  574. if s.owner == c.owner and s.kind == skParam and
  575. n.kind == nkAccQuoted and n.len == 1:
  576. incl(s.flags, sfUsed)
  577. onUse(n.info, s)
  578. return newSymNode(s, n.info)
  579. elif contains(c.toBind, s.id):
  580. return symChoice(c.c, n, s, scClosed, c.noGenSym > 0)
  581. elif contains(c.toMixin, s.name.id):
  582. return symChoice(c.c, n, s, scForceOpen, c.noGenSym > 0)
  583. else:
  584. if s.kind in {skVar, skLet, skConst}:
  585. discard qualifiedLookUp(c.c, n, {checkAmbiguity, checkModule})
  586. return semTemplSymbol(c, n, s, c.noGenSym > 0, c.c.isAmbiguous)
  587. if n.kind == nkDotExpr:
  588. result = n
  589. result[0] = semTemplBody(c, n[0])
  590. inc c.noGenSym
  591. result[1] = semTemplBody(c, n[1])
  592. dec c.noGenSym
  593. if result[1].kind == nkSym and result[1].sym.kind in routineKinds:
  594. # prevent `dotTransformation` from rewriting this node to `nkIdent`
  595. # by making it a symchoice
  596. # in generics this becomes `nkClosedSymChoice` but this breaks code
  597. # as the old behavior here was that this became `nkIdent`
  598. var choice = newNodeIT(nkOpenSymChoice, n[1].info, newTypeS(tyNone, c.c))
  599. choice.add result[1]
  600. result[1] = choice
  601. else:
  602. result = semTemplBodySons(c, n)
  603. of nkExprColonExpr, nkExprEqExpr:
  604. if n.len == 2:
  605. inc c.noGenSym
  606. result[0] = semTemplBody(c, n[0])
  607. dec c.noGenSym
  608. result[1] = semTemplBody(c, n[1])
  609. else:
  610. result = semTemplBodySons(c, n)
  611. of nkTableConstr:
  612. # also transform the keys (bug #12595)
  613. for i in 0..<n.len:
  614. result[i] = semTemplBodySons(c, n[i])
  615. else:
  616. result = semTemplBodySons(c, n)
  617. proc semTemplBodyDirty(c: var TemplCtx, n: PNode): PNode =
  618. result = n
  619. semIdeForTemplateOrGenericCheck(c.c.config, n, c.cursorInBody)
  620. case n.kind
  621. of nkIdent:
  622. let s = qualifiedLookUp(c.c, n, {})
  623. if s != nil:
  624. if s.owner == c.owner and s.kind == skParam:
  625. result = newSymNode(s, n.info)
  626. elif contains(c.toBind, s.id):
  627. result = symChoice(c.c, n, s, scClosed)
  628. of nkBind:
  629. result = semTemplBodyDirty(c, n[0])
  630. of nkBindStmt:
  631. result = semBindStmt(c.c, n, c.toBind)
  632. of nkEmpty, nkSym..nkNilLit, nkComesFrom:
  633. discard
  634. else:
  635. # dotExpr is ambiguous: note that we explicitly allow 'x.TemplateParam',
  636. # so we use the generic code for nkDotExpr too
  637. if n.kind == nkDotExpr or n.kind == nkAccQuoted:
  638. let s = qualifiedLookUp(c.c, n, {})
  639. if s != nil and contains(c.toBind, s.id):
  640. return symChoice(c.c, n, s, scClosed)
  641. result = n
  642. for i in 0..<n.len:
  643. result[i] = semTemplBodyDirty(c, n[i])
  644. # in semstmts.nim:
  645. proc semProcAnnotation(c: PContext, prc: PNode; validPragmas: TSpecialWords): PNode
  646. proc semTemplateDef(c: PContext, n: PNode): PNode =
  647. result = semProcAnnotation(c, n, templatePragmas)
  648. if result != nil: return result
  649. result = n
  650. var s: PSym
  651. if isTopLevel(c):
  652. s = semIdentVis(c, skTemplate, n[namePos], {sfExported})
  653. incl(s.flags, sfGlobal)
  654. else:
  655. s = semIdentVis(c, skTemplate, n[namePos], {})
  656. assert s.kind == skTemplate
  657. let info = getLineInfo(n[namePos])
  658. suggestSym(c.graph, info, s, c.graph.usageSym)
  659. styleCheckDef(c, s)
  660. onDef(n[namePos].info, s)
  661. # check parameter list:
  662. #s.scope = c.currentScope
  663. # push noalias flag at first to prevent unwanted recursive calls:
  664. incl(s.flags, sfNoalias)
  665. pushOwner(c, s)
  666. openScope(c)
  667. n[namePos] = newSymNode(s)
  668. s.ast = n # for implicitPragmas to use
  669. pragmaCallable(c, s, n, templatePragmas)
  670. implicitPragmas(c, s, n.info, templatePragmas)
  671. setGenericParamsMisc(c, n)
  672. # process parameters:
  673. var allUntyped = true
  674. var nullary = true
  675. if n[paramsPos].kind != nkEmpty:
  676. semParamList(c, n[paramsPos], n[genericParamsPos], s)
  677. # a template's parameters are not gensym'ed even if that was originally the
  678. # case as we determine whether it's a template parameter in the template
  679. # body by the absence of the sfGenSym flag:
  680. let retType = s.typ.returnType
  681. if retType != nil and retType.kind != tyUntyped:
  682. allUntyped = false
  683. for i in 1..<s.typ.n.len:
  684. let param = s.typ.n[i].sym
  685. if param.name.id != ord(wUnderscore):
  686. param.flags.incl sfTemplateParam
  687. param.flags.excl sfGenSym
  688. if param.typ.kind != tyUntyped: allUntyped = false
  689. # no default value, parameters required in call
  690. if param.ast == nil: nullary = false
  691. else:
  692. s.typ = newTypeS(tyProc, c)
  693. # XXX why do we need tyTyped as a return type again?
  694. s.typ.n = newNodeI(nkFormalParams, n.info)
  695. rawAddSon(s.typ, newTypeS(tyTyped, c))
  696. s.typ.n.add newNodeIT(nkType, n.info, s.typ.returnType)
  697. if n[genericParamsPos].safeLen == 0:
  698. # restore original generic type params as no explicit or implicit were found
  699. n[genericParamsPos] = n[miscPos][1]
  700. n[miscPos] = c.graph.emptyNode
  701. if allUntyped: incl(s.flags, sfAllUntyped)
  702. if nullary and
  703. n[genericParamsPos].kind == nkEmpty and
  704. n[bodyPos].kind != nkEmpty:
  705. # template can be called with alias syntax, remove pushed noalias flag
  706. excl(s.flags, sfNoalias)
  707. if n[patternPos].kind != nkEmpty:
  708. n[patternPos] = semPattern(c, n[patternPos], s)
  709. var ctx = TemplCtx(
  710. toBind: initIntSet(),
  711. toMixin: initIntSet(),
  712. toInject: initIntSet(),
  713. c: c,
  714. owner: s
  715. )
  716. # handle default params:
  717. for i in 1..<s.typ.n.len:
  718. let param = s.typ.n[i].sym
  719. if param.ast != nil:
  720. # param default values need to be treated like template body:
  721. if sfDirty in s.flags:
  722. param.ast = semTemplBodyDirty(ctx, param.ast)
  723. else:
  724. param.ast = semTemplBody(ctx, param.ast)
  725. if param.ast.referencesAnotherParam(s):
  726. param.ast.flags.incl nfDefaultRefsParam
  727. if sfDirty in s.flags:
  728. n[bodyPos] = semTemplBodyDirty(ctx, n[bodyPos])
  729. else:
  730. n[bodyPos] = semTemplBody(ctx, n[bodyPos])
  731. # only parameters are resolved, no type checking is performed
  732. semIdeForTemplateOrGeneric(c, n[bodyPos], ctx.cursorInBody)
  733. closeScope(c)
  734. popOwner(c)
  735. if sfCustomPragma in s.flags:
  736. if n[bodyPos].kind != nkEmpty:
  737. localError(c.config, n[bodyPos].info, errImplOfXNotAllowed % s.name.s)
  738. elif n[bodyPos].kind == nkEmpty:
  739. localError(c.config, n.info, "implementation of '$1' expected" % s.name.s)
  740. var (proto, comesFromShadowscope) = searchForProc(c, c.currentScope, s)
  741. if proto == nil:
  742. addInterfaceOverloadableSymAt(c, c.currentScope, s)
  743. elif not comesFromShadowscope:
  744. if {sfTemplateRedefinition, sfGenSym} * s.flags == {}:
  745. #wrongRedefinition(c, n.info, proto.name.s, proto.info)
  746. message(c.config, n.info, warnImplicitTemplateRedefinition, s.name.s)
  747. symTabReplace(c.currentScope.symbols, proto, s)
  748. if n[patternPos].kind != nkEmpty:
  749. c.patterns.add(s)
  750. proc semPatternBody(c: var TemplCtx, n: PNode): PNode =
  751. template templToExpand(s: untyped): untyped =
  752. s.kind == skTemplate and (s.typ.len == 1 or sfAllUntyped in s.flags)
  753. proc newParam(c: var TemplCtx, n: PNode, s: PSym): PNode =
  754. # the param added in the current scope is actually wrong here for
  755. # macros because they have a shadowed param of type 'PNimNode' (see
  756. # semtypes.addParamOrResult). Within the pattern we have to ensure
  757. # to use the param with the proper type though:
  758. incl(s.flags, sfUsed)
  759. onUse(n.info, s)
  760. let x = c.owner.typ.n[s.position+1].sym
  761. assert x.name == s.name
  762. result = newSymNode(x, n.info)
  763. proc handleSym(c: var TemplCtx, n: PNode, s: PSym): PNode =
  764. result = n
  765. if s != nil:
  766. if s.owner == c.owner and s.kind == skParam:
  767. result = newParam(c, n, s)
  768. elif contains(c.toBind, s.id):
  769. result = symChoice(c.c, n, s, scClosed)
  770. elif templToExpand(s):
  771. result = semPatternBody(c, semTemplateExpr(c.c, n, s, {efNoSemCheck}))
  772. else:
  773. discard
  774. # we keep the ident unbound for matching instantiated symbols and
  775. # more flexibility
  776. proc expectParam(c: var TemplCtx, n: PNode): PNode =
  777. let s = qualifiedLookUp(c.c, n, {})
  778. if s != nil and s.owner == c.owner and s.kind == skParam:
  779. result = newParam(c, n, s)
  780. else:
  781. localError(c.c.config, n.info, "invalid expression")
  782. result = n
  783. result = n
  784. case n.kind
  785. of nkIdent:
  786. let s = qualifiedLookUp(c.c, n, {})
  787. result = handleSym(c, n, s)
  788. of nkBindStmt:
  789. result = semBindStmt(c.c, n, c.toBind)
  790. of nkEmpty, nkSym..nkNilLit: discard
  791. of nkCurlyExpr:
  792. # we support '(pattern){x}' to bind a subpattern to a parameter 'x';
  793. # '(pattern){|x}' does the same but the matches will be gathered in 'x'
  794. if n.len != 2:
  795. localError(c.c.config, n.info, "invalid expression")
  796. elif n[1].kind == nkIdent:
  797. n[0] = semPatternBody(c, n[0])
  798. n[1] = expectParam(c, n[1])
  799. elif n[1].kind == nkPrefix and n[1][0].kind == nkIdent:
  800. let opr = n[1][0]
  801. if opr.ident.s == "|":
  802. n[0] = semPatternBody(c, n[0])
  803. n[1][1] = expectParam(c, n[1][1])
  804. else:
  805. localError(c.c.config, n.info, "invalid expression")
  806. else:
  807. localError(c.c.config, n.info, "invalid expression")
  808. of nkStmtList, nkStmtListExpr:
  809. if stupidStmtListExpr(n):
  810. result = semPatternBody(c, n.lastSon)
  811. else:
  812. for i in 0..<n.len:
  813. result[i] = semPatternBody(c, n[i])
  814. of nkCallKinds:
  815. let s = qualifiedLookUp(c.c, n[0], {})
  816. if s != nil:
  817. if s.owner == c.owner and s.kind == skParam: discard
  818. elif contains(c.toBind, s.id): discard
  819. elif templToExpand(s):
  820. return semPatternBody(c, semTemplateExpr(c.c, n, s, {efNoSemCheck}))
  821. if n.kind == nkInfix and (let id = considerQuotedIdent(c.c, n[0]); id != nil):
  822. # we interpret `*` and `|` only as pattern operators if they occur in
  823. # infix notation, so that '`*`(a, b)' can be used for verbatim matching:
  824. if id.s == "*" or id.s == "**":
  825. result = newNodeI(nkPattern, n.info, n.len)
  826. result[0] = newIdentNode(id, n.info)
  827. result[1] = semPatternBody(c, n[1])
  828. result[2] = expectParam(c, n[2])
  829. return
  830. elif id.s == "|":
  831. result = newNodeI(nkPattern, n.info, n.len)
  832. result[0] = newIdentNode(id, n.info)
  833. result[1] = semPatternBody(c, n[1])
  834. result[2] = semPatternBody(c, n[2])
  835. return
  836. if n.kind == nkPrefix and (let id = considerQuotedIdent(c.c, n[0]); id != nil):
  837. if id.s == "~":
  838. result = newNodeI(nkPattern, n.info, n.len)
  839. result[0] = newIdentNode(id, n.info)
  840. result[1] = semPatternBody(c, n[1])
  841. return
  842. for i in 0..<n.len:
  843. result[i] = semPatternBody(c, n[i])
  844. else:
  845. # dotExpr is ambiguous: note that we explicitly allow 'x.TemplateParam',
  846. # so we use the generic code for nkDotExpr too
  847. case n.kind
  848. of nkDotExpr, nkAccQuoted:
  849. let s = qualifiedLookUp(c.c, n, {})
  850. if s != nil:
  851. if contains(c.toBind, s.id):
  852. return symChoice(c.c, n, s, scClosed)
  853. else:
  854. return newIdentNode(s.name, n.info)
  855. of nkPar:
  856. if n.len == 1: return semPatternBody(c, n[0])
  857. else: discard
  858. for i in 0..<n.len:
  859. result[i] = semPatternBody(c, n[i])
  860. proc semPattern(c: PContext, n: PNode; s: PSym): PNode =
  861. openScope(c)
  862. var ctx = TemplCtx(
  863. toBind: initIntSet(),
  864. toMixin: initIntSet(),
  865. toInject: initIntSet(),
  866. c: c,
  867. owner: getCurrOwner(c)
  868. )
  869. result = flattenStmts(semPatternBody(ctx, n))
  870. if result.kind in {nkStmtList, nkStmtListExpr}:
  871. if result.len == 1:
  872. result = result[0]
  873. elif result.len == 0:
  874. localError(c.config, n.info, "a pattern cannot be empty")
  875. closeScope(c)
  876. addPattern(c, LazySym(sym: s))