def _resolve_reference(item, example):
  """Resolves an ambiguous token that matches multiple annotations.

  Args:
    item: position in the SQL parse where the search will start.
    example: the QuikExample containing table and column annotations.

  Raises:
    ParseError: if the ambiguity cannot be resolved.
  """
  prev_symbol = example.gold_sql_query.actions[
      len(example.gold_sql_query.actions) - 1].symbol

  if prev_symbol in ('join', 'from'):
    table_annotation = _find_table_annotation(item, example)
    assert table_annotation, ('Cannot find a table annotation for item %s' %
                              item.value)

    example.gold_sql_query.actions.append(
        SQLAction(entity_copy=SchemaEntityCopy(copied_table=table_annotation)))
    return

  parent = item.parent

  # We try the simple case, that is aliases
  parent_tokens = _get_tokens(parent)
  if _is_table_alias(parent_tokens[0]) and parent_tokens[1].value == '.':
    aliases = _get_all_aliases(item, example)

    table_annotation = aliases[parent.tokens[0].value.lower()]
    found_column = _find_column_entities(item.value, example, table_annotation)

    assert found_column, 'Could not find column with name ' + str(item.value)
    example.gold_sql_query.actions.append(
        SQLAction(entity_copy=SchemaEntityCopy(copied_column=found_column)))
    return

  def _find_direction(reverse):
    """Finds a column annotation in a given direction."""
    table_entities = _find_from_table(item, example, reverse=reverse)

    if not table_entities:
      return False

    for table_entity in table_entities:
      entity = _find_column_entities(item.value, example, table_entity)

      if entity:
        example.gold_sql_query.actions.append(
            SQLAction(entity_copy=SchemaEntityCopy(copied_column=entity)))
        return True

    raise ParseError('Unable to find annotation of table ' + str(item))

  if (prev_symbol in ('where', 'by') or _is_where(parent) or
      _is_where(parent.parent)):
    if _find_direction(reverse=True):
      return

  if _find_direction(reverse=False):
    return

  if _find_direction(reverse=True):
    return

  raise ParseError('Unable to find final annotation in any direction')
Resolves an ambiguous token that matches multiple annotations.

  Args:
    item: position in the SQL parse where the search will start.
    example: the QuikExample containing table and column annotations.

  Raises:
    ParseError: if the ambiguity cannot be resolved.
  
language/xsp/data_preprocessing/sql_parsing.py