# ====- HeaderFile Class for libc function headers  -----------*- python -*--==#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# ==-------------------------------------------------------------------------==#

import re
from functools import reduce
from pathlib import PurePosixPath


STDINT_SIZES = [
    "16",
    "32",
    "64",
    "8",
    "least16",
    "least32",
    "least64",
    "least8",
    "max",
    "ptr",
]

COMPILER_HEADER_TYPES = {
    "bool": "<stdbool.h>",
    "va_list": "<stdarg.h>",
}
COMPILER_HEADER_TYPES.update({f"int{size}_t": "<stdint.h>" for size in STDINT_SIZES})
COMPILER_HEADER_TYPES.update({f"uint{size}_t": "<stdint.h>" for size in STDINT_SIZES})

NONIDENTIFIER = re.compile("[^a-zA-Z0-9_]+")

COMMON_HEADER = PurePosixPath("__llvm-libc-common.h")

# These "attributes" are known macros defined in COMMON_HEADER.
# Others are found in "llvm-libc-macros/{name}.h".
COMMON_ATTRIBUTES = {
    "_Noreturn",
    "_Returns_twice",
}

# All the canonical identifiers are in lowercase for easy maintenance.
# This maps them to the pretty descriptions to generate in header comments.
LIBRARY_DESCRIPTIONS = {
    "stdc": "Standard C",
    "posix": "POSIX",
    "bsd": "BSD",
    "gnu": "GNU",
    "linux": "Linux",
    "uefi": "UEFI",
    "svid": "SVID",
    "stdc_ext": "Standard C Extension",
    "llvm_libc_ext": "LLVM libc Extension",
    "llvm_libc_stdfix_ext": "LLVM libc stdfix Extension",
}

HEADER_TEMPLATE = """\
//===-- {library} header <{header}> --===//
//
{license_lines}
//
//===---------------------------------------------------------------------===//

#ifndef {guard}
#define {guard}

%%public_api()

#endif // {guard}
"""

LLVM_LICENSE_TEXT = [
    "Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.",
    "See https://llvm.org/LICENSE.txt for license information.",
    "SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception",
]

PROXY_TEMPLATE = """\
//===-- Implementation proxy header for <{header}> --===//
//
{license_lines}
//
//===---------------------------------------------------------------------===//

#ifndef {guard}
#define {guard}

#ifdef LIBC_FULL_BUILD

{include_lines}
{macro_lines}

#else // Overlay mode

#include <{header}>

#endif // LLVM_LIBC_FULL_BUILD

#endif // {guard}
"""


class HeaderFile:
    def __init__(self, name):
        self.template_file = None
        self.name = name
        self.macros = []
        self.types = []
        self.enumerations = []
        self.objects = []
        self.functions = []
        self.extra_standards = {}
        self.standards = []
        self.merge_yaml_files = []
        self.license_text = []
        self.public_includes = []

    def add_macro(self, macro):
        self.macros.append(macro)

    def add_type(self, type_):
        self.types.append(type_)

    def add_enumeration(self, enumeration):
        self.enumerations.append(enumeration)

    def add_object(self, object):
        self.objects.append(object)

    def add_function(self, function):
        self.functions.append(function)

    def merge(self, other):
        self.macros = sorted(set(self.macros) | set(other.macros))
        self.types = sorted(set(self.types) | set(other.types))
        self.enumerations = sorted(set(self.enumerations) | set(other.enumerations))
        self.objects = sorted(set(self.objects) | set(other.objects))
        self.functions = sorted(set(self.functions) | set(other.functions))
        self.extra_standards |= other.extra_standards
        self.public_includes = sorted(
            set(self.public_includes) | set(other.public_includes)
        )
        if self.license_text:
            assert not other.license_text, "only one `license_text` allowed"
        else:
            self.license_text = other.license_text

    def all_types(self):
        return reduce(
            lambda a, b: a | b,
            [f.signature_types() for f in self.functions],
            set(self.types),
        )

    def all_attributes(self):
        return reduce(
            lambda a, b: a | b,
            [set(f.attributes) for f in self.functions],
            set(),
        )

    def all_standards(self):
        standards = set(self.standards)
        for collection in [
            self.macros,
            self.types,
            self.enumerations,
            self.objects,
            self.functions,
        ]:
            for item in collection:
                if item.standards:
                    standards.update(item.standards)
        descriptions = LIBRARY_DESCRIPTIONS | self.extra_standards
        for standard in standards:
            if standard not in descriptions:
                # Provide a helpful error message with acceptable values.
                expected = ", ".join(sorted(descriptions.keys()))
                raise ValueError(
                    f"Standard '{standard}' is not one of the canonical "
                    f"identifiers: {expected}"
                )
        return standards

    def includes(self):
        return (
            {f"<{inc}>" for inc in self.public_includes}
            | {
                PurePosixPath("llvm-libc-macros") / macro.header
                for macro in self.macros
                if macro.header is not None
            }
            | {
                COMPILER_HEADER_TYPES.get(
                    typ.name,
                    PurePosixPath("llvm-libc-types") / f"{typ.name}.h",
                )
                for typ in self.all_types()
                if typ.guard is None
            }
            | {
                PurePosixPath("llvm-libc-macros") / f"{attr.split('(')[0]}.h"
                for attr in self.all_attributes() - COMMON_ATTRIBUTES
            }
        )

    def header_guard(self, proxy=False):
        words = [word.upper() for word in NONIDENTIFIER.split(self.name) if word]
        if proxy:
            return "LLVM_LIBC_HDR_" + "_".join(words[:-1]) + "_PROXY_H"
        return "_LLVM_LIBC_" + "_".join(words)

    def library_description(self):
        # This also validates all standards.
        standards = self.all_standards()
        descriptions = LIBRARY_DESCRIPTIONS | self.extra_standards
        # If the header itself is in standard C, just call it that.
        if "stdc" in self.standards:
            return descriptions["stdc"]
        # If the header itself is in POSIX, just call it that.
        if "posix" in self.standards:
            return descriptions["posix"]
        # Otherwise, consider the standards for each symbol as well.
        # Otherwise, it's described by all those that apply, but ignoring
        # "stdc" and "posix" since this is not a "stdc" or "posix" header.
        return " / ".join(
            sorted(
                descriptions[standard]
                for standard in standards
                if standard not in {"stdc", "posix"}
            )
        )

    def license_lines(self):
        lines = self.license_text or LLVM_LICENSE_TEXT
        return "\n".join([f"// {line}" for line in lines])

    def template(self, dir, files_read):
        if self.template_file is not None:
            # There's a custom template file, so just read it in and record
            # that it was read as an input file.
            template_path = dir / self.template_file
            files_read.add(template_path)
            return template_path.read_text()

        # Generate the default template.
        return HEADER_TEMPLATE.format(
            library=self.library_description(),
            header=self.name,
            guard=self.header_guard(),
            license_lines=self.license_lines(),
        )

    def include_lines(self, with_common=False):
        # Python 3.12 has .relative_to(dir, walk_up=True) for this.
        path_prefix = PurePosixPath("../" * (len(PurePosixPath(self.name).parents) - 1))

        def relpath(file):
            return path_prefix / file

        # This always goes before all the other includes, which are sorted.
        # It's implicitly emitted here when using the default template so
        # it can get the right relative path.  Custom template files should
        # all have it explicitly with their right particular relative path.
        content = [
            f"#include {file}"
            for file in ([f'"{relpath(COMMON_HEADER)!s}"'] if with_common else [])
            + sorted(
                file if isinstance(file, str) else f'"{relpath(file)!s}"'
                for file in self.includes()
            )
        ]

        # Add guarded types
        current_guard = None
        has_seen_guard = False
        for typ in sorted(self.types):
            if typ.guard is None:
                continue
            if not has_seen_guard:
                has_seen_guard = True
                content.append("")
            path = COMPILER_HEADER_TYPES.get(
                typ.name,
                PurePosixPath("llvm-libc-types") / f"{typ.name}.h",
            )
            self.emit_guard(content, current_guard, typ.guard)
            current_guard = typ.guard
            content.append(f'#include "{relpath(path)!s}"')
        self.emit_guard(content, current_guard, None)

        return content

    def macro_lines(self):
        content = []
        for macro in sorted(self.macros):
            # When there is nothing to define, the Macro object converts to str
            # as an empty string.  Don't emit a blank line for those cases.
            if str(macro):
                content.extend(["", f"{macro}"])
        return content

    def enum_lines(self):
        content = []
        if self.enumerations:
            combined_enum_content = ",\n  ".join(
                str(enum) for enum in self.enumerations
            )
            content.append(f"\nenum {{\n  {combined_enum_content},\n}};")
        return content

    def proxy_contents(self):
        return PROXY_TEMPLATE.format(
            header=self.name,
            guard=self.header_guard(proxy=True),
            license_lines=self.license_lines(),
            include_lines="\n".join(self.include_lines()),
            macro_lines="\n".join(self.macro_lines()),
        )

    def public_api(self):
        content = (
            self.include_lines(self.template_file is None)
            + self.macro_lines()
            + self.enum_lines()
        )
        content.append("")
        has_decls = self.functions or self.objects
        if has_decls:
            content.append("__BEGIN_C_DECLS")
            content.append("")

        # Emit function declarations.
        current_guard = None
        last_name = None
        for function in sorted(self.functions):
            # If the last function's name was the same after underscores,
            # elide the blank line between the declarations.
            if last_name == function.name_without_underscores():
                content.pop()
            self.emit_guard(content, current_guard, function.guard)
            current_guard = function.guard
            content.append(str(function) + " __NOEXCEPT;")
            content.append("")
            last_name = function.name_without_underscores()
        self.emit_guard(content, current_guard, None)

        # Emit object declarations.
        content.extend(str(object) for object in self.objects)
        if self.objects:
            content.append("")

        if has_decls:
            content.append("__END_C_DECLS")

        return "\n".join(content)

    def json_data(self):
        return {
            "name": self.name,
            "standards": self.standards,
            "includes": sorted(str(file) for file in {COMMON_HEADER} | self.includes()),
        }

    def validate(self):
        self.all_standards()

    def emit_guard(self, content, current_guard, new_guard):
        if current_guard != new_guard:
            if current_guard is not None:
                if content[-1] == "":
                    content.pop()
                content.append(f"#endif // {current_guard}")
                content.append("")
            if new_guard is not None:
                content.append(f"#ifdef {new_guard}")
