patterns.nim 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements the pattern matching features for term rewriting
  10. ## macro support.
  11. import
  12. ast, types, semdata, sigmatch, idents, aliases, parampatterns, trees
  13. when defined(nimPreviewSlimSystem):
  14. import std/assertions
  15. type
  16. TPatternContext = object
  17. owner: PSym
  18. mapping: seq[PNode] # maps formal parameters to nodes
  19. formals: int
  20. c: PContext
  21. subMatch: bool # subnode matches are special
  22. mappingIsFull: bool
  23. PPatternContext = var TPatternContext
  24. proc getLazy(c: PPatternContext, sym: PSym): PNode =
  25. if c.mappingIsFull:
  26. result = c.mapping[sym.position]
  27. proc putLazy(c: PPatternContext, sym: PSym, n: PNode) =
  28. if not c.mappingIsFull:
  29. newSeq(c.mapping, c.formals)
  30. c.mappingIsFull = true
  31. c.mapping[sym.position] = n
  32. proc matches(c: PPatternContext, p, n: PNode): bool
  33. proc canonKind(n: PNode): TNodeKind =
  34. ## nodekind canonicalization for pattern matching
  35. result = n.kind
  36. case result
  37. of nkCallKinds: result = nkCall
  38. of nkStrLit..nkTripleStrLit: result = nkStrLit
  39. of nkFastAsgn: result = nkAsgn
  40. else: discard
  41. proc sameKinds(a, b: PNode): bool {.inline.} =
  42. result = a.kind == b.kind or a.canonKind == b.canonKind
  43. proc sameTrees*(a, b: PNode): bool =
  44. if sameKinds(a, b):
  45. case a.kind
  46. of nkSym: result = a.sym == b.sym
  47. of nkIdent: result = a.ident.id == b.ident.id
  48. of nkCharLit..nkInt64Lit: result = a.intVal == b.intVal
  49. of nkFloatLit..nkFloat64Lit: result = a.floatVal == b.floatVal
  50. of nkStrLit..nkTripleStrLit: result = a.strVal == b.strVal
  51. of nkEmpty, nkNilLit: result = true
  52. of nkType: result = sameTypeOrNil(a.typ, b.typ)
  53. else:
  54. if a.len == b.len:
  55. for i in 0..<a.len:
  56. if not sameTrees(a[i], b[i]): return
  57. result = true
  58. proc inSymChoice(sc, x: PNode): bool =
  59. if sc.kind == nkClosedSymChoice:
  60. for i in 0..<sc.len:
  61. if sc[i].sym == x.sym: return true
  62. elif sc.kind == nkOpenSymChoice:
  63. # same name suffices for open sym choices!
  64. result = sc[0].sym.name.id == x.sym.name.id
  65. proc checkTypes(c: PPatternContext, p: PSym, n: PNode): bool =
  66. # check param constraints first here as this is quite optimized:
  67. if p.constraint != nil:
  68. result = matchNodeKinds(p.constraint, n)
  69. if not result: return
  70. if isNil(n.typ):
  71. result = p.typ.kind in {tyVoid, tyTyped}
  72. else:
  73. result = sigmatch.argtypeMatches(c.c, p.typ, n.typ, fromHlo = true)
  74. proc isPatternParam(c: PPatternContext, p: PNode): bool {.inline.} =
  75. result = p.kind == nkSym and p.sym.kind == skParam and p.sym.owner == c.owner
  76. proc matchChoice(c: PPatternContext, p, n: PNode): bool =
  77. for i in 1..<p.len:
  78. if matches(c, p[i], n): return true
  79. proc bindOrCheck(c: PPatternContext, param: PSym, n: PNode): bool =
  80. var pp = getLazy(c, param)
  81. if pp != nil:
  82. # check if we got the same pattern (already unified):
  83. result = sameTrees(pp, n) #matches(c, pp, n)
  84. elif n.kind == nkArgList or checkTypes(c, param, n):
  85. putLazy(c, param, n)
  86. result = true
  87. proc gather(c: PPatternContext, param: PSym, n: PNode) =
  88. var pp = getLazy(c, param)
  89. if pp != nil and pp.kind == nkArgList:
  90. pp.add(n)
  91. else:
  92. pp = newNodeI(nkArgList, n.info, 1)
  93. pp[0] = n
  94. putLazy(c, param, pp)
  95. proc matchNested(c: PPatternContext, p, n: PNode, rpn: bool): bool =
  96. # match ``op * param`` or ``op *| param``
  97. proc matchStarAux(c: PPatternContext, op, n, arglist: PNode,
  98. rpn: bool): bool =
  99. result = true
  100. if n.kind in nkCallKinds and matches(c, op[1], n[0]):
  101. for i in 1..<n.len:
  102. if not matchStarAux(c, op, n[i], arglist, rpn): return false
  103. if rpn: arglist.add(n[0])
  104. elif n.kind == nkHiddenStdConv and n[1].kind == nkBracket:
  105. let n = n[1]
  106. for i in 0..<n.len:
  107. if not matchStarAux(c, op, n[i], arglist, rpn): return false
  108. elif checkTypes(c, p[2].sym, n):
  109. arglist.add(n)
  110. else:
  111. result = false
  112. if n.kind notin nkCallKinds: return false
  113. if matches(c, p[1], n[0]):
  114. var arglist = newNodeI(nkArgList, n.info)
  115. if matchStarAux(c, p, n, arglist, rpn):
  116. result = bindOrCheck(c, p[2].sym, arglist)
  117. proc matches(c: PPatternContext, p, n: PNode): bool =
  118. let n = skipHidden(n)
  119. if nfNoRewrite in n.flags:
  120. result = false
  121. elif isPatternParam(c, p):
  122. result = bindOrCheck(c, p.sym, n)
  123. elif n.kind == nkSym and p.kind == nkIdent:
  124. result = p.ident.id == n.sym.name.id
  125. elif n.kind == nkSym and inSymChoice(p, n):
  126. result = true
  127. elif n.kind == nkSym and n.sym.kind == skConst:
  128. # try both:
  129. if p.kind == nkSym: result = p.sym == n.sym
  130. elif matches(c, p, n.sym.astdef): result = true
  131. elif p.kind == nkPattern:
  132. # pattern operators: | *
  133. let opr = p[0].ident.s
  134. case opr
  135. of "|": result = matchChoice(c, p, n)
  136. of "*": result = matchNested(c, p, n, rpn=false)
  137. of "**": result = matchNested(c, p, n, rpn=true)
  138. of "~": result = not matches(c, p[1], n)
  139. else: doAssert(false, "invalid pattern")
  140. # template {add(a, `&` * b)}(a: string{noalias}, b: varargs[string]) =
  141. # a.add(b)
  142. elif p.kind == nkCurlyExpr:
  143. if p[1].kind == nkPrefix:
  144. if matches(c, p[0], n):
  145. gather(c, p[1][1].sym, n)
  146. result = true
  147. else:
  148. assert isPatternParam(c, p[1])
  149. if matches(c, p[0], n):
  150. result = bindOrCheck(c, p[1].sym, n)
  151. elif sameKinds(p, n):
  152. case p.kind
  153. of nkSym: result = p.sym == n.sym
  154. of nkIdent: result = p.ident.id == n.ident.id
  155. of nkCharLit..nkInt64Lit: result = p.intVal == n.intVal
  156. of nkFloatLit..nkFloat64Lit: result = p.floatVal == n.floatVal
  157. of nkStrLit..nkTripleStrLit: result = p.strVal == n.strVal
  158. of nkEmpty, nkNilLit, nkType:
  159. result = true
  160. else:
  161. # special rule for p(X) ~ f(...); this also works for stuff like
  162. # partial case statements, etc! - Not really ... :-/
  163. let v = lastSon(p)
  164. if isPatternParam(c, v) and v.sym.typ.kind == tyVarargs:
  165. var arglist: PNode
  166. if p.len <= n.len:
  167. for i in 0..<p.len - 1:
  168. if not matches(c, p[i], n[i]): return
  169. if p.len == n.len and lastSon(n).kind == nkHiddenStdConv and
  170. lastSon(n)[1].kind == nkBracket:
  171. # unpack varargs:
  172. let n = lastSon(n)[1]
  173. arglist = newNodeI(nkArgList, n.info, n.len)
  174. for i in 0..<n.len: arglist[i] = n[i]
  175. else:
  176. arglist = newNodeI(nkArgList, n.info, n.len - p.len + 1)
  177. # f(1, 2, 3)
  178. # p(X)
  179. for i in 0..n.len - p.len:
  180. arglist[i] = n[i + p.len - 1]
  181. return bindOrCheck(c, v.sym, arglist)
  182. elif p.len-1 == n.len:
  183. for i in 0..<p.len - 1:
  184. if not matches(c, p[i], n[i]): return
  185. arglist = newNodeI(nkArgList, n.info)
  186. return bindOrCheck(c, v.sym, arglist)
  187. if p.len == n.len:
  188. for i in 0..<p.len:
  189. if not matches(c, p[i], n[i]): return
  190. result = true
  191. proc matchStmtList(c: PPatternContext, p, n: PNode): PNode =
  192. proc matchRange(c: PPatternContext, p, n: PNode, i: int): bool =
  193. for j in 0..<p.len:
  194. if not matches(c, p[j], n[i+j]):
  195. # we need to undo any bindings:
  196. c.mapping = @[]
  197. c.mappingIsFull = false
  198. return false
  199. result = true
  200. if p.kind == nkStmtList and n.kind == p.kind and p.len < n.len:
  201. let n = flattenStmts(n)
  202. # no need to flatten 'p' here as that has already been done
  203. for i in 0..n.len - p.len:
  204. if matchRange(c, p, n, i):
  205. c.subMatch = true
  206. result = newNodeI(nkStmtList, n.info, 3)
  207. result[0] = extractRange(nkStmtList, n, 0, i-1)
  208. result[1] = extractRange(nkStmtList, n, i, i+p.len-1)
  209. result[2] = extractRange(nkStmtList, n, i+p.len, n.len-1)
  210. break
  211. elif matches(c, p, n):
  212. result = n
  213. proc aliasAnalysisRequested(params: PNode): bool =
  214. if params.len >= 2:
  215. for i in 1..<params.len:
  216. let param = params[i].sym
  217. if whichAlias(param) != aqNone: return true
  218. proc addToArgList(result, n: PNode) =
  219. if n.typ != nil and n.typ.kind != tyTyped:
  220. if n.kind != nkArgList: result.add(n)
  221. else:
  222. for i in 0..<n.len: result.add(n[i])
  223. proc applyRule*(c: PContext, s: PSym, n: PNode): PNode =
  224. ## returns a tree to semcheck if the rule triggered; nil otherwise
  225. var ctx: TPatternContext
  226. ctx.owner = s
  227. ctx.c = c
  228. ctx.formals = s.typ.len-1
  229. var m = matchStmtList(ctx, s.ast[patternPos], n)
  230. if isNil(m): return nil
  231. # each parameter should have been bound; we simply setup a call and
  232. # let semantic checking deal with the rest :-)
  233. result = newNodeI(nkCall, n.info)
  234. result.add(newSymNode(s, n.info))
  235. let params = s.typ.n
  236. let requiresAA = aliasAnalysisRequested(params)
  237. var args: PNode
  238. if requiresAA:
  239. args = newNodeI(nkArgList, n.info)
  240. for i in 1..<params.len:
  241. let param = params[i].sym
  242. let x = getLazy(ctx, param)
  243. # couldn't bind parameter:
  244. if isNil(x): return nil
  245. result.add(x)
  246. if requiresAA: addToArgList(args, x)
  247. # perform alias analysis here:
  248. if requiresAA:
  249. for i in 1..<params.len:
  250. var rs = result[i]
  251. let param = params[i].sym
  252. case whichAlias(param)
  253. of aqNone: discard
  254. of aqShouldAlias:
  255. # it suffices that it aliases for sure with *some* other param:
  256. var ok = false
  257. for arg in items(args):
  258. if arg != rs and aliases.isPartOf(rs, arg) == arYes:
  259. ok = true
  260. break
  261. # constraint not fulfilled:
  262. if not ok: return nil
  263. of aqNoAlias:
  264. # it MUST not alias with any other param:
  265. var ok = true
  266. for arg in items(args):
  267. if arg != rs and aliases.isPartOf(rs, arg) != arNo:
  268. ok = false
  269. break
  270. # constraint not fulfilled:
  271. if not ok: return nil
  272. markUsed(c, n.info, s)
  273. if ctx.subMatch:
  274. assert m.len == 3
  275. m[1] = result
  276. result = m