Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-css

Source of release 0.5.1

0.5.1 / tools / gen_css / text.lucb

#==============================================================================================
#
#   text - names, lists and output for the emitters
#
#   DESCRIPTION:
#       The casing helpers of Ladybird's Meta/Utils/utils.py (title_casify, camel_casify,
#       snake_casify, underlying_type_for_enum), the Luce spellings the skeleton generator gives
#       C++ names (DESIGN.md ยง4.2: an enumerator `BackgroundColor` is the case
#       `background_color`, reserved and core words take a trailing `_`), a growable list of
#       strings, and the `Out` sink the emitters write Luce into. Everything is allocated with
#       the current allocator and lives for the whole run.
#
#==============================================================================================

# mark: Strings =================================================================================

## The concatenation of `parts`.
func cat(parts: const str[]) -> str!:
    var builder: collections.Buffer
    for part in parts:
        try builder.put_text(part)
    return builder.text()

## ASCII uppercase of one byte.
func upper_byte(byte: u8) -> u8:
    if byte >= 'a' and byte <= 'z':
        return byte - 32
    return byte

## ASCII lowercase of one byte.
func lower_byte(byte: u8) -> u8:
    if byte >= 'A' and byte <= 'Z':
        return byte + 32
    return byte

func is_upper(byte: u8) -> bool:
    return byte >= 'A' and byte <= 'Z'

func is_lower(byte: u8) -> bool:
    return byte >= 'a' and byte <= 'z'

func is_digit(byte: u8) -> bool:
    return byte >= '0' and byte <= '9'

## `text` with its first byte uppercased (Python's `s[0].upper() + s[1:]`).
func upper_first(text: str) -> str!:
    if text.length == 0:
        return text
    var builder: collections.Buffer
    let first: u8[1] = [upper_byte(text.bytes[0])]
    _ = try builder.write(first)
    _ = try builder.write(text.bytes[1..])
    return builder.text()

## Whether `text` begins with `prefix`.
func starts_with(text: str, prefix: str) -> bool:
    return strings.starts_with(text, prefix)

## Whether `text` ends with `suffix`.
func ends_with(text: str, suffix: str) -> bool:
    return strings.ends_with(text, suffix)

## Whether `text` contains `needle`.
func contains(text: str, needle: str) -> bool:
    return strings.contains(text, needle)

## `text[start:end]` by bytes.
func slice(text: str, start: usize, end: usize) -> str:
    return (str)text.bytes[start..<end]

## Python's `a < b` on strings: code point order, which for UTF-8 is byte order.
func string_less(a: str, b: str) -> bool:
    let length = a.length if a.length < b.length else b.length
    for index in 0..<length:
        if a.bytes[index] != b.bytes[index]:
            return a.bytes[index] < b.bytes[index]
    return a.length < b.length

## ASCII lowercase of `text` (Python's `str.lower()` on the ASCII inputs).
func lower(text: str) -> str!:
    var builder: collections.Buffer
    for byte in text.bytes:
        let lowered: u8[1] = [lower_byte(byte)]
        _ = try builder.write(lowered)
    return builder.text()

# mark: Meta/Utils/utils.py =====================================================================

## Ported from Meta/Utils/utils.py title_casify: `background-color` is `BackgroundColor`.
func title_casify(dashy_name: str) -> str!:
    var builder: collections.Buffer
    var parts = try strings.SplitIterator.over(dashy_name, "-")
    while let part = parts.next():
        if part.length == 0:
            continue
        try builder.put_text(try upper_first(part))
    return builder.text()

## Ported from Meta/Utils/utils.py camel_casify: `background-color` is `backgroundColor`.
func camel_casify(dashy_name: str) -> str!:
    var builder: collections.Buffer
    var parts = try strings.SplitIterator.over(dashy_name, "-")
    var first = true
    while let part = parts.next():
        if part.length == 0:
            continue
        if first:
            try builder.put_text(part)
            first = false
        else:
            try builder.put_text(try upper_first(part))
    return builder.text()

## Ported from Meta/Utils/utils.py snake_casify: `background-color` is `background_color`.
func snake_casify(dashy_name: str) -> str!:
    return try strings.replace(dashy_name, "-", "_")

## Ported from Meta/Utils/utils.py underlying_type_for_enum, as the Luce integer type.
func underlying_type_for_enum(member_count: usize) -> str:
    if member_count <= 0xff:
        return "u8"
    if member_count <= 0xffff:
        return "u16"
    if member_count <= 0xffffffff:
        return "u32"
    return "u64"

# mark: Luce names (the skeleton generator's names.py) ==========================================

## The words of a C++ identifier, as names.py's `words`: each `_`-separated part split by the
## pattern `[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+`.
func identifier_words(identifier: str) -> StrList!:
    var result = try StrList.create()
    let bytes = identifier.bytes
    var index: usize = 0
    while index < bytes.length:
        let byte = bytes[index]
        if is_upper(byte):
            var end = index
            while end < bytes.length and is_upper(bytes[end]):
                end += 1
            if end - index >= 2 and end < bytes.length and is_lower(bytes[end]):
                # [A-Z]+(?=[A-Z][a-z]): the uppercase run without its last letter.
                try result.append(slice(identifier, index, end - 1))
                index = end - 1
            elif end - index == 1 and end < bytes.length and is_lower(bytes[end]):
                # [A-Z]?[a-z]+
                var word_end = end
                while word_end < bytes.length and is_lower(bytes[word_end]):
                    word_end += 1
                try result.append(slice(identifier, index, word_end))
                index = word_end
            else:
                # [A-Z]+
                try result.append(slice(identifier, index, end))
                index = end
        elif is_lower(byte):
            var end = index
            while end < bytes.length and is_lower(bytes[end]):
                end += 1
            try result.append(slice(identifier, index, end))
            index = end
        elif is_digit(byte):
            var end = index
            while end < bytes.length and is_digit(bytes[end]):
                end += 1
            try result.append(slice(identifier, index, end))
            index = end
        else:
            index += 1
    return result

## names.py's `snake`: `BackgroundColor` is `background_color`; digits stay with the word
## before them (`Matrix3d` is `matrix3_d`).
func luce_snake(identifier: str) -> str!:
    let words = try identifier_words(identifier)
    var builder: collections.Buffer
    var first = true
    for index in 0..<words.count:
        let word = words.at(index)
        if is_digit(word.bytes[0]) and not first:
            try builder.put_text(word)
            continue
        if not first:
            try builder.put_text("_")
        try builder.put_text(try lower(word))
        first = false
    return builder.text()

## names.py's `pascal`: `HTMLElement` is `HtmlElement`.
func luce_pascal(identifier: str) -> str!:
    let words = try identifier_words(identifier)
    var builder: collections.Buffer
    for index in 0..<words.count:
        let word = words.at(index)
        var all_upper = true
        for byte in word.bytes:
            if is_lower(byte):
                all_upper = false
        if all_upper or is_upper(word.bytes[0]):
            try builder.put_text(try upper_first(try lower(word)))
        else:
            try builder.put_text(try upper_first(word))
    return builder.text()

## The suffix the skeleton generator gives an overload of a C++ function taking `type_name`
## (naming.py's short_param: the snake-case type name, at most 30 bytes), as in
## `to_string_length_unit`.
func overload_suffix(type_name: str) -> str!:
    let snake = try luce_snake(type_name)
    if snake.length > 30:
        return slice(snake, 0, 30)
    return snake

## The reserved and core words of luce-base and the standard module names (names.py).
let reserved_words: str[53] = ["alloc", "and", "as", "asm", "break", "catch", "const", "continue",
                               "defer", "elif", "else", "enum", "errdefer", "export", "extern", "false", "for", "free", "from",
                               "func", "goto", "if", "import", "in", "interface", "let", "local", "match", "mutating", "new",
                               "none", "not", "or", "pub", "recover", "return", "self", "static", "struct", "test", "true",
                               "try", "type", "union", "var", "volatile", "while", "with", "class", "spawn", "assert",
                               "discard", "error"]
let core_words: str[32] = ["trap", "hash", "print", "format", "sizeof", "alignof", "offsetof", "hex",
                           "bin", "pad", "bool", "i8", "i16", "i32", "i64", "isize", "u8", "u16", "u32", "u64", "usize",
                           "f16", "f32", "f64", "char", "str", "unit", "never", "void", "fmt", "Error", "ErrorCode"]
let std_module_words: str[10] = ["memory", "io", "os", "thread", "sync", "atomic", "c", "testing",
                                 "runtime", "luce"]

## names.py's `safe`: a reserved or core word takes a trailing `_`.
func luce_safe(name: str) -> str!:
    for word in reserved_words:
        if word == name:
            return try cat([name, "_"])
    for word in core_words:
        if word == name:
            return try cat([name, "_"])
    for word in std_module_words:
        if word == name:
            return try cat([name, "_"])
    if name == "_":
        return "__"
    return name

## The Luce case of the C++ enumerator `title` (emit.py's emit_enum: `none` is `none_`).
func luce_case(title: str) -> str!:
    return try luce_safe(try luce_snake(title))

# mark: Lists ===================================================================================

## A growable list of strings.
struct StrList:
    var items: str[]
    var count: usize

    static func create() -> StrList!:
        return StrList(items = try new str[16], count = 0)

    func append(value: str) -> !:
        if self.count == self.items.length:
            let grown = try new str[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

    func at(index: usize) -> str:
        assert(index < self.count)
        return self.items[index]

    func contains(value: str) -> bool:
        for index in 0..<self.count:
            if self.items[index] == value:
                return true
        return false

    func view() -> const str[]:
        return self.items[..<self.count]

## An insertion-ordered map from strings to lists of strings (Python's
## `dict.setdefault(key, []).append(value)` pattern).
struct StrListMap:
    var keys: StrList
    var values: (StrList*?)[]

    static func create() -> StrListMap!:
        return StrListMap(keys = try StrList.create(), values = try new (StrList*?)[16])

    ## The list of `key`, created empty when there is none (`setdefault`).
    func list(key: str) -> StrList*!:
        for index in 0..<self.keys.count:
            if self.keys.at(index) == key:
                return self.values[index] else trap("a key without a list")
        if self.keys.count == self.values.length:
            let grown = try new (StrList*?)[self.values.length * 2]
            for index in 0..<self.keys.count:
                grown[index] = self.values[index]
            self.values = grown
        let created = try new StrList(items = try new str[16], count = 0)
        self.values[self.keys.count] = created
        try self.keys.append(key)
        return created

    ## The list of `key`, or none (`dict.get`).
    func get(key: str) -> StrList*?:
        for index in 0..<self.keys.count:
            if self.keys.at(index) == key:
                return self.values[index]
        return none

## Sort `list` ascending by code points (Python's `sorted` on strings).
func sort_strings(list: StrList*):
    # Insertion sort: stable, as Python's sort is.
    for index in 1..<list.count:
        let value = list.items[index]
        var position = index
        while position > 0 and string_less(value, list.items[position - 1]):
            list.items[position] = list.items[position - 1]
            position -= 1
        list.items[position] = value

# mark: Output ==================================================================================

## The text of a generated fragment.
struct Out:
    var builder: collections.Buffer

    static func create() -> Out!:
        return Out()

    ## Append `text`.
    func put(text: fmt) -> !:
        _ = try self.builder.write(text)

    ## Append `text` and a line feed.
    func line(text: fmt) -> !:
        _ = try self.builder.write(text)
        try self.builder.put_text("\n")

    ## Append an empty line.
    func blank() -> !:
        try self.builder.put_text("\n")

    func text() -> str:
        return self.builder.text()

## The standard header box of a generated fragment.
func put_header(out: Out*, name: str, summary: str, description: const str[]) -> !:
    let rule = "#=============================================================================================="
    try out.line(rule)
    try out.line("#")
    try out.line(f"#   {name} - {summary}")
    try out.line("#")
    try out.line("#   DESCRIPTION:")
    for line in description:
        if line.length == 0:
            try out.line("#")
        else:
            try out.line(f"#       {line}")
    try out.line("#")
    try out.line(rule)

## A `# mark:` line padded to the house width.
func put_mark(out: Out*, title: str) -> !:
    try out.blank()
    var text: collections.Buffer
    try text.put_text("# mark: ")
    try text.put_text(title)
    try text.put_text(" ")
    while text.length() < 97:
        try text.put_text("=")
    try out.line(f"{text.text()}")
    try out.blank()

## `text` as a Luce string literal (the JSON inputs hold no quotes or backslashes that the
## emitted names use; any that appear are escaped).
func literal(text: str) -> str!:
    var builder: collections.Buffer
    try builder.put_text("\"")
    for byte in text.bytes:
        if byte == '"':
            try builder.put_text("\\\"")
        elif byte == '\\':
            try builder.put_text("\\\\")
        else:
            let one: u8[1] = [byte]
            _ = try builder.write(one)
    try builder.put_text("\"")
    return builder.text()