#include <bits/stdc++.h>
using namespace std;
const int P = 1000000007;
char str[510];
int n, m, tot;
int f[170][(1 << 16) + 4], g[(1 << 16) + 4], p1[20], p2[20];
inline void add(int &x, int y) {
  x += y;
  if (x >= P) x -= P;
}
inline void dec(int &x, int y) {
  x -= y;
  if (x <= 0) x += P;
}
inline void fwt1(int *a) {
  for (int h = 0; h < 16; h++)
    for (int i = 0; i < (1 << 16); i++)
      if ((i >> h) & 1) add(a[i], a[i ^ (1 << h)]);
}
inline void ufwt1(int *a) {
  for (int h = 0; h < 16; h++)
    for (int i = 0; i < (1 << 16); i++)
      if ((i >> h) & 1) dec(a[i], a[i ^ (1 << h)]);
}
inline void fwt0(int *a) {
  for (int h = 0; h < 16; h++)
    for (int i = 0; i < (1 << 16); i++)
      if (!((i >> h) & 1)) add(a[i], a[i | (1 << h)]);
}
inline void ufwt0(int *a) {
  for (int h = 0; h < 16; h++)
    for (int i = 0; i < (1 << 16); i++)
      if (!((i >> h) & 1)) dec(a[i], a[i | (1 << h)]);
}
int build(int l, int r) {
  int x = ++tot;
  if (l == r) {
    int i, j, S;
    for (j = 0; j < 4; j++) {
      if (str[l] == '?' || str[l] == 'A' + j) {
        for (S = i = 0; i < 16; i++)
          if ((i >> j) & 1) S |= 1 << i;
        f[x][S]++;
      }
      if (str[l] == '?' || str[l] == 'a' + j) {
        for (S = i = 0; i < 16; i++)
          if (!((i >> j) & 1)) S |= 1 << i;
        f[x][S]++;
      }
    }
    return x;
  }
  int i, mid, t = 0;
  for (i = l; i <= r; i++) {
    t += (str[i] == '(') - (str[i] == ')');
    if (!t) break;
  }
  mid = i + 1;
  int ls = build(l + 1, mid - 2), rs = build(mid + 2, r - 1);
  if (str[mid] == '|') {
    fwt1(f[ls]), fwt1(f[rs]);
    for (i = 0; i < (1 << 16); i++) f[x][i] = 1ll * f[ls][i] * f[rs][i] % P;
    ufwt1(f[x]);
  } else if (str[mid] == '&') {
    fwt0(f[ls]), fwt0(f[rs]);
    for (i = 0; i < (1 << 16); i++) f[x][i] = 1ll * f[ls][i] * f[rs][i] % P;
    ufwt0(f[x]);
  } else {
    fwt0(f[ls]), fwt0(f[rs]);
    for (i = 0; i < (1 << 16); i++) g[i] = 1ll * f[ls][i] * f[rs][i] % P;
    ufwt0(g), ufwt0(f[ls]), ufwt0(f[rs]);
    memcpy(f[x], g, sizeof(g));
    fwt1(f[ls]), fwt1(f[rs]);
    for (i = 0; i < (1 << 16); i++) g[i] = 1ll * f[ls][i] * f[rs][i] % P;
    ufwt1(g);
    for (i = 0; i < (1 << 16); i++) add(f[x][i], g[i]);
  }
  return x;
}
int main() {
  scanf("%s%d", str + 1, &m), n = strlen(str + 1);
  int i, j, ans = 0, S = 0, t;
  for (i = 1; i <= m; i++) {
    for (S = j = 0; j < 4; j++) scanf("%d", &t), S |= t << j;
    scanf("%d", &t), p1[i] = S, p2[i] = t;
  }
  build(1, n);
  for (i = 0; i < (1 << 16); i++) {
    for (j = 1; j <= m; j++)
      if (((i >> p1[j]) & 1) != p2[j]) break;
    if (j > m) add(ans, f[1][i]);
  }
  printf("%d", ans);
  return 0;
}
