aboutsummaryrefslogtreecommitdiffhomepage
path: root/src-cslul/tree.c
blob: 547a37d7938b2294ec129659cf866e879b606852 (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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391

/*

  tree.c -- AVL tree map for hashed items

  Copyright © 2021-2024 Samuel Lidén Borell <samuel@kodafritt.se>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

#include "internal.h"
#include <assert.h>
#include <string.h>
#define INTERR_TREE(errnum) MAKE_INTERR(errnum, INTERRBASE_TREE)

#define RDZERO  0
#define RDMINUS 1
#define RDPLUS  2

/** Simple locale-insensitive strcasecmp, for equal-length strings,
    that supports a-zA-Z0-9._/ */
int silly_casestrcmp(const char *a, const char *b, size_t len)
{
    while (len--) {
        char ca = *(a++) | 0x20;
        char cb = *(b++) | 0x20;
        if (ca == cb) continue;
        else if (ca < cb) return -1;
        else return 1;
    }
    return 0;
}

const char *node_nameptr(const struct TreeNode *n)
{
    return (n->length <= PTRSIZE ? n->name.copy : n->name.ptr);
}

int ident_equals(const struct TreeNode *n, const char *s, size_t len)
{
    if (n->length != len) return 0;
    return !memcmp(node_nameptr(n), s, len);
}

/**
 * Compares the node a with the sought value b
 * \return -1 if b is larger, 0 if equal, 1 if a is larger
 */
static int ncmp(const struct CSlul *ctx, const struct TreeNode *a,
                HashCode bhash, uint32 blen, const char *bname)
{
    uint32 alen;
    /* Sort by hash first */
    if (a->hashcode < bhash) return -1;
    if (a->hashcode > bhash) return 1;
    /* Sort by length second */
    alen = a->length;
    if (alen < blen) return -1;
    if (alen > blen) return 1;
    /* Sort by contents as a last resort */
    if (!ctx->case_insens) {
        return memcmp(node_nameptr(a), bname, alen);
    } else {
        return silly_casestrcmp(node_nameptr(a), bname, alen);
    }
}

/**
 * Looks up a node.
 *
 * \return A pointer the to node if it existed, or NULL if not found.
 */
struct TreeNode *tree_search(const struct CSlul *ctx,
                             const struct TreeNode *root,
                             HashCode h, uint32 len, const char *name)
{
    const struct TreeNode *n = root;
    while (n) {
        int cmp = ncmp(ctx, n, h, len, name);
        if (cmp == 0) return (struct TreeNode *)n;
        else if (cmp > 0) n = n->lower;
        else n = n->higher;
    }
    return NULL;
}

struct TreeNode *tree_search_node(const struct CSlul *ctx,
                                  const struct TreeNode *root,
                                  const struct TreeNode *n)
{
    return tree_search(ctx, root, n->hashcode, n->length, node_nameptr(n));
}

static struct TreeNode *rotate_left(struct TreeNode *n)
{
    struct TreeNode *higher = n->higher;
    n->higher = higher->lower;
    higher->lower = n;
    n->rankdelta = higher->rankdelta = RDZERO;
    return higher;
}

static struct TreeNode *rotate_right(struct TreeNode *n)
{
    struct TreeNode *lower = n->lower;
    n->lower = lower->higher;
    lower->higher = n;
    n->rankdelta = lower->rankdelta = RDZERO;
    return lower;
}

static struct TreeNode *rotate_leftright(struct TreeNode *base)
{
    struct TreeNode *l = base->lower;    /*       ___________b_   */
    struct TreeNode *lh = l->higher;     /*    __l____         h  */
    base->lower = lh->higher;            /*  ll       _lh_        */
    l->higher = lh->lower;               /*        lhl    lhh     */
    lh->higher = base;
    lh->lower = l;                       /*       becomes         */
    if (lh->rankdelta == RDMINUS) {
        base->rankdelta = RDPLUS;        /*       _____lh____     */
        l->rankdelta = RDZERO;           /*    __l__        _b_   */
    } else {                             /*  ll     lhl  lhh   h  */
        base->rankdelta = RDZERO;
        l->rankdelta = RDMINUS;
    }
    lh->rankdelta = RDZERO;
    return lh;
}

/** Performs a right-left rotation and returns the new subtree root */
static struct TreeNode *rotate_rightleft(struct TreeNode *base)
{
    struct TreeNode *h = base->higher;   /*   _b___________       */
    struct TreeNode *hl = h->lower;      /*  l         ____h__    */
    base->higher = hl->lower;            /*         _hl_      hh  */
    h->lower = hl->higher;               /*      hll    hlh       */
    hl->lower = base;
    hl->higher = h;                      /*       becomes         */
    if (hl->rankdelta == RDPLUS) {
        base->rankdelta = RDMINUS;       /*     ____hl_____       */
        h->rankdelta = RDZERO;           /*   _b_        __h__    */
    } else {                             /*  l   hll  hlh    hhh  */
        base->rankdelta = RDZERO;
        h->rankdelta = RDPLUS;
    }
    hl->rankdelta = RDZERO;
    return hl;
}

static struct TreeNode *create_node(struct CSlul *ctx,
                                    HashCode h, uint32 len, const char *name,
                                    struct TreeNode *newnode, size_t newsize)
{
    if (!newnode) {
        assert(len != USE_EXISTING);
        newnode = aallocp(ctx, newsize);
        if (!newnode) return NULL;
        if (newsize > sizeof(struct TreeNode)) {
            memset(newnode+1, 0, newsize - sizeof(struct TreeNode));
            #ifdef SLUL_DEBUG
            /* Fill the middle bytes (assuming 32 bit) to make sure we don't
               create a "valid", but not standards compliant, NULL pointer.
               (This works on 64 bit platforms too) */
            {
                char *p = (char*)&newnode[1];
                char *end = (char*)newnode +
                                (newsize - sizeof(struct TreeNode) + 1);
                for (; p < end; p++) {
                    uintptr modulo = (uintptr)p & 0x3;
                    if (modulo == 1 || modulo == 2) *p = 0x10;
                }
            }
            #endif
        }
    }
    newnode->lower = NULL;
    newnode->higher = NULL;
    if (len != USE_EXISTING) {
        assert(name != NULL);
        newnode->hashcode = h;
        newnode->rankdelta = RDZERO;
        newnode->state = TNS_INITIAL;
        newnode->length = len;
        newnode->line = ctx->tokline;
        newnode->column = ctx->tokcolumn;
        newnode->is_new = 1;
        newnode->filename = ctx->current_filename;
        if (len <= PTRSIZE) {
            memcpy(newnode->name.copy, name, len);
        } else {
            if (!(newnode->name.ptr = aalloc_memzdup(ctx, name, len)))
                return NULL;
        }
    } else {
        newnode->rankdelta = RDZERO;
        newnode->is_new = 1;
    }
    PROTECT_STRUCT(*newnode);
    return newnode;
}

/**
 * Looks up or inserts a node. If newnode is NULL, the node is allocated
 * if it does not exist.
 *
 * If len is set to USE_EXISTING, then the name, length and hashcode are
 * taken from newnode (which must be non-NULL)
 *
 * The is_new field is set to 0 if the node already existed, or
 * 1 if it was just inserted.
 *
 * \return A pointer the to node, or NULL is returned on memory
 *         allocation failure.
 */
struct TreeNode *tree_insert(struct CSlul *ctx, struct TreeNode **root,
                             HashCode h, uint32 len, const char *name,
                             struct TreeNode *newnode, size_t newsize)
{
    struct TreeNode *path[MAXDEPTH];
    struct TreeNode **lastp;
    struct TreeNode *n, *rotroot;
    struct TreeNode **inspoint;
    uint32 length;
    short depth;

    if (!*root) {
        n = create_node(ctx, h, len, name, newnode, newsize);
        if (!n) return NULL;
        *root = n;
        return n;
    }
    length = len;
    if (len == USE_EXISTING) {
        h = newnode->hashcode;
        length = newnode->length;
        name = node_nameptr(newnode);
    }
    lastp = &path[0];
    depth = 0;
    n = *root;
    /* Insert */
    for (;;) {
        int cmp;
        if (++depth >= MAXDEPTH) goto too_deep;
        *lastp = n;
        cmp = ncmp(ctx, n, h, length, name);
        if (cmp == 0) {
            n->is_new = 0;
            return n;
        } else if (cmp > 0) {
            inspoint = &n->lower;
            n = n->lower;
        } else {
            inspoint = &n->higher;
            n = n->higher;
        }
        if (!n) break;
        lastp++;
    }
    n = create_node(ctx, h, len, name, newnode, newsize);
    if (!n) return NULL; /* out of memory */
    *inspoint = n;
    newnode = n;
    /* Rebalance if necessary.
       This is done by backtracking through the path. */
    for (;;) { /* while depth > 0 */
        struct TreeNode *p = *lastp;
        assert(n->lower  || n->rankdelta != RDMINUS);
        assert(n->higher || n->rankdelta != RDPLUS);
        if (p->lower == n) { /* new node is in left/lower subtree */
            if (p->rankdelta == RDMINUS) {
                if (n->rankdelta == RDPLUS) {
                    rotroot = rotate_leftright(p);
                } else {
                    rotroot = rotate_right(p);
                }
            } else if (p->rankdelta == RDPLUS) {
                p->rankdelta = RDZERO;
                break;
            } else {
                p->rankdelta = RDMINUS;
                goto continue_up;
            }
        } else { /* new node is in right/higher subtree */
            assert(p->higher == n);
            if (p->rankdelta == RDPLUS) {
                if (n->rankdelta == RDMINUS) {
                    rotroot = rotate_rightleft(p);
                } else {
                    rotroot = rotate_left(p);
                }
            } else if (p->rankdelta == RDMINUS) {
                p->rankdelta = RDZERO;
                break;
            } else {
                p->rankdelta = RDPLUS;
                goto continue_up;
            }
        }
        if (depth <= 1) *root = rotroot;
        else if (lastp[-1]->lower == p) {
            lastp[-1]->lower = rotroot;
        } else {
            assert(lastp[-1]->higher == p);
            lastp[-1]->higher = rotroot;
        }
        break;
      continue_up:
        if (!--depth) break;
        lastp--;
        n = p;
    }
    return newnode;
  too_deep:
    error_linecol(ctx, CSLUL_E_TREETOODEEP, 0, 0);
    return NULL;
}

/**
 * Initializes an iterator and points it to the lowest/first node in the tree.
 */
void tree_iter_init(struct TreeIter *iter, struct TreeNode *root)
{
    struct TreeNode **stack = &iter->stack[0];
    struct TreeNode *n = root;
    short depth = -1;
    for (;;) {
        *stack = n;
        if (!n) break;
        depth++;
        n = n->lower;
        if (!n) break;
        stack++;
        assert(depth < MAXDEPTH);
    }
    iter->depth = depth;

}

/**
 * Iterates through the nodes in a tree. Each call returns the next node.
 *
 * \param iter Iterator
 * \param nodeptr This pointer is updated to point to the next node
 * \return 1 if a node was returned
 */
int tree_iter_next(struct TreeIter *iter, struct TreeNode **nodeptr)
{
    struct TreeNode **stack;
    struct TreeNode *n;
    short depth = iter->depth;
    if (depth < 0) return 0;
    stack = &iter->stack[depth];
    n = *stack;
    *nodeptr = n;
    /* Determine next node */
    if (n->higher) {
        n = n->higher;
        /* Go to the lowest node in the subtree */
        for (;;) {
            *stack = n;
            n = n->lower;
            if (!n) break;
            stack++;
            depth++;
            assert(depth < MAXDEPTH);
        }
    } else {
        /* Go one level up */
        depth--;
    }
    iter->depth = depth;
    return 1;
}