patterns.nim 10 KB

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