tools/spinel_rbs_extract.c in matz/spinel

tools/spinel_rbs_extract.c 940 lines · 37.6 KB · c
1
/* spinel_rbs_extract -- walk a directory for .rbs files and emit a
2
 * seed file for spinel_analyze's --rbs path.
3
 *
4
 * Reads RBS source through the vendored rbs C parser (vendor/rbs/) and
5
 * emits a tiny line-oriented seed format consumed by load_rbs_seeds /
6
 * apply_rbs_seeds in spinel_analyze.rb. Per the design conversation,
7
 * this is *advisory* seeding: only a subset of RBS maps to spinel's
8
 * type vocabulary, and anything outside the subset is silently
9
 * skipped. The analyzer's existing inference still runs on top.
10
 *
11
 * Subset supported (everything else dropped without warning):
12
 *   - Primitives: Integer, Float, String, Symbol, TrueClass,
13
 *     FalseClass, NilClass, bool, nil, void (→ nil for returns)
14
 *   - Nominal class instances → obj_<QualifiedName>
15
 *   - Array[T] where T is in subset → str_array / int_array /
16
 *     float_array / sym_array / obj_X_ptr_array / poly_array
17
 *   - Hash[K, V] → str_int_hash / sym_str_hash / str_poly_hash etc.
18
 *   - Optional T (T?) → <subset>?    (recursive)
19
 *   - Union T | nil → T?    (any other union → skip)
20
 *
21
 * Dropped: generics with variables, overloads beyond #1, blocks,
22
 * proc types, intersections, records, tuples, interfaces, literal
23
 * types, type aliases, self / instance / class / top / bottom /
24
 * any types.
25
 *
26
 * Usage:
27
 *   spinel_rbs_extract DIR [DIR ...]
28
 *
29
 * Walks each DIR recursively for *.rbs files, writes seed lines to
30
 * stdout. The `spinel` wrapper captures stdout to a tmpfile and
31
 * passes it as ARGV[2] to spinel_analyze. */
32
33
#include <stdio.h>
34
#include <stdlib.h>
35
#include <string.h>
36
#include <dirent.h>
37
#include <sys/stat.h>
38
#include <fcntl.h>
39
#include <unistd.h>
40
41
#include "rbs/parser.h"
42
#include "rbs/ast.h"
43
#include "rbs/util/rbs_encoding.h"
44
#include "rbs/util/rbs_constant_pool.h"
45
46
/* ---- small string buffer ----------------------------------- */
47
48
typedef struct {
49
    char *buf;
50
    size_t len;
51
    size_t cap;
52
} sbuf_t;
53
54
static void sbuf_init(sbuf_t *s) { s->buf = NULL; s->len = 0; s->cap = 0; }
55
static void sbuf_free(sbuf_t *s) { free(s->buf); s->buf = NULL; s->len = 0; s->cap = 0; }
56
57
static void sbuf_grow(sbuf_t *s, size_t need) {
58
    if (s->cap >= need) return;
59
    size_t ncap = s->cap == 0 ? 64 : s->cap;
60
    while (ncap < need) ncap *= 2;
61
    char *nbuf = (char *) realloc(s->buf, ncap);
62
    if (nbuf == NULL) {
63
        fprintf(stderr, "spinel_rbs_extract: out of memory\n");
64
        exit(1);
65
    }
66
    s->buf = nbuf;
67
    s->cap = ncap;
68
}
69
70
static void sbuf_append(sbuf_t *s, const char *src, size_t n) {
71
    sbuf_grow(s, s->len + n + 1);
72
    memcpy(s->buf + s->len, src, n);
73
    s->len += n;
74
    s->buf[s->len] = '\0';
75
}
76
77
static void sbuf_append_cstr(sbuf_t *s, const char *src) {
78
    sbuf_append(s, src, strlen(src));
79
}
80
81
static void sbuf_set(sbuf_t *s, const char *src, size_t n) {
82
    s->len = 0;
83
    sbuf_append(s, src, n);
84
}
85
86
/* ---- known-name set (issue #656) ---------------------------- */
87
88
/* Set of qualified class/module names defined across all .rbs files
89
 * traversed. Populated by collect_decl_names in a pre-pass before
90
 * the emit pass; consulted by resolve_unqualified_name so a bare
91
 * `Article` written inside `module Views; module Articles` walks
92
 * the lexical chain (Views_Articles_Article, Views_Article,
93
 * Article) and picks the first match. Without the set we either
94
 * always prepend the enclosing scope (wrong when the referent is
95
 * top-level) or never prepend (wrong for the sibling-in-module
96
 * case). Issue #656. */
97
static char **known_names = NULL;
98
static size_t known_names_len = 0;
99
static size_t known_names_cap = 0;
100
101
static void known_names_add(const char *name, size_t n) {
102
    /* dedupe (linear; n is small in practice) */
103
    for (size_t i = 0; i < known_names_len; i++) {
104
        if (strlen(known_names[i]) == n && memcmp(known_names[i], name, n) == 0) return;
105
    }
106
    if (known_names_len >= known_names_cap) {
107
        size_t ncap = known_names_cap == 0 ? 32 : known_names_cap * 2;
108
        char **nbuf = (char **) realloc(known_names, ncap * sizeof(char *));
109
        if (nbuf == NULL) {
110
            fprintf(stderr, "spinel_rbs_extract: out of memory\n");
111
            exit(1);
112
        }
113
        known_names = nbuf;
114
        known_names_cap = ncap;
115
    }
116
    char *copy = (char *) malloc(n + 1);
117
    if (copy == NULL) {
118
        fprintf(stderr, "spinel_rbs_extract: out of memory\n");
119
        exit(1);
120
    }
121
    memcpy(copy, name, n);
122
    copy[n] = '\0';
123
    known_names[known_names_len++] = copy;
124
}
125
126
static bool known_names_has(const char *name) {
127
    for (size_t i = 0; i < known_names_len; i++) {
128
        if (strcmp(known_names[i], name) == 0) return true;
129
    }
130
    return false;
131
}
132
133
/* ---- name lookup via rbs constant pool --------------------- */
134
135
/* Read the bytes for a constant_id out of the parser's pool into a sbuf.
136
 * Resets the buffer first. Result is NUL-terminated. */
137
static void name_of_symbol(rbs_parser_t *p, rbs_ast_symbol_t *sym, sbuf_t *out) {
138
    out->len = 0;
139
    if (sym == NULL) { sbuf_append(out, "", 0); return; }
140
    rbs_constant_t *c = rbs_constant_pool_id_to_constant(&p->constant_pool, sym->constant_id);
141
    if (c == NULL) { sbuf_append(out, "", 0); return; }
142
    sbuf_set(out, (const char *) c->start, c->length);
143
}
144
145
/* Qualified name from a type_name: namespace path joined with "_"
146
 * plus the leaf symbol. Spinel registers nested classes with "_"
147
 * separators (e.g. `module Tep; class Json` → `Tep_Json` in
148
 * @cls_names; `Tep::Security::Cors` → `Tep_Security_Cors`). RBS
149
 * spells them with `::`, so we translate here. */
150
static void name_of_type_name(rbs_parser_t *p, rbs_type_name_t *tn, sbuf_t *out) {
151
    out->len = 0;
152
    if (tn == NULL) return;
153
    if (tn->rbs_namespace != NULL && tn->rbs_namespace->path != NULL) {
154
        rbs_node_list_node_t *cur = tn->rbs_namespace->path->head;
155
        while (cur != NULL) {
156
            if (cur->node->type == RBS_AST_SYMBOL) {
157
                rbs_ast_symbol_t *seg = (rbs_ast_symbol_t *) cur->node;
158
                rbs_constant_t *c = rbs_constant_pool_id_to_constant(&p->constant_pool, seg->constant_id);
159
                if (c != NULL) {
160
                    sbuf_append(out, (const char *) c->start, c->length);
161
                    sbuf_append_cstr(out, "_");
162
                }
163
            }
164
            cur = cur->next;
165
        }
166
    }
167
    rbs_constant_t *c = rbs_constant_pool_id_to_constant(&p->constant_pool, tn->name->constant_id);
168
    if (c != NULL) {
169
        sbuf_append(out, (const char *) c->start, c->length);
170
    }
171
}
172
173
/* ---- subset type mapping ----------------------------------- */
174
175
/* Categorize a primitive name to a spinel scalar tag. NULL on
176
 * non-primitive (caller treats as nominal `obj_<Name>`). */
177
static const char *primitive_tag(const char *name, size_t len) {
178
    if (len == 7 && memcmp(name, "Integer", 7) == 0) return "int";
179
    if (len == 5 && memcmp(name, "Float", 5) == 0)   return "float";
180
    if (len == 6 && memcmp(name, "String", 6) == 0)  return "string";
181
    if (len == 6 && memcmp(name, "Symbol", 6) == 0)  return "symbol";
182
    if (len == 9 && memcmp(name, "TrueClass", 9) == 0)  return "bool";
183
    if (len == 10 && memcmp(name, "FalseClass", 10) == 0) return "bool";
184
    if (len == 8 && memcmp(name, "NilClass", 8) == 0)   return "nil";
185
    return NULL;
186
}
187
188
/* Map a typed element (already mapped to a spinel scalar/obj tag) into
189
 * the array variant name spinel uses. NULL if unsupported. */
190
static const char *array_tag_for_elem(const char *elem) {
191
    if (strcmp(elem, "int") == 0)    return "int_array";
192
    if (strcmp(elem, "float") == 0)  return "float_array";
193
    if (strcmp(elem, "string") == 0) return "str_array";
194
    if (strcmp(elem, "symbol") == 0) return "sym_array";
195
    if (strncmp(elem, "obj_", 4) == 0) {
196
        /* obj_Foo → obj_Foo_ptr_array (heuristic, mirrors spinel's
197
         * array-of-objects shape). Caller must append _ptr_array. */
198
        return NULL;
199
    }
200
    return "poly_array";
201
}
202
203
/* Map (K, V) of a Hash[K, V] to spinel's hash variant name. NULL on
204
 * unsupported combinations. */
205
static const char *hash_tag_for_kv(const char *k, const char *v) {
206
    if (strcmp(k, "string") == 0) {
207
        if (strcmp(v, "int") == 0)    return "str_int_hash";
208
        if (strcmp(v, "string") == 0) return "str_str_hash";
209
        return "str_poly_hash";
210
    }
211
    if (strcmp(k, "symbol") == 0) {
212
        if (strcmp(v, "int") == 0)    return "sym_int_hash";
213
        if (strcmp(v, "string") == 0) return "sym_str_hash";
214
        return "sym_poly_hash";
215
    }
216
    if (strcmp(k, "int") == 0) {
217
        if (strcmp(v, "string") == 0) return "int_str_hash";
218
    }
219
    /* `Hash[untyped, untyped]` (and any leftover combination where
220
     * one side is untyped without a matching concrete variant
221
     * above) — map to bare "poly" rather than poly_poly_hash. The
222
     * analyzer treats this slot as sp_RbVal (tagged union), which
223
     * matches how a top-level `def f(h)` with no caller signal
224
     * settles. Picking poly_poly_hash here forced a specific tagged
225
     * struct pointer (sp_PolyPolyHash *) that doesn't accept the
226
     * sp_RbVal arguments callers actually pass through poly
227
     * narrowing branches (e.g. `v.is_a?(Hash) ? f(v) : v`). Issue
228
     * #613. */
229
    if (strcmp(k, "poly") == 0 || strcmp(v, "poly") == 0) {
230
        return "poly";
231
    }
232
    return NULL;
233
}
234
235
/* Forward decl. Write a spinel type tag into out; return true on
236
 * success, false to signal "out of subset, caller should skip".
237
 *
238
 * `enclosing_scope` (may be NULL/"") is the qualified name of the
239
 * declaration we're currently inside, e.g. `ActiveRecord` while
240
 * traversing members of `module ActiveRecord; class RecordInvalid`.
241
 * Used to resolve unqualified nominal type references: `Base` inside
242
 * `ActiveRecord` becomes `obj_ActiveRecord_Base`. Without this, the
243
 * extractor emits `obj_Base` and the seed misses any class actually
244
 * stored at the qualified name in spinel's tables. */
245
static bool map_type(rbs_parser_t *p, rbs_node_t *node,
246
                     const char *enclosing_scope, sbuf_t *out);
247
248
/* True if the type_name was written unqualified in source (no `::`
249
 * separators, no leading `::`). RBS exposes this as an empty
250
 * namespace path. */
251
static bool type_name_is_unqualified(rbs_type_name_t *tn) {
252
    if (tn == NULL || tn->rbs_namespace == NULL) return true;
253
    if (tn->rbs_namespace->path == NULL) return true;
254
    return tn->rbs_namespace->path->length == 0;
255
}
256
257
/* Map a ClassInstance node. Handles Array[T], Hash[K,V], primitives,
258
 * and nominal classes. */
259
static bool map_class_instance(rbs_parser_t *p, rbs_types_class_instance_t *ci,
260
                                const char *enclosing_scope, sbuf_t *out) {
261
    sbuf_t name;
262
    sbuf_init(&name);
263
    name_of_type_name(p, ci->name, &name);
264
265
    /* Primitive lookup uses the leaf name only. After name_of_type_name
266
     * the separator is "_" (translated from RBS's "::"), so the leaf
267
     * is the substring after the last "_". Conservative: only treat
268
     * the trailing segment as the primitive name; a class actually
269
     * named `Foo_Integer` would shadow the primitive, but that's
270
     * extremely unlikely in practice. */
271
    const char *primitive = NULL;
272
    {
273
        const char *leaf = name.buf;
274
        size_t leaf_len = name.len;
275
        for (size_t i = 0; i < name.len; i++) {
276
            if (name.buf[i] == '_') {
277
                leaf = name.buf + i + 1;
278
                leaf_len = name.len - (i + 1);
279
            }
280
        }
281
        primitive = primitive_tag(leaf, leaf_len);
282
    }
283
284
    size_t argc = ci->args != NULL ? ci->args->length : 0;
285
286
    if (primitive != NULL && argc == 0) {
287
        sbuf_set(out, primitive, strlen(primitive));
288
        sbuf_free(&name);
289
        return true;
290
    }
291
292
    /* Array[T] */
293
    if (name.len >= 5 && strcmp(name.buf + name.len - 5, "Array") == 0 && argc == 1) {
294
        sbuf_t elem;
295
        sbuf_init(&elem);
296
        if (!map_type(p, ci->args->head->node, enclosing_scope, &elem)) {
297
            sbuf_free(&elem);
298
            sbuf_free(&name);
299
            return false;
300
        }
301
        if (strncmp(elem.buf, "obj_", 4) == 0) {
302
            sbuf_set(out, elem.buf, elem.len);
303
            sbuf_append_cstr(out, "_ptr_array");
304
        }
305
else {
306
            const char *tag = array_tag_for_elem(elem.buf);
307
            if (tag == NULL) {
308
                sbuf_free(&elem);
309
                sbuf_free(&name);
310
                return false;
311
            }
312
            sbuf_set(out, tag, strlen(tag));
313
        }
314
        sbuf_free(&elem);
315
        sbuf_free(&name);
316
        return true;
317
    }
318
319
    /* Hash[K, V] */
320
    if (name.len >= 4 && strcmp(name.buf + name.len - 4, "Hash") == 0 && argc == 2) {
321
        sbuf_t k, v;
322
        sbuf_init(&k); sbuf_init(&v);
323
        if (!map_type(p, ci->args->head->node, enclosing_scope, &k)
324
            || !map_type(p, ci->args->head->next->node, enclosing_scope, &v)) {
325
            sbuf_free(&k); sbuf_free(&v); sbuf_free(&name); return false;
326
        }
327
        const char *tag = hash_tag_for_kv(k.buf, v.buf);
328
        sbuf_free(&k); sbuf_free(&v);
329
        if (tag == NULL) { sbuf_free(&name); return false; }
330
        sbuf_set(out, tag, strlen(tag));
331
        sbuf_free(&name);
332
        return true;
333
    }
334
335
    /* Generic with arity > 0 of an unrecognized container → skip. */
336
    if (argc > 0) {
337
        sbuf_free(&name);
338
        return false;
339
    }
340
341
    /* Nominal class instance: emit obj_<QualifiedName>. Three cases:
342
     *
343
     * 1. Source wrote `::Const` (absolute): use the bare name as-is,
344
     *    never prepend the enclosing scope (issue #656).
345
     * 2. Source wrote unqualified `Const` and we're inside a class/
346
     *    module scope: walk the lexical chain from innermost outward
347
     *    and pick the first qualified name present in known_names.
348
     *    Fall back to bare when no candidate matches (matches Ruby's
349
     *    `::Const` resolution at top-level).
350
     * 3. Source wrote qualified `A::B::C`: use as-is (name already
351
     *    contains the full path via name_of_type_name).
352
     */
353
    sbuf_set(out, "obj_", 4);
354
    bool absolute = (ci->name != NULL && ci->name->rbs_namespace != NULL
355
                     && ci->name->rbs_namespace->absolute);
356
    if (!absolute && enclosing_scope != NULL && enclosing_scope[0] != '\0'
357
        && type_name_is_unqualified(ci->name)) {
358
        /* Walk the lexical chain: try `<chain>_<name>` for each suffix
359
         * of enclosing_scope (innermost outward), then top-level. */
360
        sbuf_t candidate;
361
        sbuf_init(&candidate);
362
        const char *scope_end = enclosing_scope + strlen(enclosing_scope);
363
        const char *cur = enclosing_scope;
364
        bool resolved = false;
365
        while (cur != NULL && cur < scope_end) {
366
            candidate.len = 0;
367
            sbuf_append(&candidate, cur, scope_end - cur);
368
            sbuf_append_cstr(&candidate, "_");
369
            sbuf_append(&candidate, name.buf, name.len);
370
            if (known_names_has(candidate.buf)) {
371
                sbuf_append(out, candidate.buf, candidate.len);
372
                resolved = true;
373
                break;
374
            }
375
            /* Step to the next inner namespace by skipping past the
376
             * next "_". `Views_Articles_Helpers` -> `Articles_Helpers`
377
             * -> `Helpers` -> done. */
378
            const char *next = (const char *) memchr(cur, '_', scope_end - cur);
379
            if (next == NULL) break;
380
            cur = next + 1;
381
        }
382
        if (!resolved) {
383
            /* Top-level fallback: emit bare name. */
384
            sbuf_append(out, name.buf, name.len);
385
        }
386
        sbuf_free(&candidate);
387
    }
388
else {
389
        sbuf_append(out, name.buf, name.len);
390
    }
391
    sbuf_free(&name);
392
    return true;
393
}
394
395
static bool map_type(rbs_parser_t *p, rbs_node_t *node,
396
                     const char *enclosing_scope, sbuf_t *out) {
397
    if (node == NULL) return false;
398
    switch (node->type) {
399
        case RBS_TYPES_BASES_BOOL:
400
            sbuf_set(out, "bool", 4);
401
            return true;
402
        case RBS_TYPES_BASES_NIL:
403
            sbuf_set(out, "nil", 3);
404
            return true;
405
        case RBS_TYPES_BASES_VOID:
406
            /* void only appears as a return type; spinel uses "nil"
407
             * (which void-returning methods discard). */
408
            sbuf_set(out, "nil", 3);
409
            return true;
410
        case RBS_TYPES_BASES_ANY:
411
            /* `untyped` in RBS == anything. Spinel's nearest is poly
412
             * (sp_RbVal — tagged union). Hash[untyped, untyped] uses
413
             * this in hash_tag_for_kv to land on poly_poly_hash. */
414
            sbuf_set(out, "poly", 4);
415
            return true;
416
        case RBS_TYPES_CLASS_INSTANCE:
417
            return map_class_instance(p, (rbs_types_class_instance_t *) node, enclosing_scope, out);
418
        case RBS_TYPES_OPTIONAL: {
419
            rbs_types_optional_t *opt = (rbs_types_optional_t *) node;
420
            sbuf_t inner;
421
            sbuf_init(&inner);
422
            if (!map_type(p, opt->type, enclosing_scope, &inner)) { sbuf_free(&inner); return false; }
423
            /* Avoid double-?: nil? → just nil; obj_Foo?? → obj_Foo? */
424
            if (inner.len > 0 && inner.buf[inner.len - 1] == '?') {
425
                sbuf_set(out, inner.buf, inner.len);
426
            }
427
else if (inner.len == 3 && memcmp(inner.buf, "nil", 3) == 0) {
428
                sbuf_set(out, "nil", 3);
429
            }
430
else {
431
                sbuf_set(out, inner.buf, inner.len);
432
                sbuf_append_cstr(out, "?");
433
            }
434
            sbuf_free(&inner);
435
            return true;
436
        }
437
        case RBS_TYPES_UNION: {
438
            /* `T | nil` (the nilable shape) maps to `T?`. Every other
439
             * union has no single concrete C representation, so it
440
             * maps to poly (sp_RbVal, the tagged union) -- the same
441
             * target `untyped` uses. This boxes the value correctly.
442
             *
443
             * Previously any non-`T | nil` union returned false, which
444
             * dropped the *entire* method seed (the caller bails on a
445
             * false return type), letting inference collapse e.g.
446
             * {int, string} to a single C type and mis-compile
447
             * heterogeneous returns (matz/spinel#1255). Mapping to poly
448
             * is the faithful choice: spinel's only representation for
449
             * "one of several incompatible types" is the tagged union.
450
             *
451
             * This touches only the RBS-seed layer. The self-host build
452
             * ships no `.rbs`, so the inference-level unify_return_type
453
             * heuristic (load-bearing for stage-2) is unaffected. */
454
            rbs_types_union_t *u = (rbs_types_union_t *) node;
455
            if (u->types != NULL && u->types->length == 2) {
456
                rbs_node_t *a = u->types->head->node;
457
                rbs_node_t *b = u->types->head->next->node;
458
                rbs_node_t *t = NULL;
459
                if (a->type == RBS_TYPES_BASES_NIL) t = b;
460
                else if (b->type == RBS_TYPES_BASES_NIL) t = a;
461
                if (t != NULL) {
462
                    sbuf_t inner;
463
                    sbuf_init(&inner);
464
                    if (map_type(p, t, enclosing_scope, &inner)) {
465
                        sbuf_set(out, inner.buf, inner.len);
466
                        if (inner.len == 0 || inner.buf[inner.len - 1] != '?') {
467
                            sbuf_append_cstr(out, "?");
468
                        }
469
                        sbuf_free(&inner);
470
                        return true;
471
                    }
472
                    /* `T | nil` where T is itself out-of-subset →
473
                     * fall through to poly below. */
474
                    sbuf_free(&inner);
475
                }
476
            }
477
            sbuf_set(out, "poly", 4);
478
            return true;
479
        }
480
        default:
481
            /* Out of subset: Self / Top / Bottom / Any / Instance /
482
             * Class / Block / Function / Interface / Intersection /
483
             * Literal / Proc / Record / RecordFieldType / Tuple /
484
             * UntypedFunction / Variable / Alias. */
485
            return false;
486
    }
487
}
488
489
/* ---- emit one method signature ----------------------------- */
490
491
/* Pick the seed-line keyword from rbs's method-definition kind.
492
 * `meth` lands in the instance table (@cls_meth_*), `cmeth` in the
493
 * class table (@cls_cmeth_*). SINGLETON_INSTANCE (def self?.foo)
494
 * emits both so seed_class_method on the analyzer side hits whichever
495
 * the source actually defined. */
496
static void emit_method(rbs_parser_t *p, rbs_ast_members_method_definition_t *m,
497
                        const char *enclosing_scope, FILE *out) {
498
    if (m->overloads == NULL || m->overloads->head == NULL) return;
499
    /* Only the first overload; multiple overloads are out of subset
500
     * (spinel can't pick between them deterministically). */
501
    rbs_node_t *first = m->overloads->head->node;
502
    if (first->type != RBS_AST_MEMBERS_METHOD_DEFINITION_OVERLOAD) return;
503
    rbs_ast_members_method_definition_overload_t *ov =
504
        (rbs_ast_members_method_definition_overload_t *) first;
505
506
    if (ov->method_type == NULL || ov->method_type->type != RBS_METHOD_TYPE) return;
507
    rbs_method_type_t *mt = (rbs_method_type_t *) ov->method_type;
508
    /* type_params on the method (generics) → can't be represented;
509
     * skip the signature rather than emit a misleading one. */
510
    if (mt->type_params != NULL && mt->type_params->length > 0) return;
511
    if (mt->type == NULL || mt->type->type != RBS_TYPES_FUNCTION) {
512
        /* untyped_function or proc → out of subset. */
513
        return;
514
    }
515
    rbs_types_function_t *fn = (rbs_types_function_t *) mt->type;
516
517
    /* Out-of-subset shapes: rest-positional / rest-keyword / optional
518
     * or trailing positionals. These break the fixed-arity contract
519
     * the seed format expects (one ptype slot per Ruby def param).
520
     * Required + optional keywords ARE handled — we walk them in
521
     * insertion order (head/next linked list; rbs_hash_set appends
522
     * to tail, matching RBS source order) and append the value types
523
     * to the ptype list after the required positionals. The arity
524
     * lines up with the Ruby def order spinel's collect_all sees.
525
     *
526
     * NOTE: rbs_hash_t.length is not incremented by rbs_hash_set
527
     * (upstream rbs/ast.c#rbs_hash_set inserts into head/tail without
528
     * updating length). Detect emptiness via `head == NULL`, not via
529
     * `length`. Same applies in the walking code below.
530
     *
531
     * Positional rbs_node_list_t.length IS maintained by rbs_node_list_
532
     * append — so the optional/trailing positional checks below use
533
     * `head == NULL` as the safer cross-cutting "is empty" predicate. */
534
    if ((fn->optional_positionals != NULL && fn->optional_positionals->head != NULL)
535
        || fn->rest_positionals != NULL
536
        || (fn->trailing_positionals != NULL && fn->trailing_positionals->head != NULL)
537
        || fn->rest_keywords != NULL) {
538
        return;
539
    }
540
541
    /* Map every required positional. If any maps as out-of-subset,
542
     * skip the whole signature -- the analyzer can't act on a
543
     * partially-typed method (would need a sentinel for "leave
544
     * alone" per-param, which the seed format doesn't have today). */
545
    sbuf_t ptypes;
546
    sbuf_init(&ptypes);
547
    bool first_p = true;
548
    if (fn->required_positionals != NULL) {
549
        rbs_node_list_node_t *cur = fn->required_positionals->head;
550
        while (cur != NULL) {
551
            if (cur->node->type != RBS_TYPES_FUNCTION_PARAM) { sbuf_free(&ptypes); return; }
552
            rbs_types_function_param_t *pp = (rbs_types_function_param_t *) cur->node;
553
            sbuf_t t;
554
            sbuf_init(&t);
555
            if (!map_type(p, pp->type, enclosing_scope, &t)) { sbuf_free(&t); sbuf_free(&ptypes); return; }
556
            if (!first_p) sbuf_append_cstr(&ptypes, ",");
557
            sbuf_append(&ptypes, t.buf, t.len);
558
            first_p = false;
559
            sbuf_free(&t);
560
            cur = cur->next;
561
        }
562
    }
563
564
    /* Required + optional keywords. Both are stored as rbs_hash
565
     * mapping name-Symbol → function_param. The hash is insertion-
566
     * ordered (head/tail linked list); RBS's parser inserts kwargs in
567
     * source order. We walk required then optional, mapping each
568
     * param's value type. The arity adds up to (positionals +
569
     * required_kwargs + optional_kwargs), matching Ruby's def in
570
     * source-order — same shape collect_all sees. Optionality is an
571
     * arity-affecting source property and doesn't change the type
572
     * slot the seed targets. */
573
    const rbs_hash_t *kw_hashes[] = { fn->required_keywords, fn->optional_keywords };
574
    for (size_t ki = 0; ki < sizeof(kw_hashes)/sizeof(kw_hashes[0]); ki++) {
575
        const rbs_hash_t *hash = kw_hashes[ki];
576
        if (hash == NULL) continue;
577
        rbs_hash_node_t *cur = hash->head;
578
        while (cur != NULL) {
579
            /* Defensive: an upstream rbs change adding a different
580
             * value-node type would land here. Skipping the whole
581
             * signature (rather than producing a partial seed) keeps
582
             * the analyzer consistent — apply_rbs_seeds overwrites a
583
             * method's ptype list wholesale, so a half-populated entry
584
             * is worse than no entry. Same policy as the positional
585
             * loop above and the existing out-of-subset early-return. */
586
            if (cur->value == NULL || cur->value->type != RBS_TYPES_FUNCTION_PARAM) {
587
                sbuf_free(&ptypes); return;
588
            }
589
            rbs_types_function_param_t *pp = (rbs_types_function_param_t *) cur->value;
590
            sbuf_t t;
591
            sbuf_init(&t);
592
            if (!map_type(p, pp->type, enclosing_scope, &t)) { sbuf_free(&t); sbuf_free(&ptypes); return; }
593
            if (!first_p) sbuf_append_cstr(&ptypes, ",");
594
            sbuf_append(&ptypes, t.buf, t.len);
595
            first_p = false;
596
            sbuf_free(&t);
597
            cur = cur->next;
598
        }
599
    }
600
601
    if (ptypes.len == 0) sbuf_append_cstr(&ptypes, "-");
602
603
    sbuf_t ret;
604
    sbuf_init(&ret);
605
    if (!map_type(p, fn->return_type, enclosing_scope, &ret)) { sbuf_free(&ret); sbuf_free(&ptypes); return; }
606
607
    sbuf_t mname;
608
    sbuf_init(&mname);
609
    name_of_symbol(p, m->name, &mname);
610
611
    bool emit_inst = (m->kind == RBS_METHOD_DEFINITION_KIND_INSTANCE)
612
                  || (m->kind == RBS_METHOD_DEFINITION_KIND_SINGLETON_INSTANCE);
613
    bool emit_cls  = (m->kind == RBS_METHOD_DEFINITION_KIND_SINGLETON)
614
                  || (m->kind == RBS_METHOD_DEFINITION_KIND_SINGLETON_INSTANCE);
615
616
    if (emit_inst) fprintf(out, "meth %s %s %s\n",  mname.buf, ret.buf, ptypes.buf);
617
    if (emit_cls)  fprintf(out, "cmeth %s %s %s\n", mname.buf, ret.buf, ptypes.buf);
618
619
    sbuf_free(&mname);
620
    sbuf_free(&ret);
621
    sbuf_free(&ptypes);
622
}
623
624
/* ---- emit attr_accessor / reader / writer ------------------ */
625
626
static void emit_attr(rbs_parser_t *p, rbs_ast_symbol_t *name, rbs_node_t *type,
627
                      const char *enclosing_scope, FILE *out) {
628
    sbuf_t t;
629
    sbuf_init(&t);
630
    if (!map_type(p, type, enclosing_scope, &t)) { sbuf_free(&t); return; }
631
    sbuf_t n;
632
    sbuf_init(&n);
633
    name_of_symbol(p, name, &n);
634
    fprintf(out, "ivar %s %s\n", n.buf, t.buf);
635
    sbuf_free(&n);
636
    sbuf_free(&t);
637
}
638
639
/* ---- traverse class/module body ---------------------------- */
640
641
/* `qualified_scope` is this declaration's full path (used as the
642
 * `class X` line). `lookup_scope` is the *parent* path (used to
643
 * resolve unqualified type references inside the members). For
644
 * `module ActiveRecord; class RecordInvalid; def record: () -> Base`:
645
 * qualified_scope = "ActiveRecord_RecordInvalid",
646
 * lookup_scope    = "ActiveRecord".
647
 * That makes `Base` resolve to `obj_ActiveRecord_Base` — the sibling-
648
 * in-module pattern, which dominates real RBS in practice. Ruby's
649
 * actual constant lookup walks every enclosing scope outward; this
650
 * single-level fallback covers the common case without a symbol
651
 * table. */
652
static void traverse_members(rbs_parser_t *p, rbs_node_list_t *members,
653
                             const char *qualified_scope,
654
                             const char *lookup_scope, FILE *out) {
655
    if (members == NULL || members->length == 0) return;
656
    fprintf(out, "class %s\n", qualified_scope);
657
    rbs_node_list_node_t *cur = members->head;
658
    while (cur != NULL) {
659
        rbs_node_t *n = cur->node;
660
        switch (n->type) {
661
            case RBS_AST_MEMBERS_METHOD_DEFINITION:
662
                emit_method(p, (rbs_ast_members_method_definition_t *) n, lookup_scope, out);
663
                break;
664
            case RBS_AST_MEMBERS_ATTR_ACCESSOR: {
665
                rbs_ast_members_attr_accessor_t *a = (rbs_ast_members_attr_accessor_t *) n;
666
                emit_attr(p, a->name, a->type, lookup_scope, out);
667
                break;
668
            }
669
            case RBS_AST_MEMBERS_ATTR_READER: {
670
                rbs_ast_members_attr_reader_t *a = (rbs_ast_members_attr_reader_t *) n;
671
                emit_attr(p, a->name, a->type, lookup_scope, out);
672
                break;
673
            }
674
            case RBS_AST_MEMBERS_ATTR_WRITER: {
675
                rbs_ast_members_attr_writer_t *a = (rbs_ast_members_attr_writer_t *) n;
676
                emit_attr(p, a->name, a->type, lookup_scope, out);
677
                break;
678
            }
679
            case RBS_AST_MEMBERS_INSTANCE_VARIABLE: {
680
                /* `@name: Type` declarations. seed_class_ivar in
681
                 * analyze prepends "@" if missing; emit_attr writes
682
                 * the name as-is (which in RBS includes the leading
683
                 * @), so the seed line ends up with "@@name" if we
684
                 * don't strip first. The seed_class_ivar handles
685
                 * either form, but normalize here so the seed file
686
                 * matches the attr_* shape (single `@`). */
687
                rbs_ast_members_instance_variable_t *iv = (rbs_ast_members_instance_variable_t *) n;
688
                emit_attr(p, iv->name, iv->type, lookup_scope, out);
689
                break;
690
            }
691
            default:
692
                /* Skip: include / extend / prepend / public / private
693
                 * / alias / class_variable. */
694
                break;
695
        }
696
        cur = cur->next;
697
    }
698
}
699
700
/* Pre-pass: collect every Class/Module declaration's qualified name
701
 * (with "_" separators) into known_names. Recurses through members so
702
 * `module A; module B; class C` registers all of A, A_B, A_B_C. The
703
 * later emit pass uses the set to disambiguate unqualified type
704
 * references (issue #656). */
705
static void collect_decl_names(rbs_parser_t *p, rbs_node_t *node,
706
                                const char *parent_scope) {
707
    sbuf_t leaf;
708
    sbuf_init(&leaf);
709
    rbs_node_list_t *members = NULL;
710
711
    if (node->type == RBS_AST_DECLARATIONS_CLASS) {
712
        rbs_ast_declarations_class_t *c = (rbs_ast_declarations_class_t *) node;
713
        name_of_type_name(p, c->name, &leaf);
714
        members = c->members;
715
    }
716
else if (node->type == RBS_AST_DECLARATIONS_MODULE) {
717
        rbs_ast_declarations_module_t *m = (rbs_ast_declarations_module_t *) node;
718
        name_of_type_name(p, m->name, &leaf);
719
        members = m->members;
720
    }
721
else {
722
        sbuf_free(&leaf);
723
        return;
724
    }
725
726
    sbuf_t qualified;
727
    sbuf_init(&qualified);
728
    if (parent_scope != NULL && parent_scope[0] != '\0') {
729
        sbuf_append_cstr(&qualified, parent_scope);
730
        sbuf_append_cstr(&qualified, "_");
731
    }
732
    sbuf_append(&qualified, leaf.buf, leaf.len);
733
    known_names_add(qualified.buf, qualified.len);
734
735
    if (members != NULL) {
736
        rbs_node_list_node_t *cur = members->head;
737
        while (cur != NULL) {
738
            if (cur->node->type == RBS_AST_DECLARATIONS_CLASS
739
                || cur->node->type == RBS_AST_DECLARATIONS_MODULE) {
740
                collect_decl_names(p, cur->node, qualified.buf);
741
            }
742
            cur = cur->next;
743
        }
744
    }
745
746
    sbuf_free(&qualified);
747
    sbuf_free(&leaf);
748
}
749
750
/* Recurse into a declaration. For Class/Module: extend the scope path
751
 * with the declaration's leaf name, emit members, then recurse into
752
 * any nested Class/Module members so e.g. `module Foo; class Bar; end;
753
 * end` produces a `class Foo::Bar` block. */
754
static void traverse_decl(rbs_parser_t *p, rbs_node_t *node,
755
                          const char *parent_scope, FILE *out) {
756
    sbuf_t leaf;
757
    sbuf_init(&leaf);
758
    rbs_node_list_t *members = NULL;
759
760
    if (node->type == RBS_AST_DECLARATIONS_CLASS) {
761
        rbs_ast_declarations_class_t *c = (rbs_ast_declarations_class_t *) node;
762
        name_of_type_name(p, c->name, &leaf);
763
        members = c->members;
764
    }
765
else if (node->type == RBS_AST_DECLARATIONS_MODULE) {
766
        rbs_ast_declarations_module_t *m = (rbs_ast_declarations_module_t *) node;
767
        name_of_type_name(p, m->name, &leaf);
768
        members = m->members;
769
    }
770
else {
771
        /* Skip Interface, Constant, Global, TypeAlias, ClassAlias,
772
         * ModuleAlias, Directives. */
773
        sbuf_free(&leaf);
774
        return;
775
    }
776
777
    /* qualified = parent_scope (if any) "_" + leaf -- spinel's
778
     * nested-class storage uses underscore as separator. */
779
    sbuf_t qualified;
780
    sbuf_init(&qualified);
781
    if (parent_scope != NULL && parent_scope[0] != '\0') {
782
        sbuf_append_cstr(&qualified, parent_scope);
783
        sbuf_append_cstr(&qualified, "_");
784
    }
785
    sbuf_append(&qualified, leaf.buf, leaf.len);
786
787
    traverse_members(p, members, qualified.buf, parent_scope, out);
788
789
    /* Recurse into nested declarations. */
790
    if (members != NULL) {
791
        rbs_node_list_node_t *cur = members->head;
792
        while (cur != NULL) {
793
            if (cur->node->type == RBS_AST_DECLARATIONS_CLASS
794
                || cur->node->type == RBS_AST_DECLARATIONS_MODULE) {
795
                traverse_decl(p, cur->node, qualified.buf, out);
796
            }
797
            cur = cur->next;
798
        }
799
    }
800
801
    sbuf_free(&qualified);
802
    sbuf_free(&leaf);
803
}
804
805
/* ---- per-file processing ----------------------------------- */
806
807
/* Read a file fully into a malloc'd buffer. Returns NULL on failure;
808
 * sets *len_out to the byte count on success. */
809
static char *slurp(const char *path, size_t *len_out) {
810
    FILE *fp = fopen(path, "rb");
811
    if (fp == NULL) return NULL;
812
    if (fseek(fp, 0, SEEK_END) != 0) { fclose(fp); return NULL; }
813
    long sz = ftell(fp);
814
    if (sz < 0) { fclose(fp); return NULL; }
815
    if (fseek(fp, 0, SEEK_SET) != 0) { fclose(fp); return NULL; }
816
    char *buf = (char *) malloc((size_t) sz + 1);
817
    if (buf == NULL) { fclose(fp); return NULL; }
818
    size_t got = fread(buf, 1, (size_t) sz, fp);
819
    fclose(fp);
820
    buf[got] = '\0';
821
    *len_out = got;
822
    return buf;
823
}
824
825
/* Per-pass selector for process_file. Splitting the per-file work
826
 * into two phases (collect names; emit decls) lets walk() run twice
827
 * over the directory tree so cross-file module reopens have every
828
 * class registered before any unqualified-Const reference is
829
 * resolved. Issue #658. */
830
typedef enum {
831
    PHASE_COLLECT_NAMES = 0,
832
    PHASE_EMIT = 1
833
} process_phase_t;
834
835
static void process_file_phase(const char *path, FILE *out, process_phase_t phase) {
836
    size_t len = 0;
837
    char *src = slurp(path, &len);
838
    if (src == NULL) {
839
        fprintf(stderr, "spinel_rbs_extract: cannot read %s\n", path);
840
        return;
841
    }
842
    rbs_string_t str = rbs_string_new(src, src + len);
843
    rbs_parser_t *p = rbs_parser_new(str, RBS_ENCODING_UTF_8_ENTRY, 0, (int) len);
844
    if (p == NULL) { free(src); return; }
845
    rbs_signature_t *sig = NULL;
846
    bool ok = rbs_parse_signature(p, &sig);
847
    if (!ok || sig == NULL) {
848
        if (phase == PHASE_EMIT) {
849
            fprintf(stderr, "spinel_rbs_extract: parse failed in %s\n", path);
850
            if (p->error != NULL && p->error->message != NULL) {
851
                fprintf(stderr, "  %s\n", p->error->message);
852
            }
853
        }
854
        rbs_parser_free(p);
855
        free(src);
856
        return;
857
    }
858
    if (phase == PHASE_COLLECT_NAMES) {
859
        rbs_node_list_node_t *pre = sig->declarations->head;
860
        while (pre != NULL) {
861
            collect_decl_names(p, pre->node, "");
862
            pre = pre->next;
863
        }
864
    }
865
else {
866
        rbs_node_list_node_t *cur = sig->declarations->head;
867
        while (cur != NULL) {
868
            traverse_decl(p, cur->node, "", out);
869
            cur = cur->next;
870
        }
871
    }
872
    rbs_parser_free(p);
873
    free(src);
874
}
875
876
static void process_file(const char *path, FILE *out) {
877
    process_file_phase(path, out, PHASE_EMIT);
878
}
879
880
/* ---- directory walk ---------------------------------------- */
881
882
static bool ends_with(const char *s, const char *suffix) {
883
    size_t sl = strlen(s), su = strlen(suffix);
884
    if (su > sl) return false;
885
    return strcmp(s + sl - su, suffix) == 0;
886
}
887
888
static void walk_phase(const char *path, FILE *out, process_phase_t phase) {
889
    struct stat st;
890
    if (stat(path, &st) != 0) {
891
        if (phase == PHASE_EMIT) {
892
            fprintf(stderr, "spinel_rbs_extract: %s: not found\n", path);
893
        }
894
        return;
895
    }
896
    if (S_ISREG(st.st_mode)) {
897
        if (ends_with(path, ".rbs")) process_file_phase(path, out, phase);
898
        return;
899
    }
900
    if (!S_ISDIR(st.st_mode)) return;
901
    DIR *d = opendir(path);
902
    if (d == NULL) return;
903
    struct dirent *ent;
904
    while ((ent = readdir(d)) != NULL) {
905
        if (ent->d_name[0] == '.') continue;
906
        char full[4096];
907
        int n = snprintf(full, sizeof(full), "%s/%s", path, ent->d_name);
908
        if (n < 0 || (size_t) n >= sizeof(full)) {
909
            if (phase == PHASE_EMIT) {
910
                fprintf(stderr, "spinel_rbs_extract: path too long, skipping: %s/%s\n",
911
                        path, ent->d_name);
912
            }
913
            continue;
914
        }
915
        walk_phase(full, out, phase);
916
    }
917
    closedir(d);
918
}
919
920
static void walk(const char *path, FILE *out) { walk_phase(path, out, PHASE_EMIT); }
921
922
int main(int argc, char **argv) {
923
    if (argc < 2) {
924
        fprintf(stderr, "Usage: spinel_rbs_extract DIR [DIR ...]\n");
925
        return 1;
926
    }
927
    /* Two-pass walk: first phase collects every Class / Module's
928
     * qualified name across all .rbs files into known_names; second
929
     * phase emits decls. Splitting the pre-pass from the emit pass
930
     * lets a bare `Bar` inside `baz.rbs`'s reopen of `module Foo`
931
     * see `Foo::Bar` from a sibling `bar.rbs` regardless of which
932
     * file readdir visited first. Issue #658 (followup to #656). */
933
    for (int i = 1; i < argc; i++) {
934
        walk_phase(argv[i], stdout, PHASE_COLLECT_NAMES);
935
    }
936
    for (int i = 1; i < argc; i++) {
937
        walk_phase(argv[i], stdout, PHASE_EMIT);
938
    }
939
    return 0;
940
}