#! @file pattern.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains `pattern`, a glob read into the pieces that match it, and how the #! text of a path is matched against one. module std::io::glob; #! A glob, read into what each of its names matches. #! #! Braces are taken out as it is read, so a pattern is one or more choices, #! each a root and a list of segments: a name as written, a name matched by its #! pieces, or `**`. Every segment, piece, and set is held in a flat array of the #! pattern's, by index, as are the bytes of the names and pieces as written. pub struct pattern { var _text: string; #! The glob, as given. var _options: options; var _bytes: string; #! The bytes of every name and text piece, and every root, escapes taken out. var _pieces: vector; var _ranges: vector; #! The characters of every set. var _segments: vector; var _choices: vector; } # What a piece of a name matches. enum piece_kind: u8 { text, #! Its bytes, as written. one, #! Any one character. any, #! Any run of characters, or none. set, #! One character within any of its ranges. unset, #! One character within none of its ranges. } # A piece of a name: what it matches, and where its bytes or ranges are. struct piece { var kind: piece_kind; var start: u64; #! Its first byte in `_bytes`, or its first range in `_ranges`. var length: u64; #! How many bytes or ranges it has. } # The characters from one to another, both included, which a set holds. struct bounds { var low: u32; var high: u32; } # What a segment of a choice matches. enum segment_kind: u8 { literal, #! One name, as written: its bytes are in `_bytes`. wild, #! One name its pieces match: they are in `_pieces`. deep, #! Any number of whole names, none included, as `**` does. } # A segment of a choice: what it matches, and where its bytes or pieces are. struct segment { var kind: segment_kind; var start: u64; #! Its first byte or piece. var length: u64; #! How many bytes or pieces it has. var dotted: bool; #! Whether it starts with `.` as written, so it may match a hidden name. } # One of the globs a pattern's braces make: where it starts, and its segments. struct choice { var start: u64; #! Its first segment in `_segments`. var length: u64; #! How many segments it has. var root: u64; #! Its root's first byte in `_bytes`. var rooted: u64; #! How many bytes its root has: none, as `/`, or as `C:/`. var directories: bool; #! Whether it ended in `/`, so only directories match. } # A character of text, and how many bytes it takes. struct rune { var value: u32; var width: u64; } #! Reads a glob. #! @param text The glob, as `src/**/*.sakura`. #! @param settings How it is read and matched. #! @param alloc The optional allocator for what the pattern holds. #! @returns The pattern, or the first mistake the text holds. pub def pattern::parse( text: strview, settings: options = options {}, alloc: maybe<&mut allocator> = nothing{} ): result { if text.length == 0 { return error { kind = error_kind::empty, offset = 0 }; } if mistake_in(text) is some(found) { return found; } var choices := vector::::new(alloc); if !expand(text, &mut choices, alloc) { return error { kind = error_kind::too_many_choices, offset = 0 }; } var made := pattern { _text = string::from(text, alloc), _options = settings, _bytes = string::new(alloc), _pieces = vector::::new(alloc), _ranges = vector::::new(alloc), _segments = vector::::new(alloc), _choices = vector::::new(alloc) }; for &each in choices { made.add_choice(each.view()); } return move(made); } #! The glob the pattern was read from. #! @param this The pattern. #! @returns The glob's text, as given. pub val pattern::text: strview { get => this._text.view(); } #! Whether the glob has no wildcards or braces, so it names one path, which #! matches only itself. #! @param this The pattern. #! @returns Whether every name of its one choice is written as it is. pub val pattern::is_literal: bool { get { return false if this._choices.length != 1; val only := this._choices[0]; for s in only.start..(only.start + only.length) { return false if this._segments[s].kind != segment_kind::literal; } return true; } } #! Whether the glob ends in `/`, so only directories match it. #! @param this The pattern. #! @returns Whether any of its choices does. pub val pattern::directories: bool { get { for c in 0..this._choices.length { return true if this._choices[c].directories; } return false; } } #! Tells whether the text of a path matches the glob, from the text alone. #! @param this The pattern. #! @param text The path, as `src/main.sakura`. A name of `.`, and a `/` more #! than one between names, are passed over, as a path's normal #! form does. On Windows, `\` separates names too. #! @returns Whether any of the pattern's choices matches it. A glob ending in #! `/` matches only text ending in one, which says it is a directory, #! and text that is only a root, or `.`, is matched only by a glob #! naming it, as `**` doesn't. pub def pattern::matches(&this, text: strview): bool { var at := 0u; var root := strview::empty(); if text.length > 0 && is_delim(text[0]) { root = "/"; at = 1; } when os == windows { if text.length > 2 && text[0].is_alpha && text[1] == ':' && is_delim(text[2]) { root = text.substr(0, 2); at = 3; } } var names := vector::::new(); var from := at; while at <= text.length { if at < text.length && !is_delim(text[at]) { at++; continue; } val name := text.substr(from, at - from); if name.length != 0 && name != "." { names.append(name); } at++; from = at; } val directory := text.length > 0 && is_delim(text[text.length - 1]); for c in 0..this._choices.length { val each := this._choices[c]; continue if each.directories && !directory; continue if !this.same_root(&each, root); return true if this.fits(&each, names.view()); } return false; } # Whether a byte separates the names of a path's text. def is_delim(byte: u8): bool { when os == windows { return byte == '/' || byte == '\\'; } return byte == '/'; } # Whether text's root is a choice's, which is empty, `/`, or a drive's: `C:` in # the text, and `C:/` in the choice. def pattern::same_root(&this, each: &choice, root: strview): bool { if each.rooted == 0 || root.length == 0 { return each.rooted == 0 && root.length == 0; } val mine := this._bytes.substr(each.root, each.rooted); if root == "/" { return mine == "/"; } return mine.length == 3 && mine[0].to_lower == root[0].to_lower; } # Whether a choice's segments match the names, one each, but for `**`, which # matches any number of them. def pattern::fits(&this, each: &choice, names: span): bool { if names.length == 0 { return each.length == 0; } # Without `**`, each segment matches the name in its place. var deep := false; for s in each.start..(each.start + each.length) { deep = deep || this._segments[s].kind == segment_kind::deep; } if !deep { return false if each.length != names.length; for k in 0..names.length { return false if !this.fits_name(&this._segments[each.start + k], names[k]); } return true; } # With it, whether the segments from each on match the names from each on, # worked out from the last of both back, in a row of `names.length + 1` for # each segment, so every segment is matched against every name at most once. val row := names.length + 1; var ends := vector::::new(); ends.resize((each.length + 1) * row, false); ends.set(each.length * row + names.length, true); var s := each.length; while s > 0 { s--; val seg := this._segments[each.start + s]; var n := row; while n > 0 { n--; var fits := false; if seg.kind == segment_kind::deep { fits = ends[(s + 1) * row + n] || (n < names.length && this.covers(names[n]) && ends[s * row + n + 1]); } else { fits = n < names.length && ends[(s + 1) * row + n + 1] && this.fits_name(&seg, names[n]); } ends.set(s * row + n, fits); } } return ends[0]; } # Whether a segment matches one name, which for `**` is whether it may cover it. def pattern::fits_name(&this, seg: &segment, name: strview): bool { return match seg.kind { literal => this.same(this._bytes.substr(seg.start, seg.length), name), deep => this.covers(name), wild => this.wild_fits(seg, name), }; } # Whether `**` may cover a name: any but `.`, `..`, and a hidden one, unless the # options let it. def pattern::covers(&this, name: strview): bool { return false if name == "." || name == ".."; return this._options.hidden || name.length == 0 || name[0] != '.'; } # Whether the pieces of a segment match a name, letting the last `*` seen take # a character more each time what follows it doesn't fit, as `*` matches any run. def pattern::wild_fits(&this, seg: &segment, name: strview): bool { return false if name == "." || name == ".."; if !this._options.hidden && name.length > 0 && name[0] == '.' && !seg.dotted { return false; } val end := seg.start + seg.length; var p := seg.start; var t := 0u; var starred := false; var star := 0u; # The piece after the last `*`. var resume := 0u; # Where the text goes on from after what that `*` took. while true { if p < end { val each := this._pieces[p]; if each.kind == piece_kind::any { p++; return true if p == end; starred = true; star = p; resume = t; continue; } if t < name.length { val taken := this.taken(&each, name, t); if taken != 0 { p++; t += taken; continue; } } } else if t == name.length { return true; } return false if !starred || resume >= name.length; resume += rune_at(name, resume).width; t = resume; p = star; } return false; } # How many bytes of a name a piece other than `*` takes where it starts at a # byte, or zero where it doesn't fit there. def pattern::taken(&this, each: &piece, name: strview, at: u64): u64 { if each.kind == piece_kind::text { return 0 if name.length - at < each.length; val fits := this.same(this._bytes.substr(each.start, each.length), name.substr(at, each.length)); return fits ? each.length : 0; } val read := rune_at(name, at); if each.kind == piece_kind::one { return read.width; } var within := this.within(each, read.value); if this._options.folds_case && !within { within = this.within(each, other_case(read.value)); } return within == (each.kind == piece_kind::set) ? read.width : 0; } # Whether a character is within any of a set's ranges. def pattern::within(&this, each: &piece, value: u32): bool { for r in each.start..(each.start + each.length) { val range := this._ranges[r]; return true if value >= range.low && value <= range.high; } return false; } # Whether two runs of bytes are the same, in either case where the options fold # it. def pattern::same(&this, a: strview, b: strview): bool { return false if a.length != b.length; if !this._options.folds_case { return a == b; } for k in 0..a.length { return false if a[k].to_lower != b[k].to_lower; } return true; } # An ASCII letter in the other case, and anything else as it is. def other_case(value: u32): u32 { if value >= ('a' as u32) && value <= ('z' as u32) { return value - 32; } if value >= ('A' as u32) && value <= ('Z' as u32) { return value + 32; } return value; } # The character text holds at a byte. A byte starting no character of UTF-8, or # one too short, too long, or past U+10FFFF, is a character of its own, U+FFFD. def rune_at(text: strview, at: u64): rune { val lead := text[at]; if lead < 0x80 { return rune { value = lead as u32, width = 1 }; } var width: u64 = 0; var value: u32 = 0; var least: u32 = 0; if (lead & 0xE0) == 0xC0 { width = 2; value = (lead & 0x1F) as u32; least = 0x80; } else if (lead & 0xF0) == 0xE0 { width = 3; value = (lead & 0x0F) as u32; least = 0x800; } else if (lead & 0xF8) == 0xF0 { width = 4; value = (lead & 0x07) as u32; least = 0x10000; } val malformed := rune { value = 0xFFFD, width = 1 }; return malformed if width == 0 || at + width > text.length; for k in 1..width { val byte := text[at + k]; return malformed if (byte & 0xC0) != 0x80; value = (value << 6) | (byte & 0x3F) as u32; } if value < least || value > 0x10FFFF || (value >= 0xD800 && value <= 0xDFFF) { return malformed; } return rune { value = value, width = width }; } # The first mistake in a glob's text, where it holds one: an escape ending it, # or a set or brace left open, or a brace closed that wasn't opened. def mistake_in(text: strview): maybe { var open := vector::::new(); # Where each brace still open is. var at := 0u; while at < text.length { val byte := text[at]; if byte == '\\' { return error { kind = error_kind::trailing_escape, offset = at } if at + 1 == text.length; at += 2; continue; } if byte == '[' { val end := set_end(text, at); return error { kind = error_kind::unclosed_set, offset = at } if end is none; at = end.some + 1; continue; } if byte == '{' { open.append(at); } else if byte == '}' { return error { kind = error_kind::unopened_brace, offset = at } if open.length == 0; open.remove_at(open.length - 1); } at++; } if open.length != 0 { return error { kind = error_kind::unclosed_brace, offset = open[open.length - 1] }; } return nothing{}; } # Where the `]` closing the set opened at a byte is: after a `!` or `^` and a # `]` first, which are the set's, and passing over escaped characters. def set_end(text: strview, at: u64): maybe { var k := at + 1; if k < text.length && (text[k] == '!' || text[k] == '^') { k++; } if k < text.length && text[k] == ']' { k++; } while k < text.length { return k if text[k] == ']'; k += text[k] == '\\' ? 2 : 1; } return nothing{}; } # Adds each glob a glob's braces make, in order, as `a{b,c}d` makes `abd` and # `acd`, giving whether there were no more than `choice_limit`. The text holds # no mistakes. def expand(text: strview, into: &mut vector, alloc: maybe<&mut allocator>): bool { # The first brace outside a set. var open := text.length; var at := 0u; while at < text.length { val byte := text[at]; if byte == '\\' { at += 2; continue; } if byte == '[' { at = set_end(text, at).some + 1; continue; } if byte == '{' { open = at; break; } at++; } if open == text.length { into.append(string::from(text, alloc)); return into.length <= choice_limit; } # Each choice it holds, between it, the commas within it but not within a # brace it holds, and the brace closing it. var cuts := vector::::new(); var depth := 0u; cuts.append(open); at = open + 1; while true { val byte := text[at]; if byte == '\\' { at += 2; continue; } if byte == '[' { at = set_end(text, at).some + 1; continue; } if byte == '{' { depth++; } else if byte == '}' { if depth == 0 { cuts.append(at); break; } depth--; } else if byte == ',' && depth == 0 { cuts.append(at); } at++; } val close := cuts[cuts.length - 1]; val after := text.substr(close + 1, text.length - close - 1); for k in 0..(cuts.length - 1) { var joined := string::from(text.substr(0, open), alloc); joined.append(text.substr(cuts[k] + 1, cuts[k + 1] - cuts[k] - 1)); joined.append(after); return false if !expand(joined.view(), into, alloc); } return true; } # Reads one glob without braces into a choice: its root, then a segment for # each name, passing over empty names and `.`, and taking `**` after `**` as # one. def pattern::add_choice(&mut this, text: strview): void { var made := choice { start = this._segments.length, root = this._bytes.length }; var at := 0u; if text.length > 0 && text[0] == '/' { this._bytes.push('/'); at = 1; } when os == windows { if text.length > 2 && text[0].is_alpha && text[1] == ':' && text[2] == '/' { this._bytes.append(text.substr(0, 3)); at = 3; } } made.rooted = this._bytes.length - made.root; made.directories = text.length > at && text[text.length - 1] == '/'; var from := at; # Where the name being read starts. var first := this._pieces.length; while true { val ends := at == text.length || text[at] == '/' || (text[at] == '\\' && text[at + 1] == '/'); if ends { this.add_segment(text.substr(from, at - from), first, made.start); break if at == text.length; at += text[at] == '\\' ? 2 : 1; from = at; first = this._pieces.length; continue; } val byte := text[at]; if byte == '\\' { this.add_text(text.substr(at + 1, 1), first); at += 2; } else if byte == '*' { val last := this._pieces.length; if last == first || this._pieces[last - 1].kind != piece_kind::any { this._pieces.append(piece { kind = piece_kind::any }); } at++; } else if byte == '?' { this._pieces.append(piece { kind = piece_kind::one }); at++; } else if byte == '[' { val end := set_end(text, at).some; this.add_set(text, at, end); at = end + 1; } else { this.add_text(text.substr(at, 1), first); at++; } } made.length = this._segments.length - made.start; this._choices.append(made); } # Adds bytes matched as written to the name being read, whose pieces start at # one, onto its last piece where that is text too. def pattern::add_text(&mut this, bytes: strview, first: u64): void { val last := this._pieces.length; if last > first { val prior := this._pieces[last - 1]; if prior.kind == piece_kind::text && prior.start + prior.length == this._bytes.length { this._pieces.at(last - 1).length += bytes.length; this._bytes.append(bytes); return; } } this._pieces.append(piece { kind = piece_kind::text, start = this._bytes.length, length = bytes.length }); this._bytes.append(bytes); } # Adds the set from its `[` to its `]`: each character, or range of them, it # holds, and whether it matches those or the rest. def pattern::add_set(&mut this, text: strview, open: u64, close: u64): void { var made := piece { kind = piece_kind::set, start = this._ranges.length }; var at := open + 1; if text[at] == '!' || text[at] == '^' { made.kind = piece_kind::unset; at++; } while at < close { val low := item_at(text, at); at += low.width; if at + 1 < close && text[at] == '-' { val high := item_at(text, at + 1); at += 1 + high.width; this._ranges.append(bounds { low = low.value, high = high.value }); } else { this._ranges.append(bounds { low = low.value, high = low.value }); } } made.length = this._ranges.length - made.start; this._pieces.append(made); } # The character a set holds at a byte, escaped or not, with the bytes it takes. def item_at(text: strview, at: u64): rune { if text[at] == '\\' { val escaped := rune_at(text, at + 1); return rune { value = escaped.value, width = escaped.width + 1 }; } return rune_at(text, at); } # Ends the name being read, whose pieces start at one, as a segment of the # choice whose segments start at another: a name as written where its pieces # are all text, `**` where it is only that, and its pieces otherwise. An empty # name and `.` add none, nor does `**` after `**`. def pattern::add_segment(&mut this, written: strview, first: u64, opened: u64): void { val count := this._pieces.length - first; if written.length == 0 || written == "." { this._pieces.resize(first); return; } if written == "**" { this._pieces.resize(first); val segments := this._segments.length; if segments > opened && this._segments[segments - 1].kind == segment_kind::deep { return; } this._segments.append(segment { kind = segment_kind::deep }); return; } if count == 1 && this._pieces[first].kind == piece_kind::text { val only := this._pieces[first]; this._pieces.resize(first); this._segments.append(segment { kind = segment_kind::literal, start = only.start, length = only.length }); return; } val lead := this._pieces[first]; this._segments.append(segment { kind = segment_kind::wild, start = first, length = count, dotted = lead.kind == piece_kind::text && this._bytes[lead.start] == '.' }); }