// snlMatch2 keeps existing matches and restores matches on false

static boolean snlMatch2(S pat, S snl, SNLMatches matches) {
  ret snlMatch2(snlToTree_cached(pat), snlToTree(snl), matches);
}

static boolean snlMatch2(Lisp pat, S snl, SNLMatches matches) {
  ret snlMatch2(pat, snlToTree(snl), matches);
}

static boolean snlMatch2(S pat, Lisp snl, SNLMatches matches) {
  ret snlMatch2(snlToTree_cached(pat), snl, matches);
}

static boolean snlMatch2(Lisp pat, Lisp snl, SNLMatches matches) {
  int level = matches.save();
  if (snlMatch2_sub(pat, snl, matches))
    ret true;
  matches.restore(level);
  ret false;
}

static boolean snlMatch2_sub(Lisp pat, Lisp snl, SNLMatches m) {
  if (pat == null || snl == null) ret false;
  if (pat.isA("*"))
    ret true;
  if (startsWithUpperCase(pat.head))
    ret snlMatch2_putMatch(m, pat.head, snl);
    
  if (neq(pat.head, snl.head)) ret false;
  
  // heads identical, proceed to children
  int n = pat.size();
  if (n != snl.size()) ret false;
  
  for (int i = 0; i < n; i++)
    if (!snlMatch2_sub(pat.get(i), snl.get(i), m))
      ret false;
      
  ret true;
}

static boolean snlMatch2_putMatch(SNLMatches matches, S key, Lisp val) {
  ret matches.put(key, val);
}