summaryrefslogtreecommitdiffhomepage
path: root/src/pattern.c
blob: 0dabc155c9905e079d3a89a08197ad0f76c65452 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
 * @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 <ctype.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>

#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) {
    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;
}

/**
 * @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);
            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);
}