#!/usr/bin/env python3 """Generates the style refinement types and the `Styled` fluent API. GPUI produces this code with Rust macros: `#[derive(Refineable)]` (crates/refineable) and `gpui_macros::style_helpers!` plus the `*_style_methods!` macros (crates/gpui_macros/src/styles.rs). MoonBit has no macros, so this script emits the equivalent MoonBit source. The output is committed; rerun after changing this script or `src/style/styled.mbt`: python3 tools/gen_style.py && moon fmt Outputs (all in src/style/): style_generated.mbt Style, StyleRefinement, TextStyle, TextStyleRefinement and their refine methods styled_generated.mbt the `Styled` trait and generated helpers styled_extend_generated.mbt promotes all `Styled` methods on StyleRefinement Other packages that implement `Styled` (e.g. `Div`) need the same `extend` list; pass `--extend Type=path/to/file.mbt` to emit it there. """ import argparse import os import re import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STYLE_DIR = os.path.join(ROOT, "src", "style") HANDWRITTEN = os.path.join(STYLE_DIR, "styled.mbt") HEADER = ( "// GENERATED by tools/gen_style.py. DO NOT EDIT.\n" "// Port of GPUI's derive(Refineable) / gpui_macros style helpers.\n\n" ) G = "@geometry" # --------------------------------------------------------------------------- # Refineable structs # # kind: # "plain" field T, refinement T? (set when Some) # "option" field T?, refinement T? (set when Some) # ("nested", RefinementType) refined recursively with `.refined(...)` # --------------------------------------------------------------------------- STYLE_FIELDS = [ ("display", "Display", "plain", "How the element is laid out (block, flex, grid, none)."), ("visibility", "Visibility", "plain", "Whether the element is painted."), ("overflow", "@geometry.Point[Overflow]", ("nested", "@geometry.PointRefinement[Overflow]"), "Overflow behavior per axis."), ("scrollbar_width", "@geometry.AbsoluteLength", "plain", "Space reserved for scrollbars."), ("allow_concurrent_scroll", "Bool", "plain", "Whether both axes may scroll at once."), ("restrict_scroll_to_axis", "Bool", "plain", "Whether scrolling is restricted to the dominant axis."), ("position", "Position", "plain", "Relative or absolute positioning."), ("inset", "@geometry.Edges[@geometry.Length]", ("nested", "@geometry.EdgesRefinement[@geometry.Length]"), "Offsets for positioned elements."), ("size", "@geometry.Size[@geometry.Length]", ("nested", "@geometry.SizeRefinement[@geometry.Length]"), "Preferred size."), ("min_size", "@geometry.Size[@geometry.Length]", ("nested", "@geometry.SizeRefinement[@geometry.Length]"), "Minimum size."), ("max_size", "@geometry.Size[@geometry.Length]", ("nested", "@geometry.SizeRefinement[@geometry.Length]"), "Maximum size."), ("aspect_ratio", "Double?", "option", "Preferred width / height ratio."), ("margin", "@geometry.Edges[@geometry.Length]", ("nested", "@geometry.EdgesRefinement[@geometry.Length]"), "Outer spacing."), ("padding", "@geometry.Edges[@geometry.DefiniteLength]", ("nested", "@geometry.EdgesRefinement[@geometry.DefiniteLength]"), "Inner spacing."), ("border_widths", "@geometry.Edges[@geometry.AbsoluteLength]", ("nested", "@geometry.EdgesRefinement[@geometry.AbsoluteLength]"), "Border width per side."), ("align_items", "AlignItems?", "option", "Cross-axis alignment of children."), ("align_self", "AlignItems?", "option", "Cross-axis alignment of this element (GPUI: AlignSelf)."), ("align_content", "AlignContent?", "option", "Distribution of lines in a multi-line container."), ("justify_content", "AlignContent?", "option", "Main-axis distribution of children (GPUI: JustifyContent)."), ("gap", "@geometry.Size[@geometry.DefiniteLength]", ("nested", "@geometry.SizeRefinement[@geometry.DefiniteLength]"), "Gap between children (width: column gap, height: row gap)."), ("flex_direction", "FlexDirection", "plain", "Main axis direction."), ("flex_wrap", "FlexWrap", "plain", "Whether children wrap onto new lines."), ("flex_basis", "@geometry.Length", "plain", "Initial main size before growing or shrinking."), ("flex_grow", "Double", "plain", "Share of free space to take."), ("flex_shrink", "Double", "plain", "Share of negative space to give up."), ("background", "Fill?", "option", "Background fill."), ("border_color", "@color.Hsla?", "option", "Border color."), ("border_style", "@scene.BorderStyle", "plain", "Solid or dashed border."), ("corner_radii", "@geometry.Corners[@geometry.AbsoluteLength]", ("nested", "@geometry.CornersRefinement[@geometry.AbsoluteLength]"), "Corner radii."), ("box_shadow", "Array[BoxShadow]", "plain", "Box shadows, painted in order. Treat as immutable."), ("text", "TextStyleRefinement", ("nested", "TextStyleRefinement"), "Text style inherited by descendants."), ("mouse_cursor", "CursorStyle?", "option", "Cursor shown while hovering."), ("opacity", "Double?", "option", "Opacity multiplier for the element and its children."), ("grid_cols", "GridTemplate?", "option", "Grid column template."), ("grid_rows", "GridTemplate?", "option", "Grid row template."), ("grid_location", "@geometry.GridLocation?", "option", "Placement within a grid parent."), ("debug", "Bool", "plain", "Paint a debug outline around the element."), ("debug_below", "Bool", "plain", "Paint debug outlines around all descendants."), ] TEXT_STYLE_FIELDS = [ ("color", "@color.Hsla", "plain", "Text color."), ("font_family", "String", "plain", "Font family name."), ("font_features", "@font.FontFeatures", "plain", "OpenType features."), ("font_fallbacks", "@font.FontFallbacks?", "option", "Fallback families."), ("font_size", "@geometry.AbsoluteLength", "plain", "Font size."), ("line_height", "@geometry.DefiniteLength", "plain", "Line height; fractions are relative to the font size."), ("font_weight", "@font.FontWeight", "plain", "Font weight."), ("font_style", "@font.FontStyle", "plain", "Upright, italic or oblique."), ("background_color", "@color.Hsla?", "option", "Background behind the glyphs."), ("underline", "UnderlineStyle?", "option", "Underline decoration."), ("strikethrough", "StrikethroughStyle?", "option", "Strikethrough decoration."), ("white_space", "WhiteSpace", "plain", "Whether text wraps."), ("text_overflow", "TextOverflow?", "option", "How overflowing text is truncated."), ("text_align", "TextAlign", "plain", "Horizontal alignment."), ("line_clamp", "Int?", "option", "Maximum number of lines."), ] def refinement_type(ty, kind): if kind == "plain": return f"{ty}?" if kind == "option": return ty return kind[1] def gen_style_structs(): out = [HEADER] # --- Style ------------------------------------------------------------- out.append("///|\n/// The fully resolved style of an element (GPUI: `Style`).\n") out.append("/// Immutable; build one by refining `Style::default()`.\n") out.append("#derive(Eq, Debug)\npub(all) struct Style {\n") for name, ty, kind, doc in STYLE_FIELDS: out.append(f" /// {doc}\n {name} : {ty}\n") out.append("}\n\n") # --- StyleRefinement ----------------------------------------------------- out.append( "///|\n/// A partial `Style`: every field optional (GPUI: `StyleRefinement`).\n" "/// Mutable, because it is the builder that `Styled` methods write to.\n" ) out.append("#derive(Eq, Debug)\npub(all) struct StyleRefinement {\n") for name, ty, kind, doc in STYLE_FIELDS: out.append(f" mut {name} : {refinement_type(ty, kind)}\n") out.append("}\n\n") out.append("///|\n/// An empty refinement (no field set).\n") out.append("pub fn StyleRefinement::new() -> StyleRefinement {\n {\n") for name, ty, kind, doc in STYLE_FIELDS: value = "None" if kind in ("plain", "option") else "Default::default()" out.append(f" {name}: {value},\n") out.append(" }\n}\n\n") out.append( "///|\npub impl Default for StyleRefinement with default() {\n" " StyleRefinement::new()\n}\n\n" ) out.append("///|\n/// A copy that can be mutated independently.\n") out.append("pub fn StyleRefinement::copy(self : StyleRefinement) -> StyleRefinement {\n {\n") for name, *_ in STYLE_FIELDS: out.append(f" {name}: self.{name},\n") out.append(" }\n}\n\n") out.append("///|\n/// Applies `other` on top of `self`, in place: fields set in `other` win.\n") out.append( "pub fn StyleRefinement::refine(\n self : StyleRefinement,\n other : StyleRefinement,\n) -> Unit {\n" ) for name, ty, kind, doc in STYLE_FIELDS: if kind in ("plain", "option"): out.append(f" if other.{name} is Some(_) {{\n self.{name} = other.{name}\n }}\n") else: out.append(f" self.{name} = self.{name}.refined(other.{name})\n") out.append("}\n\n") out.append("///|\n/// A new refinement: `self` with `other` applied on top.\n") out.append( "pub fn StyleRefinement::refined(\n self : StyleRefinement,\n other : StyleRefinement,\n) -> StyleRefinement {\n" " let result = self.copy()\n result.refine(other)\n result\n}\n\n" ) out.append("///|\n/// Whether any field is set.\n") out.append("pub fn StyleRefinement::is_some(self : StyleRefinement) -> Bool {\n") conds = [] for name, ty, kind, doc in STYLE_FIELDS: if kind in ("plain", "option"): conds.append(f"self.{name} is Some(_)") else: conds.append(f"self.{name}.is_some()") out.append(" " + " ||\n ".join(conds) + "\n}\n\n") out.append("///|\n/// `self` with every field set in `refinement` overwritten.\n") out.append("pub fn Style::refined(self : Style, refinement : StyleRefinement) -> Style {\n {\n") for name, ty, kind, doc in STYLE_FIELDS: if kind == "plain": out.append(f" {name}: refine_value(refinement.{name}, self.{name}),\n") elif kind == "option": out.append(f" {name}: refine_option(refinement.{name}, self.{name}),\n") else: out.append(f" {name}: self.{name}.refined(refinement.{name}),\n") out.append(" }\n}\n\n") # --- TextStyle ----------------------------------------------------------- out.append("///|\n/// The resolved style of a run of text (GPUI: `TextStyle`).\n") out.append("#derive(Eq, Debug)\npub(all) struct TextStyle {\n") for name, ty, kind, doc in TEXT_STYLE_FIELDS: out.append(f" /// {doc}\n {name} : {ty}\n") out.append("}\n\n") out.append("///|\n/// A partial `TextStyle` (GPUI: `TextStyleRefinement`). Immutable.\n") out.append("#derive(Eq, Default, Debug)\npub(all) struct TextStyleRefinement {\n") for name, ty, kind, doc in TEXT_STYLE_FIELDS: out.append(f" {name} : {refinement_type(ty, kind)}\n") out.append("}\n\n") out.append("///|\n/// Combines two refinements; fields set in `other` win.\n") out.append( "pub fn TextStyleRefinement::refined(\n self : TextStyleRefinement,\n" " other : TextStyleRefinement,\n) -> TextStyleRefinement {\n {\n" ) for name, *_ in TEXT_STYLE_FIELDS: out.append(f" {name}: refine_option(other.{name}, self.{name}),\n") out.append(" }\n}\n\n") out.append("///|\n/// Whether any field is set.\n") out.append("pub fn TextStyleRefinement::is_some(self : TextStyleRefinement) -> Bool {\n") out.append( " " + " ||\n ".join(f"self.{name} is Some(_)" for name, *_ in TEXT_STYLE_FIELDS) + "\n}\n\n" ) out.append("///|\n/// `self` with every field set in `refinement` overwritten.\n") out.append( "pub fn TextStyle::refined(\n self : TextStyle,\n refinement : TextStyleRefinement,\n) -> TextStyle {\n {\n" ) for name, ty, kind, doc in TEXT_STYLE_FIELDS: fn = "refine_value" if kind == "plain" else "refine_option" out.append(f" {name}: {fn}(refinement.{name}, self.{name}),\n") out.append(" }\n}\n") return "".join(out) # --------------------------------------------------------------------------- # Styled helpers (gpui_macros/src/styles.rs) # --------------------------------------------------------------------------- # Container field -> length type stored in StyleRefinement. CONTAINER_TYPES = { "size": "Length", "min_size": "Length", "max_size": "Length", "inset": "Length", "margin": "Length", "padding": "DefiniteLength", "gap": "DefiniteLength", "corner_radii": "AbsoluteLength", "border_widths": "AbsoluteLength", } # Number of members of each container (Size: 2, Edges/Corners: 4). CONTAINER_ARITY = { "size": 2, "min_size": 2, "max_size": 2, "gap": 2, "inset": 4, "margin": 4, "padding": 4, "corner_radii": 4, "border_widths": 4, } PARAM_TYPES = { "Length": ("@geometry.IntoLength", "into_length"), "DefiniteLength": ("@geometry.IntoDefiniteLength", "into_definite_length"), "AbsoluteLength": ("@geometry.IntoAbsoluteLength", "into_absolute_length"), } # (prefix, auto_allowed, fields, description) BOX_PREFIXES = [ ("w", True, ["size.width"], "the width"), ("h", True, ["size.height"], "the height"), ("size", True, ["size.width", "size.height"], "the width and height"), ("min_size", True, ["min_size.width", "min_size.height"], "the minimum width and height"), ("min_w", True, ["min_size.width"], "the minimum width"), ("min_h", True, ["min_size.height"], "the minimum height"), ("max_size", True, ["max_size.width", "max_size.height"], "the maximum width and height"), ("max_w", True, ["max_size.width"], "the maximum width"), ("max_h", True, ["max_size.height"], "the maximum height"), ("gap", False, ["gap.width", "gap.height"], "the gap between rows and columns"), ("gap_x", False, ["gap.width"], "the gap between columns"), ("gap_y", False, ["gap.height"], "the gap between rows"), ] MARGIN_PREFIXES = [ ("m", True, ["margin.top", "margin.bottom", "margin.left", "margin.right"], "the margin on all sides"), ("mt", True, ["margin.top"], "the top margin"), ("mb", True, ["margin.bottom"], "the bottom margin"), ("my", True, ["margin.top", "margin.bottom"], "the vertical margin"), ("mx", True, ["margin.left", "margin.right"], "the horizontal margin"), ("ml", True, ["margin.left"], "the left margin"), ("mr", True, ["margin.right"], "the right margin"), ] PADDING_PREFIXES = [ ("p", False, ["padding.top", "padding.bottom", "padding.left", "padding.right"], "the padding on all sides"), ("pt", False, ["padding.top"], "the top padding"), ("pb", False, ["padding.bottom"], "the bottom padding"), ("px", False, ["padding.left", "padding.right"], "the horizontal padding"), ("py", False, ["padding.top", "padding.bottom"], "the vertical padding"), ("pl", False, ["padding.left"], "the left padding"), ("pr", False, ["padding.right"], "the right padding"), ] POSITION_PREFIXES = [ ("inset", True, ["inset.top", "inset.right", "inset.bottom", "inset.left"], "the inset on all sides"), ("top", True, ["inset.top"], "the top inset"), ("bottom", True, ["inset.bottom"], "the bottom inset"), ("left", True, ["inset.left"], "the left inset"), ("right", True, ["inset.right"], "the right inset"), ] # (suffix, (unit, value)) BOX_SUFFIXES = [ ("0", ("px", 0.0)), ("0p5", ("rems", 0.125)), ("1", ("rems", 0.25)), ("1p5", ("rems", 0.375)), ("2", ("rems", 0.5)), ("2p5", ("rems", 0.625)), ("3", ("rems", 0.75)), ("3p5", ("rems", 0.875)), ("4", ("rems", 1.0)), ("5", ("rems", 1.25)), ("6", ("rems", 1.5)), ("7", ("rems", 1.75)), ("8", ("rems", 2.0)), ("9", ("rems", 2.25)), ("10", ("rems", 2.5)), ("11", ("rems", 2.75)), ("12", ("rems", 3.0)), ("16", ("rems", 4.0)), ("20", ("rems", 5.0)), ("24", ("rems", 6.0)), ("32", ("rems", 8.0)), ("40", ("rems", 10.0)), ("48", ("rems", 12.0)), ("56", ("rems", 14.0)), ("64", ("rems", 16.0)), ("72", ("rems", 18.0)), ("80", ("rems", 20.0)), ("96", ("rems", 24.0)), ("112", ("rems", 28.0)), ("128", ("rems", 32.0)), ("auto", ("auto", None)), ("px", ("px", 1.0)), ("full", ("relative", 1.0)), ("1_2", ("relative", 0.5)), ("1_3", ("relative", 1.0 / 3.0)), ("2_3", ("relative", 2.0 / 3.0)), ("1_4", ("relative", 0.25)), ("2_4", ("relative", 0.5)), ("3_4", ("relative", 0.75)), ("1_5", ("relative", 0.2)), ("2_5", ("relative", 0.4)), ("3_5", ("relative", 0.6)), ("4_5", ("relative", 0.8)), ("1_6", ("relative", 1.0 / 6.0)), ("5_6", ("relative", 5.0 / 6.0)), ("1_12", ("relative", 1.0 / 12.0)), ] CORNER_PREFIXES = [ ("rounded", ["corner_radii.top_left", "corner_radii.top_right", "corner_radii.bottom_right", "corner_radii.bottom_left"], "all corner radii"), ("rounded_t", ["corner_radii.top_left", "corner_radii.top_right"], "the top corner radii"), ("rounded_b", ["corner_radii.bottom_left", "corner_radii.bottom_right"], "the bottom corner radii"), ("rounded_r", ["corner_radii.top_right", "corner_radii.bottom_right"], "the right corner radii"), ("rounded_l", ["corner_radii.top_left", "corner_radii.bottom_left"], "the left corner radii"), ("rounded_tl", ["corner_radii.top_left"], "the top-left corner radius"), ("rounded_tr", ["corner_radii.top_right"], "the top-right corner radius"), ("rounded_bl", ["corner_radii.bottom_left"], "the bottom-left corner radius"), ("rounded_br", ["corner_radii.bottom_right"], "the bottom-right corner radius"), ] CORNER_SUFFIXES = [ ("none", ("px", 0.0)), ("xs", ("rems", 0.125)), ("sm", ("rems", 0.25)), ("md", ("rems", 0.375)), ("lg", ("rems", 0.5)), ("xl", ("rems", 0.75)), ("2xl", ("rems", 1.0)), ("3xl", ("rems", 1.5)), ("full", ("px", 9999.0)), ] BORDER_PREFIXES = [ ("border", ["border_widths.top", "border_widths.right", "border_widths.bottom", "border_widths.left"], "the border width on all sides"), ("border_t", ["border_widths.top"], "the top border width"), ("border_b", ["border_widths.bottom"], "the bottom border width"), ("border_r", ["border_widths.right"], "the right border width"), ("border_l", ["border_widths.left"], "the left border width"), ("border_x", ["border_widths.left", "border_widths.right"], "the left and right border widths"), ("border_y", ["border_widths.top", "border_widths.bottom"], "the top and bottom border widths"), ] BORDER_SUFFIXES = [(str(n), ("px", float(n))) for n in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 16, 20, 24, 32]] # (method, CursorStyle variant) CURSORS = [ ("cursor_default", "Arrow"), ("cursor_pointer", "PointingHand"), ("cursor_text", "IBeam"), ("cursor_move", "ClosedHand"), ("cursor_not_allowed", "OperationNotAllowed"), ("cursor_context_menu", "ContextualMenu"), ("cursor_crosshair", "Crosshair"), ("cursor_vertical_text", "IBeamCursorForVerticalLayout"), ("cursor_alias", "DragLink"), ("cursor_copy", "DragCopy"), ("cursor_no_drop", "OperationNotAllowed"), ("cursor_grab", "OpenHand"), ("cursor_grabbing", "ClosedHand"), ("cursor_ew_resize", "ResizeLeftRight"), ("cursor_ns_resize", "ResizeUpDown"), ("cursor_nesw_resize", "ResizeUpRightDownLeft"), ("cursor_nwse_resize", "ResizeUpLeftDownRight"), ("cursor_col_resize", "ResizeColumn"), ("cursor_row_resize", "ResizeRow"), ("cursor_n_resize", "ResizeUp"), ("cursor_e_resize", "ResizeRight"), ("cursor_s_resize", "ResizeDown"), ("cursor_w_resize", "ResizeLeft"), ] def fmt_number(value): text = repr(float(value)) if "e" in text or "E" in text: return text return text if "." in text else text + ".0" def length_expr(spec, target, negate): """MoonBit expression for a predefined length, converted to `target`.""" unit, value = spec if unit == "auto": assert target == "Length", "auto is only valid for Length fields" return f"{G}.Length::Auto" if negate: value = -value if value == 0.0: value = -0.0 number = fmt_number(value) if unit == "relative": base = f"{G}.relative({number})" if target == "Length": return f"{base}.to_length()" if target == "DefiniteLength": return base raise ValueError("relative lengths are not absolute") base = f"{G}.{unit}({number})" return { "Length": f"{base}.to_length()", "DefiniteLength": f"{base}.to_definite()", "AbsoluteLength": f"{base}.to_absolute()", }[target] def human(spec, negate): unit, value = spec if unit == "auto": return "`auto`" value = -value if negate else value if unit == "relative": return f"{fmt_number(value * 100)}%" if unit == "rems": return f"`rems({fmt_number(value)})` ({fmt_number(value * 16)}px at a 16px rem)" return f"`px({fmt_number(value)})`" def group_fields(fields): """[('margin', ['top', 'bottom']), ...] preserving order.""" groups = {} order = [] for f in fields: container, member = f.split(".") if container not in groups: groups[container] = [] order.append(container) groups[container].append(member) return [(c, groups[c]) for c in order] def assignment_body(fields, value_expr): lines = [" let style = self.style()", f" let value = Some({value_expr})"] for container, members in group_fields(fields): updates = ", ".join(f"{m}: value" for m in members) if len(members) == CONTAINER_ARITY[container]: lines.append(f" style.{container} = {{ {updates} }}") else: lines.append(f" style.{container} = {{ ..style.{container}, {updates} }}") lines.append(" self") return "\n".join(lines) class Methods: def __init__(self): self.decls = [] # (name, param_types) self.impls = [] # source blocks def add(self, name, params, body, doc): """params: list of (name, type) excluding self.""" self.decls.append((name, [t for _, t in params])) sig = ", ".join(["self : Self"] + [f"{n} : {t}" for n, t in params]) self.impls.append(f"///|\n/// {doc}\nimpl Styled with fn {name}({sig}) -> Self {{\n{body}\n}}\n") def gen_box_methods(m, prefixes, suffixes): for prefix, auto_allowed, fields, desc in prefixes: target = CONTAINER_TYPES[fields[0].split(".")[0]] if not auto_allowed: assert target != "Length" or prefix in ("gap", "gap_x", "gap_y") param_type, conv = PARAM_TYPES[target] m.add( prefix, [("length", "&" + param_type)], assignment_body(fields, f"length.{conv}()"), f"Sets {desc}.", ) for suffix, spec in suffixes: if suffix != "auto" or auto_allowed: m.add( f"{prefix}_{suffix}", [], assignment_body(fields, length_expr(spec, target, False)), f"Sets {desc} to {human(spec, False)}.", ) if suffix != "auto": m.add( f"{prefix}_neg_{suffix}", [], assignment_body(fields, length_expr(spec, target, True)), f"Sets {desc} to {human(spec, True)}.", ) def gen_value_methods(m, prefixes, suffixes): for prefix, fields, desc in prefixes: target = CONTAINER_TYPES[fields[0].split(".")[0]] param_type, conv = PARAM_TYPES[target] m.add( prefix, [("length", "&" + param_type)], assignment_body(fields, f"length.{conv}()"), f"Sets {desc}.", ) for suffix, spec in suffixes: m.add( f"{prefix}_{suffix}", [], assignment_body(fields, length_expr(spec, target, False)), f"Sets {desc} to {human(spec, False)}.", ) def gen_cursor_methods(m): for name, variant in CURSORS: m.add( name, [], f" self.style().mouse_cursor = Some(CursorStyle::{variant})\n self", f"Shows the `{variant}` cursor while hovering.", ) def split_params(text): parts, depth, current = [], 0, "" for ch in text: if ch in "[(": depth += 1 elif ch in "])": depth -= 1 if ch == "," and depth == 0: parts.append(current) current = "" else: current += ch if current.strip(): parts.append(current) return [p.strip() for p in parts if p.strip()] def handwritten_decls(): src = open(HANDWRITTEN).read() decls = [] pattern = re.compile( r"^impl Styled with (?:fn )?(\w+)\((.*?)\)\s*->\s*Self\s*\{", re.S | re.M ) for match in pattern.finditer(src): name = match.group(1) params = split_params(match.group(2)) if not params or not params[0].startswith("self"): sys.exit(f"gen_style: {name}: first parameter must be `self : Self`") types = [] for p in params[1:]: if ":" not in p: sys.exit(f"gen_style: {name}: parameter `{p}` needs a type annotation") types.append(p.split(":", 1)[1].strip()) decls.append((name, types)) if not decls: sys.exit("gen_style: found no `impl Styled with` blocks in styled.mbt") return decls def gen_styled(): m = Methods() gen_box_methods(m, BOX_PREFIXES, BOX_SUFFIXES) gen_box_methods(m, MARGIN_PREFIXES, BOX_SUFFIXES) gen_box_methods(m, PADDING_PREFIXES, BOX_SUFFIXES) gen_box_methods(m, POSITION_PREFIXES, BOX_SUFFIXES) gen_value_methods(m, CORNER_PREFIXES, CORNER_SUFFIXES) gen_value_methods(m, BORDER_PREFIXES, BORDER_SUFFIXES) gen_cursor_methods(m) all_decls = handwritten_decls() + m.decls names = [n for n, _ in all_decls] duplicates = sorted({n for n in names if names.count(n) > 1}) if duplicates: sys.exit(f"gen_style: duplicate Styled methods: {duplicates}") out = [HEADER] out.append( "///|\n/// Fluent styling methods (GPUI: `Styled`). Implementors only provide\n" "/// `style`, the refinement the methods write to; every other method has a\n" "/// default implementation. Because methods of a trait are not callable with\n" "/// dot syntax until promoted, implementors also need the `extend` list that\n" "/// tools/gen_style.py emits (`--extend Type=file`).\n" ) out.append("pub(open) trait Styled {\n fn style(Self) -> StyleRefinement\n") for name, types in all_decls: out.append(f" fn {name}({', '.join(['Self'] + types)}) -> Self = _\n") out.append("}\n\n") out.append("\n".join(m.impls)) return "".join(out), names def gen_extend(type_name, names): body = ",\n ".join(names) return ( HEADER + f"///|\npub extend {type_name} with Styled::{{\n {body},\n}}\n" ) def write(path, content): with open(path, "w") as f: f.write(content) print(f"wrote {os.path.relpath(path, ROOT)}") def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( "--extend", action="append", default=[], metavar="TYPE=FILE", help="also emit `pub extend TYPE with Styled::{...}` into FILE (relative to the repo root)", ) args = parser.parse_args() write(os.path.join(STYLE_DIR, "style_generated.mbt"), gen_style_structs()) styled, names = gen_styled() write(os.path.join(STYLE_DIR, "styled_generated.mbt"), styled) write( os.path.join(STYLE_DIR, "styled_extend_generated.mbt"), gen_extend("StyleRefinement", names), ) for spec in args.extend: if "=" not in spec: sys.exit(f"gen_style: --extend expects TYPE=FILE, got {spec!r}") type_name, path = spec.split("=", 1) write(os.path.join(ROOT, path), gen_extend(type_name, names)) print(f"{len(names)} Styled methods") if __name__ == "__main__": main()