## vim: filetype=python

def token_match(self, other):
    """
    Helper for the finditer/find/findall methods, so that a token matches
    another token even if they are not strictly equivalent.
    """
    return self == other or self.text == other


@property
def doc_name(n):
    """
    Format this name to be a readable qualified name for the entity designated
    by it. Meant to be used in documentation context.

    If the entity is local, it will return the relative name. If it is
    non-local, return the shortest qualified name not taking use clauses into
    account.

    .. WARNING:: This is an EXPERIMENTAL feature. This is a python specific
        method, because for the moment this is not conveniently implementable
        directly as a libadalang property.  Consider it an experimental API
        endpoint, and use it at your own risk.
    """
    if n.p_is_defining and not n.is_a(DefiningName):
        n = n.p_enclosing_defining_name

    ref_decl = n.p_basic_decl if n.p_is_defining else n.p_referenced_decl()
    ref_decl_fqn = ref_decl.p_fully_qualified_name

    enclosing_package = next(
        (p for p in n.parents() if p.is_a(BasePackageDecl)),
        None
    )

    if enclosing_package is None or enclosing_package == ref_decl:
        return ref_decl_fqn

    enclosing_decl_fqn = enclosing_package.p_fully_qualified_name

    if ref_decl_fqn.lower().startswith(enclosing_decl_fqn.lower()):
        return ref_decl_fqn[len(enclosing_decl_fqn):].strip(".")
    else:
        return ref_decl_fqn

Token.match = token_match
Name.doc_name = doc_name
