summaryrefslogtreecommitdiffhomepage
path: root/src/alias.c
blob: bf1a236c3788a03fdd1d92d30f43dae46c33c768 (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
/**
 * @file alias.c
 * @brief The alias table and the `alias` and `unalias` builtins.
 *
 * Aliases are substituted by the parser, at the command-name position
 * only (see alias_expand() in parser.c).  While the table is empty the
 * parser does not look anything up, so a script that defines no aliases
 * pays nothing for the feature, and because a loop body is parsed once,
 * an alias used inside a loop is not looked up again on each iteration.
 */
#include <stdlib.h>
#include <string.h>

#include "exec.h"
#include "parser.h"

/** @brief Number of hash buckets. Aliases are few, so this is small. */
#define ATAB_SIZE ((size_t)32)

/**
 * @brief The alias hash table.
 */
static alias *atab[ATAB_SIZE];

/** @brief How many aliases exist. The parser's "anything to do?" test. */
int alias_count;

/**
 * @brief Hash an alias name to a bucket index.
 * @param s NUL-terminated name.
 * @return Bucket index in [0, ATAB_SIZE).
 */
static size_t alias_hash(const char *s) {
    unsigned h = 5381;
    while (*s)
        h = h * 33 + (unsigned char)*s++;
    return h % ATAB_SIZE;
}

/**
 * @brief Look up an alias.
 * @param name Candidate command word.
 * @return The alias, or nullptr if `name` is not one.
 */
alias *alias_find(const char *name) {
    for (alias *a = atab[alias_hash(name)]; a; a = a->next) {
        if (!strcmp(a->name, name))
            return a;
    }
    return nullptr;
}

/**
 * @brief Call a function for the name of every alias.
 * @param fn  Callback.
 * @param arg Passed through to the callback.
 */
void alias_each(void (*fn)(const char *name, void *arg), void *arg) {
    for (size_t b = 0; b < ATAB_SIZE; b++) {
        for (const alias *a = atab[b]; a; a = a->next)
            fn(a->name, arg);
    }
}

/**
 * @brief Define or redefine an alias.
 * @param name  Alias name.
 * @param value Replacement text, copied.
 */
void alias_set(const char *name, const char *value) {
    alias *a = alias_find(name);
    if (a) {
        /*
         * The old text may still be the lexer's input if this command line
         * used the alias. Leaking it in that case is the safe choice.
         */
        if (!a->in_use)
            free(a->value);
        a->value = xstrdup(value);
        return;
    }
    a = xmalloc(sizeof *a);
    alias **bucket = &atab[alias_hash(name)];
    *a = (alias){*bucket, xstrdup(name), xstrdup(value), false};
    *bucket = a;
    alias_count++;
}

/**
 * @brief Remove one alias.
 * @param name Alias name.
 * @return false if there was no such alias.
 */
static bool alias_remove(const char *name) {
    for (alias **pa = &atab[alias_hash(name)]; *pa; pa = &(*pa)->next) {
        alias *a = *pa;
        if (strcmp(a->name, name))
            continue;
        *pa = a->next;
        alias_count--;
        if (!a->in_use) { /* otherwise the lexer still reads from it */
            free(a->value);
            free(a->name);
            free(a);
        }
        return true;
    }
    return false;
}

/**
 * @brief Print one alias in a form that can be read back.
 * @param a The alias.
 */
static void alias_print(const alias *a) {
    out_puts(&out1, a->name);
    out_putc(&out1, '=');
    out_quote(&out1, a->value);
    out_putc(&out1, '\n');
}

/** @brief qsort() comparison of two `struct alias *` by name. */
static int alias_cmp(const void *x, const void *y) {
    const alias *const *a = x;
    const alias *const *b = y;
    return strcmp((*a)->name, (*b)->name);
}

/**
 * @brief Is this name acceptable as an alias name?
 *
 * POSIX allows letters, digits and `! % , @ _`. Like other shells zash
 * accepts anything that the lexer would read as one plain word.
 */
static bool alias_name_ok(const char *s, size_t n) {
    if (!n)
        return false;
    for (size_t i = 0; i < n; i++) {
        if (strchr(" \t\n;&|<>()$`\\\"'=", s[i]))
            return false;
    }
    return true;
}

/**
 * @brief The `alias` builtin: `alias [name[=value] ...]`.
 *
 * With no operands, prints every alias in name order.  `name=value`
 * defines an alias. A bare `name` prints it.
 *
 * @return 0, or 1 if a bare name was not an alias.
 */
int builtin_alias(int argc, char **argv) {
    int i = 1;
    if (i < argc && !strcmp(argv[i], "--"))
        i++;
    if (i >= argc) {
        alias **list = xmalloc(((size_t)alias_count + 1) * sizeof *list);
        size_t n = 0;
        for (size_t b = 0; b < ATAB_SIZE; b++) {
            for (alias *a = atab[b]; a; a = a->next)
                list[n++] = a;
        }
        qsort(list, n, sizeof *list, alias_cmp);
        for (size_t k = 0; k < n; k++)
            alias_print(list[k]);
        free(list);
        return 0;
    }
    int status = 0;
    for (; i < argc; i++) {
        const char *eq = strchr(argv[i], '=');
        if (eq && eq != argv[i]) {
            size_t nlen = (size_t)(eq - argv[i]);
            if (!alias_name_ok(argv[i], nlen)) {
                sh_warn("alias: %s: bad alias name", argv[i]);
                status = 1;
                continue;
            }
            alias_set(arena_strndup(&scratch, argv[i], nlen), eq + 1);
        } else {
            const alias *a = alias_find(argv[i]);
            if (a) {
                alias_print(a);
            } else {
                sh_warn("alias: %s: not found", argv[i]);
                status = 1;
            }
        }
    }
    return status;
}

/**
 * @brief The `unalias` builtin: `unalias name ...` or `unalias -a`.
 * @return 0, or 1 if a name was not an alias.
 */
int builtin_unalias(int argc, char **argv) {
    int status = 0;
    for (int i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "-a")) {
            for (size_t b = 0; b < ATAB_SIZE; b++) {
                while (atab[b])
                    alias_remove(atab[b]->name);
            }
        } else if (!strcmp(argv[i], "--")) {
            continue;
        } else if (!alias_remove(argv[i])) {
            sh_warn("unalias: %s: not found", argv[i]);
            status = 1;
        }
    }
    return status;
}