def CheckValidSumAverageArgument(stack):
  top = stack.pop()
  if ((isinstance(top, util.OperatorToken) and top.num_args == 1) or
      isinstance(top, util.BuiltInFunctionToken) or
      isinstance(top, util.AggregationFunctionToken) or
      isinstance(top, util.LiteralToken)):
    raise bigquery_client.BigqueryInvalidQueryError(
        'Invalid SUM arguments. %s is not supported' %top, None, None, None)
  elif top in ['+', '-']:
    op2 = CheckValidSumAverageArgument(stack)
    op1 = CheckValidSumAverageArgument(stack)
    list_fields = list(op1[0])
    if top == '-':
      for i in range(len(op2[0])):
        op2[0][i].extend([-1, util.OperatorToken('*', 2)])
    for i in range(len(op2[0])):
      list_fields.append(op2[0][i])
    return [list_fields, op1[1] or op2[1], op1[2] or op2[2]]
  elif top == '*':
    op2 = CheckValidSumAverageArgument(stack)
    op1 = CheckValidSumAverageArgument(stack)
    if (op1[1] and (op2[1] or op2[2])) or (op2[1] and (op1[1] or op1[2])):
      raise bigquery_client.BigqueryInvalidQueryError(
          'Invalid AVG/SUM argument. An encrypted field is multipled by another'
          ' field.', None, None, None)
    list_fields = []
    for field1 in op1[0]:
      for field2 in op2[0]:
        value = list(field1)
        value.extend(field2)
        value.append(util.OperatorToken('*', 2))
        list_fields.append(value)
    return [list_fields, op1[1] or op2[1], op1[2] or op2[2]]
  elif top == '/':
    op2 = CheckValidSumAverageArgument(stack)
    op1 = CheckValidSumAverageArgument(stack)
    if op2[1] or (op1[1] and op2[2]):
      raise bigquery_client.BigqueryInvalidQueryError(
          'Division by/of an encrypted field: not a linear function.', None,
          None, None)
    append_divisor = []
    for field in op2[0]:
      append_divisor.extend(field)
    for i in range(len(op2[0]) - 1):
      append_divisor.append(util.OperatorToken('+', 2))
    append_divisor.append(util.OperatorToken('/', 2))
    list_fields = list(op1[0])
    for i in xrange(len(list_fields)):
      list_fields[i].extend(append_divisor)
    return [list_fields, op1[1], op1[2] or op2[2]]
  else:
    if (isinstance(top, util.PseudonymToken) or
        isinstance(top, util.SearchwordsToken) or
        isinstance(top, util.ProbabilisticToken)):
      raise bigquery_client.BigqueryInvalidQueryError(
          'Cannot do SUM/AVG on non-homomorphic encryption.', None, None, None)
    is_encrypted = (
        isinstance(top, util.HomomorphicIntToken) or
        isinstance(top, util.HomomorphicFloatToken))
    return [[[top]], is_encrypted, not util.IsFloat(top)]
Checks if stack is a proper argument for SUM/AVG.
dataset/ETHPy150Open google/encrypted-bigquery-client/src/query_interpreter.py/CheckValidSumAverageArgument