/** * @file pattern.c * @brief Pattern matching (`case`, `${x#pat}`) and pathname expansion. * * Ranges and character classes are defined over the portable character * set by position in the alphabet, so `[a-z]` means the same in ASCII and * in EBCDIC, where the letters are not contiguous. */ #include #include #include #include #include "expand.h" /** * @brief Position of `c` in the alphabet `set`. * @return The index, or -1 if `c` is not in it. */ static int index_in(const char *set, unsigned char c) { const char *p = c ? strchr(set, c) : nullptr; return p ? (int)(p - set) : -1; } /** * @brief Is `c` within the range `lo`-`hi` of a bracket expression? * * Letters are not contiguous in EBCDIC, so a range between two letters of * the same case, or between two digits, is taken by position in the * alphabet. Any other range is by character code. */ static bool in_range(unsigned char lo, unsigned char hi, unsigned char c) { #if ZASH_ASCII /* Code order is alphabet order here: one comparison, no table. */ return lo <= c && c <= hi; #else static const char *const sets[] = { "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "0123456789", }; for (size_t i = 0; i < ARRAY_LEN(sets); i++) { int a = index_in(sets[i], lo); int b = index_in(sets[i], hi); if (a >= 0 && b >= 0) { int k = index_in(sets[i], c); return k >= a && k <= b; } } return lo <= c && c <= hi; #endif } /** * @brief Does `c` belong to a named class such as `alpha` in `[[:alpha:]]`? * @param name Class name (not NUL-terminated). * @param len Its length. * @param c The character. */ static bool in_class(const char *name, size_t len, unsigned char c) { static const struct { const char *name; int (*test)(int); } classes[] = { {"alpha", isalpha}, {"digit", isdigit}, {"alnum", isalnum}, {"upper", isupper}, {"lower", islower}, {"space", isspace}, {"blank", isblank}, {"punct", ispunct}, {"print", isprint}, {"graph", isgraph}, {"cntrl", iscntrl}, {"xdigit", isxdigit}, }; for (size_t i = 0; i < ARRAY_LEN(classes); i++) { if (strlen(classes[i].name) == len && !memcmp(classes[i].name, name, len)) return classes[i].test(c) != 0; } return false; } /** * @brief Match one character against a bracket expression. * * @param p Points at the `[`. * @param endp Receives the position after the closing `]`. * @param c The character to test. * @return 1 for a match, 0 for no match, -1 if this is not a well-formed * bracket expression (the `[` is then an ordinary character). */ static int match_bracket(const char *p, const char **endp, unsigned char c) { const char *q = p + 1; bool negate = *q == '!' || *q == '^'; if (negate) q++; bool found = false; for (bool first = true;; first = false) { unsigned char lo = (unsigned char)*q; if (!lo) return -1; if (lo == ']' && !first) { q++; break; } if (lo == '[' && q[1] == ':') { const char *close = strstr(q + 2, ":]"); if (close) { found |= in_class(q + 2, (size_t)(close - q - 2), c); q = close + 2; continue; } } if (lo == '\\' && q[1]) lo = (unsigned char)*++q; q++; if (*q == '-' && q[1] && q[1] != ']') { unsigned char hi = (unsigned char)*++q; if (hi == '\\' && q[1]) hi = (unsigned char)*++q; q++; found |= in_range(lo, hi, c); } else { found |= lo == c; } } *endp = q; return found != negate; } /** * @brief Does a pattern match a whole string? * * Supports `*`, `?`, bracket expressions and backslash quoting. The match * is iterative with a single backtrack point per `*`, so it cannot recurse * deeply or take exponential time. * * @param pat The pattern, NUL-terminated. * @param s Start of the string. * @param send One past its end. * @return true if all of [s, send) matches. */ bool pat_match(const char *pat, const char *s, const char *send) { const char *star_pat = nullptr; const char *star_s = nullptr; for (;;) { char c = *pat; if (c == '*') { while (*pat == '*') pat++; if (!*pat) return true; star_pat = pat; star_s = s; continue; } if (s == send) { if (!c) return true; } else if (c == '?') { pat++; s++; continue; } else if (c == '[') { const char *end; int r = match_bracket(pat, &end, (unsigned char)*s); if (r > 0 || (r < 0 && *s == '[')) { pat = r > 0 ? end : pat + 1; s++; continue; } } else if (c == '\\' && pat[1]) { if (pat[1] == *s) { pat += 2; s++; continue; } } else if (c && c == *s) { pat++; s++; continue; } /* Mismatch: let the last '*' swallow one more character. */ if (!star_pat || star_s == send) return false; pat = star_pat; s = ++star_s; } } /* ---- pathname expansion ---------------------------------------------- */ /** * @brief State of one pathname expansion. */ typedef struct globber { strbuf path; void (*add)(void *ctx, const char *path); void *ctx; } globber; /** * @brief Does a path component contain an unquoted pattern character? */ static bool has_meta(const char *s, size_t n) { for (size_t i = 0; i < n; i++) { if (s[i] == '\\' && i + 1 < n) i++; else if (s[i] == '*' || s[i] == '?' || s[i] == '[') return true; } return false; } /** * @brief Expand the rest of a pattern, one path component at a time. * * `g->path` holds the directory reached so far. A component with no * pattern characters is appended without reading the directory. * * @param g Expansion state. * @param pat Remaining pattern. */ static void glob_from(globber *g, const char *pat) { size_t saved = g->path.len; while (*pat == '/') { sb_putc(&g->path, '/'); pat++; } if (!*pat) { struct stat st; if (lstat(sb_cstr(&g->path), &st) == 0) g->add(g->ctx, g->path.s); g->path.len = saved; return; } size_t clen = 0; while (pat[clen] && pat[clen] != '/') clen++; const char *rest = pat + clen; if (!has_meta(pat, clen)) { /* A literal component: no need to read the directory. */ for (size_t i = 0; i < clen; i++) { if (pat[i] == '\\' && i + 1 < clen) i++; sb_putc(&g->path, pat[i]); } glob_from(g, rest); g->path.len = saved; return; } size_t dirlen = g->path.len; DIR *dir = opendir(dirlen ? sb_cstr(&g->path) : "."); if (dir) { char *comp = arena_strndup(&scratch, pat, clen); const struct dirent *de; while ((de = readdir(dir)) != nullptr) { const char *name = de->d_name; if (name[0] == '.' && comp[0] != '.' && !(comp[0] == '\\' && comp[1] == '.')) continue; if (!pat_match(comp, name, name + strlen(name))) continue; g->path.len = dirlen; sb_puts(&g->path, name); /* readdir() already named this entry: the last component needs * no lstat(), only a literal tail or a trailing `/` does. */ if (!*rest) g->add(g->ctx, sb_cstr(&g->path)); else glob_from(g, rest); } closedir(dir); } g->path.len = saved; } /** * @brief Pathname expansion. * @param pat Pattern. Quoted characters are backslash-escaped. * @param add Called with each existing path that matches, in any order. * @param ctx Passed through to `add`. */ void glob_expand(const char *pat, void (*add)(void *ctx, const char *path), void *ctx) { globber g = {.add = add, .ctx = ctx}; sb_init(&g.path, &scratch); glob_from(&g, pat); }