Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / tools / gen_aria_roles / emit_aria_roles.lucb

#==============================================================================================
#
#   emit_aria_roles - the AriaRoles.cpp half of generate_libweb_aria_roles.py
#
#   DESCRIPTION:
#       write_implementation_file and generate_hash_table_member of the Python generator, in
#       its order: for each role of AriaRoles.json, the eight hash table members, the two
#       constructors, accessible_name_required, children_are_presentational,
#       default_value_for_property_or_state and (when the role has one) name_from_source.
#
#       Where C++ and Luce differ:
#         - a C++ function-local `static HashTable<...>` is a module variable of the fragment,
#           filled on first use by aria_role_type_fill_static_table (role_type.lucb), which
#           makes it in the C heap (DESIGN.md ยง3.3 rule 7);
#         - a constructor runs its bases' constructors (the first base takes the data, the
#           others are default-constructed, as in C++) and then installs the class's vtable
#           in its RoleType and in each RoleType of a further base along the first-base chain
#           (the C++ vptrs), with aria_role_type_set_class;
#         - an implicit value of AriaRoles.json is a C++ expression (`true`, `100.0`,
#           `AriaLive::Polite`); it becomes the matching case of AriaDefaultValueType.
#
#==============================================================================================

# mark: Names ===================================================================================

## Ported from generate_libweb_aria_roles.py ARIA_NAME_TO_ENUM: the StateAndProperties
## enumerator of an `aria-*` attribute name.
let aria_names: str[53] = ["aria-activedescendant", "aria-atomic", "aria-autocomplete", "aria-braillelabel",
                           "aria-brailleroledescription", "aria-busy", "aria-checked", "aria-colcount", "aria-colindex",
                           "aria-colindextext", "aria-colspan", "aria-controls", "aria-current", "aria-describedby",
                           "aria-description", "aria-details", "aria-disabled", "aria-dropeffect", "aria-errormessage",
                           "aria-expanded", "aria-flowto", "aria-grabbed", "aria-haspopup", "aria-hidden", "aria-invalid",
                           "aria-keyshortcuts", "aria-label", "aria-labelledby", "aria-level", "aria-live", "aria-modal",
                           "aria-multiline", "aria-multiselectable", "aria-orientation", "aria-owns", "aria-placeholder",
                           "aria-posinset", "aria-pressed", "aria-readonly", "aria-relevant", "aria-required",
                           "aria-roledescription", "aria-rowcount", "aria-rowindex", "aria-rowindextext", "aria-rowspan",
                           "aria-selected", "aria-setsize", "aria-sort", "aria-valuemax", "aria-valuemin", "aria-valuenow",
                           "aria-valuetext"]
let aria_enum_names: str[53] = ["AriaActiveDescendant", "AriaAtomic", "AriaAutoComplete", "AriaBrailleLabel",
                                "AriaBrailleRoleDescription", "AriaBusy", "AriaChecked", "AriaColCount", "AriaColIndex",
                                "AriaColIndexText", "AriaColSpan", "AriaControls", "AriaCurrent", "AriaDescribedBy",
                                "AriaDescription", "AriaDetails", "AriaDisabled", "AriaDropEffect", "AriaErrorMessage",
                                "AriaExpanded", "AriaFlowTo", "AriaGrabbed", "AriaHasPopup", "AriaHidden", "AriaInvalid",
                                "AriaKeyShortcuts", "AriaLabel", "AriaLabelledBy", "AriaLevel", "AriaLive", "AriaModal",
                                "AriaMultiLine", "AriaMultiSelectable", "AriaOrientation", "AriaOwns", "AriaPlaceholder",
                                "AriaPosInSet", "AriaPressed", "AriaReadOnly", "AriaRelevant", "AriaRequired",
                                "AriaRoleDescription", "AriaRowCount", "AriaRowIndex", "AriaRowIndexText", "AriaRowSpan",
                                "AriaSelected", "AriaSetSize", "AriaSort", "AriaValueMax", "AriaValueMin", "AriaValueNow",
                                "AriaValueText"]

## Ported from generate_libweb_aria_roles.py aria_name_to_enum_name, answering the Luce case
## of the enumerator (`aria-activedescendant` is `aria_active_descendant`).
func aria_name_to_enum_case(name: str) -> str!:
    for index in 0..<aria_names.length:
        if aria_names[index] == name:
            return try luce_case(aria_enum_names[index])
    trap(f"no StateAndProperties enumerator for {name}")

## The Luce function prefix of the role class `name` (`AlertDialog` is `aria_alert_dialog`).
func role_function_prefix(name: str) -> str!:
    return try cat(["aria_", try luce_snake(name)])

## The member `key` of a role's JSON object.
func role_member(value: const Json*, key: str) -> Json*:
    return value.get(key) else trap(f"a role without {key}")

## The super class roles of `name`, or none for RoleType (which AriaRoles.json does not describe).
func super_class_roles(roles_data: const Json*, name: str) -> Json*?:
    let value = roles_data.get(name) else return none
    return role_member(value, "superClassRoles")

# mark: The vtables of a class ==================================================================

## A RoleType subobject of a class other than its own: the field path from the class to the
## base whose RoleType it is, and that base's name.
struct MixinBase:
    var path: str
    var name: str

## The bases of `name` beyond the first, and those of the bases along its first-base chain,
## with their field paths (the skeleton generator's "mixin" vtables of the class).
func mixin_bases(roles_data: const Json*, name: str, result: MixinBaseList*) -> !:
    let bases = super_class_roles(roles_data, name) else return
    let primary = bases.at(0).string()
    var inherited = try MixinBaseList.create()
    try mixin_bases(roles_data, primary, &inherited)
    for index in 0..<inherited.count:
        let base = inherited.items[index]
        try result.append(MixinBase(path = try cat([try luce_snake(primary), ".", base.path]), name = base.name))
    for index in 1..<bases.count:
        let base = bases.at(index).string()
        try result.append(MixinBase(path = try luce_snake(base), name = base))

## A growable list of MixinBase.
struct MixinBaseList:
    var items: MixinBase[]
    var count: usize

    static func create() -> MixinBaseList!:
        return MixinBaseList(items = try new MixinBase[8], count = 0)

    func append(value: MixinBase) -> !:
        if self.count == self.items.length:
            let grown = try new MixinBase[self.items.length * 2]
            for index in 0..<self.count:
                grown[index] = self.items[index]
            self.items = grown
        self.items[self.count] = value
        self.count += 1

# mark: Members =================================================================================

## Ported from generate_libweb_aria_roles.py generate_hash_table_member: `member_name` of
## the class `name` answers its static `HashTable<enum_class>`, filled with `values` (Luce
## cases) on first use.
func generate_hash_table_member(out: Out*, name: str, member_name: str, hash_table_name: str, enum_class: str, values: const StrList*) -> !:
    let prefix = try role_function_prefix(name)
    let luce_enum = try cat(["Aria", enum_class])
    let table_type = try cat(["ak.HashTable[", luce_enum, ", ", luce_enum, "Traits]"])
    let table = try cat([prefix, "_", member_name, "_table"])
    try out.blank()
    try out.line(f"# static HashTable<{enum_class}> {hash_table_name};")
    try out.line(f"var {table}: {table_type}")
    try out.blank()
    try out.line(f"## Ported from Build/Libraries/LibWeb/ARIA/AriaRoles.cpp Web::ARIA::{name}::{member_name} (override).")
    try out.line(f"pub func {prefix}_{member_name}_impl(base: AriaRoleType*) -> {table_type}:")
    if values.count == 0:
        try out.line(f"    return {table}")
        return
    try out.line(f"    let {hash_table_name} = &{table}")
    try out.line(f"    if ak.hash_table_is_empty({hash_table_name}):")
    # One value per line: `ensure_capacity(n)` and the `set` calls of the C++.
    try out.line(f"        aria_role_type_fill_static_table({hash_table_name}, [")
    for index in 0..<values.count:
        try out.line(f"            {luce_enum}.{values.at(index)},")
    try out.line("        ], ensure_capacity = true)")
    try out.line(f"    return *{hash_table_name}")

## The Luce cases of the `aria-*` names of the JSON array `names`
## (translate_aria_names_to_enum).
func translate_aria_names_to_enum(names: const Json*) -> StrList!:
    var result = try StrList.create()
    for index in 0..<names.count:
        try result.append(try aria_name_to_enum_case(names.at(index).string()))
    return result

## The Luce cases of the role names of the JSON array `roles`.
func translate_roles(roles: const Json*) -> StrList!:
    var result = try StrList.create()
    for index in 0..<roles.count:
        try result.append(try luce_safe(roles.at(index).string()))
    return result

## A constructor of `name`: its first base takes `first_base_argument` (`data` or nothing), the
## other bases are default-constructed, then the class's vtables are installed.
func emit_constructor(out: Out*, roles_data: const Json*, name: str, with_data: bool) -> !:
    let prefix = try role_function_prefix(name)
    let bases = super_class_roles(roles_data, name) else trap("a role without super class roles")
    if with_data:
        try out.line(f"## Ported from Build/Libraries/LibWeb/ARIA/AriaRoles.cpp Web::ARIA::{name}::{name}(AriaData const&).")
        try out.line(f"pub func {prefix}_construct_aria_data(this: Aria{name}*, data: AriaData):")
    else:
        try out.line(f"## Ported from Build/Libraries/LibWeb/ARIA/AriaRoles.cpp Web::ARIA::{name}::{name}().")
        try out.line(f"pub func {prefix}_construct(this: Aria{name}*):")
    for index in 0..<bases.count:
        let base = bases.at(index).string()
        let field = try luce_snake(base)
        if index == 0 and with_data:
            try out.line(f"    {try role_function_prefix(base)}_construct_aria_data(&this.{field}, data)")
        else:
            try out.line(f"    {try role_function_prefix(base)}_construct(&this.{field})")
    try out.line(f"    aria_role_type_set_class(this.aria_role_type(), (const AriaRoleTypeVTable*)&{prefix}_vtable, &{prefix}_class)")
    var mixins = try MixinBaseList.create()
    try mixin_bases(roles_data, name, &mixins)
    for index in 0..<mixins.count:
        let mixin = mixins.items[index]
        let vtable = try cat([prefix, "_", try luce_snake(mixin.name), "_vtable"])
        try out.line(f"    aria_role_type_set_class(this.{mixin.path}.aria_role_type(), (const AriaRoleTypeVTable*)&{vtable}, &{prefix}_class)")

## An implicit value of AriaRoles.json (a C++ expression of DefaultValueType) as Luce.
func implicit_value(text: str) -> str!:
    if text == "true" or text == "false":
        return try cat(["AriaDefaultValueType.bool_(", text, ")"])
    if text.length > 0 and (is_digit(text.bytes[0]) or text.bytes[0] == '-'):
        return try cat(["AriaDefaultValueType.f64_(", text, ")"])
    # `Type::Enumerator`.
    for index in 0..<text.length - 1:
        if text.bytes[index] == ':' and text.bytes[index + 1] == ':':
            let type_name = slice(text, 0, index)
            let enumerator = slice(text, index + 2, text.length)
            return try cat(["AriaDefaultValueType.", try luce_snake(type_name), "(", type_name, ".", try luce_case(enumerator), ")"])
    trap(f"an implicit value that is no DefaultValueType: {text}")

# mark: The implementation file =================================================================

## `// {description}` of the header: a description of several lines continues with lines that are
## already `//` comments, which become `#` comments.
func put_comment(out: Out*, text: str) -> !:
    var start: usize = 0
    var first = true
    for index in 0..<text.length + 1:
        if index < text.length and text.bytes[index] != '\n':
            continue
        let line = slice(text, start, index)
        if first:
            try out.line(f"# {line}")
        elif line.length >= 2 and line.bytes[0] == '/' and line.bytes[1] == '/':
            try out.line(f"#{slice(line, 2, line.length)}")
        else:
            try out.line(f"# {line}")
        first = false
        start = index + 1

## Ported from generate_libweb_aria_roles.py write_implementation_file.
func emit_aria_roles(roles_data: const Json*) -> str!:
    var out = try Out.create()
    try put_header(&out, "aria_roles", "the ARIA role classes' constructors and RoleType overrides", [
        "Generated by tools/gen_aria_roles from data/aria/AriaRoles.json; do not edit.",
        "The C++ it stands for, at Ladybird 47c82b38d0, is Build/Libraries/LibWeb/ARIA/AriaRoles.cpp,",
        "written by Meta/Generators/generate_libweb_aria_roles.py; the classes themselves",
        "(AriaRoles.h) are generated/aria/types_aria_roles.lucb.",
        "",
        "Copyright (c) 2023, Jonah Shafran <jonahshafran@gmail.com>",
        "Copyright (c) 2026-present, the Ladybird developers.",
        "Copyright (c) 2026 the luce-browser authors.",
        "SPDX-License-Identifier: BSD-2-Clause (see data/aria/LICENSE)",
    ])

    for role_index in 0..<roles_data.count:
        let name = roles_data.key(role_index)
        let value = roles_data.at(role_index)
        let prefix = try role_function_prefix(name)
        try put_mark(&out, name)
        try out.line(f"# {role_member(value, "specLink").string()}")
        try put_comment(&out, role_member(value, "description").string())

        let supported_states = try translate_aria_names_to_enum(role_member(value, "supportedStates"))
        try generate_hash_table_member(&out, name, "supported_states", "states", "StateAndProperties", &supported_states)
        let supported_properties = try translate_aria_names_to_enum(role_member(value, "supportedProperties"))
        try generate_hash_table_member(&out, name, "supported_properties", "properties", "StateAndProperties", &supported_properties)

        let required_states = try translate_aria_names_to_enum(role_member(value, "requiredStates"))
        try generate_hash_table_member(&out, name, "required_states", "states", "StateAndProperties", &required_states)
        let required_properties = try translate_aria_names_to_enum(role_member(value, "requiredProperties"))
        try generate_hash_table_member(&out, name, "required_properties", "properties", "StateAndProperties", &required_properties)

        let prohibited_states = try translate_aria_names_to_enum(role_member(value, "prohibitedStates"))
        try generate_hash_table_member(&out, name, "prohibited_states", "states", "StateAndProperties", &prohibited_states)
        let prohibited_properties = try translate_aria_names_to_enum(role_member(value, "prohibitedProperties"))
        try generate_hash_table_member(&out, name, "prohibited_properties", "properties", "StateAndProperties", &prohibited_properties)

        let required_context_roles = try translate_roles(role_member(value, "requiredContextRoles"))
        try generate_hash_table_member(&out, name, "required_context_roles", "roles", "Role", &required_context_roles)
        let required_owned_elements = try translate_roles(role_member(value, "requiredOwnedElements"))
        try generate_hash_table_member(&out, name, "required_owned_elements", "roles", "Role", &required_owned_elements)

        let accessible_name_required = "true" if role_member(value, "accessibleNameRequired").boolean() else "false"
        let children_are_presentational = "true" if role_member(value, "childrenArePresentational").boolean() else "false"

        try out.blank()
        try emit_constructor(&out, roles_data, name, false)
        try out.blank()
        try emit_constructor(&out, roles_data, name, true)
        try out.blank()
        try out.line(f"## Ported from Build/Libraries/LibWeb/ARIA/AriaRoles.cpp Web::ARIA::{name}::accessible_name_required (override).")
        try out.line(f"pub func {prefix}_accessible_name_required_impl(base: AriaRoleType*) -> bool:")
        try out.line(f"    return {accessible_name_required}")
        try out.blank()
        try out.line(f"## Ported from Build/Libraries/LibWeb/ARIA/AriaRoles.cpp Web::ARIA::{name}::children_are_presentational (override).")
        try out.line(f"pub func {prefix}_children_are_presentational_impl(base: AriaRoleType*) -> bool:")
        try out.line(f"    return {children_are_presentational}")

        let implicit_value_for_role = role_member(value, "implicitValueForRole")
        try out.blank()
        try out.line(f"## Ported from Build/Libraries/LibWeb/ARIA/AriaRoles.cpp Web::ARIA::{name}::default_value_for_property_or_state (override).")
        if implicit_value_for_role.count == 0:
            try out.line(f"pub func {prefix}_default_value_for_property_or_state_impl(base: AriaRoleType*, arg0: AriaStateAndProperties) -> AriaDefaultValueType:")
            try out.line("    return AriaDefaultValueType.empty")
        else:
            try out.line(f"pub func {prefix}_default_value_for_property_or_state_impl(base: AriaRoleType*, state_or_property: AriaStateAndProperties) -> AriaDefaultValueType:")
            try out.line("    match state_or_property:")
            for index in 0..<implicit_value_for_role.count:
                let state_name = implicit_value_for_role.key(index)
                let implicit = implicit_value_for_role.at(index).string()
                try out.line(f"        .{try aria_name_to_enum_case(state_name)}:")
                try out.line(f"            return {try implicit_value(implicit)}")
            try out.line("        _:")
            try out.line("            return AriaDefaultValueType.empty")

        if let name_from_source = value.get("nameFromSource"):
            if name_from_source.kind != JsonKind.null_:
                try out.blank()
                try out.line(f"## Ported from Build/Libraries/LibWeb/ARIA/AriaRoles.cpp Web::ARIA::{name}::name_from_source (override).")
                try out.line(f"pub func {prefix}_name_from_source_impl(base: AriaRoleType*) -> AriaNameFromSource:")
                try out.line(f"    return AriaNameFromSource.{try luce_case(name_from_source.string())}")
    return out.text()