aboutsummaryrefslogtreecommitdiff
path: root/src/z/parser/js/ast/decl.zig
blob: a9a6117b3fe0d28eef0118a0bda5573c672ca98c (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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
const std = @import("std");
const Loc = @import("loc.zig").Loc;
const Expr = @import("expr.zig").Expr;
const Pat = @import("pat.zig").Pat;
const Stmt = @import("stmt.zig").Stmt;
const BlockStmt = @import("stmt.zig").BlockStmt;
const VarStmt = @import("stmt.zig").VarStmt;
const VarDeclarator = @import("stmt.zig").VarDeclarator;
const VarKind = @import("stmt.zig").VarKind;
const FnType = @import("expr.zig").FnType;
const ClassElem = @import("expr.zig").ClassElem;
const Parser = @import("../parser.zig").Parser;
const Formatter = @import("../formatter.zig").Formatter;
const ParseError = @import("../parser.zig").ParseError;

pub const DeclType = union(enum) {
    @"fn": FnDecl,
    class: ClassDecl,
    @"var": VarDecl,
    using: UsingDecl,
    import: ImportDecl,
    @"export": ExportDecl,
    export_default: ExportDefault,
};

pub const Decl = struct {
    loc: Loc,
    data: DeclType,

    pub fn fmt(self: @This(), f: *Formatter) void {
        switch (self.data) {
            .@"fn" => |d| d.fmt(f),
            .class => |c| c.fmt(f),
            .@"var" => |v| {
                f.write(@tagName(v.kind));
                f.writeSpace();
                for (v.decls, 0..) |d, i| {
                    if (i > 0) f.write(", ");
                    d.fmt(f);
                }
            },
            .using => |u| {
                f.write("using ");
                for (u.decls, 0..) |d, i| {
                    if (i > 0) f.write(", ");
                    d.fmt(f);
                }
            },
            .import => |i| i.fmt(f),
            .@"export" => |e| e.fmt(f),
            .export_default => |e| e.fmt(f),
        }
    }

    pub fn parse(p: *Parser) ParseError!Decl {
        switch (p.peek()) {
            .@"var" => {
                const s = try VarStmt.parse(p);
                return Decl{ .loc = s.loc, .data = .{ .@"var" = .{ .loc = s.loc, .kind = s.kind, .decls = s.decls } } };
            },
            else => return ParseError.ExpectedStatement,
        }
    }
};

pub const FnDecl = struct {
    loc: Loc,
    fn_type: FnType,
    id: ?[]const u8,
    params: []const Pat,
    body: BlockStmt,

    pub fn parse(p: *Parser, fn_type_arg: FnType, mode: enum { stmt, expr }) ParseError!?Stmt {
        const start = p.tok().loc.start;
        var fn_type = fn_type_arg;

        if (fn_type == .async) {
            _ = p.advanceTok();
        } else if (fn_type == .async_generator) {
            _ = p.advanceTok();
            _ = p.advanceTok();
        }

        _ = p.advanceTok();

        if (fn_type == .normal and p.peek() == .@"*") {
            p.advance();
            fn_type = .generator;
        }

        var id: ?[]const u8 = null;
        if (p.peek().isIdentifier()) {
            const id_tok = p.advanceTok();
            id = p.tokenSlice(id_tok);
        }

        const params = try p.parseParams();
        const body = try p.parseFunctionBody();

        const end = body.loc.end;

        if (mode == .stmt) {
            return Stmt{
                .loc = .{ .start = start, .end = end },
                .data = .{ .function = .{ .loc = .{ .start = start, .end = end }, .fn_type = fn_type, .id = id, .params = params, .body = body } },
            };
        }
        return null;
    }

    pub fn fmt(self: @This(), f: *Formatter) void {
        f.write("function");
        if (self.fn_type == .generator or self.fn_type == .async_generator) {
            f.write("*");
        }
        if (self.fn_type == .async or self.fn_type == .async_generator) {
            f.write(" async");
        }
        if (self.id) |id| {
            f.writeSpace();
            f.write(id);
        }
        f.writeChar('(');
        for (self.params, 0..) |p, i| {
            if (i > 0) f.write(", ");
            p.fmt(f);
        }
        f.write(") ");
        self.body.fmt(f);
    }
};

pub const ClassDecl = struct {
    loc: Loc,
    id: ?[]const u8,
    super_class: ?*const Expr,
    body: []const ClassElem,

    pub fn parse(p: *Parser, mode: enum { stmt, expr }) ParseError!?Stmt {
        const start = p.advanceTok().loc.start;

        var id: ?[]const u8 = null;
        if (p.peek() == .identifier) {
            const id_tok = p.advanceTok();
            id = p.tokenSlice(id_tok);
        }

        var super_class: ?*const Expr = null;
        if (p.matchKeyword(.extends)) {
            super_class = try Expr.parse(p, 0);
        }

        try p.expect(.lbrace);
        var elems: [128]ClassElem = undefined;
        var elem_count: usize = 0;

        while (p.peek() != .rbrace and p.peek() != .eof) {
            const elem = try ClassElem.parse(p);
            elems[elem_count] = elem;
            elem_count += 1;
            if (elem_count >= elems.len) return ParseError.TooManyTokens;
        }

        const end_tok = try p.expectTok(.rbrace);

        if (mode == .stmt) {
            return Stmt{
                .loc = .{ .start = start, .end = end_tok.loc.end },
                .data = .{ .class = .{ .loc = .{ .start = start, .end = end_tok.loc.end }, .id = id, .super_class = super_class, .body = elems[0..elem_count] } },
            };
        }
        return null;
    }

    pub fn fmt(self: @This(), f: *Formatter) void {
        f.write("class");
        if (self.id) |id| {
            f.writeSpace();
            f.write(id);
        }
        if (self.super_class) |sc| {
            f.write(" extends ");
            sc.*.fmt(f);
        }
        f.write(" {");
        f.newline();
        f.indent_level += 1;
        for (self.body) |elem| {
            f.writeIndent();
            elem.fmt(f);
            f.newline();
        }
        f.indent_level -= 1;
        f.writeIndent();
        f.writeChar('}');
    }
};

pub const VarDecl = struct {
    loc: Loc,
    kind: VarKind,
    decls: []const VarDeclarator,
};

pub const UsingDecl = struct {
    loc: Loc,
    is_await: bool,
    decls: []const VarDeclarator,
};

pub const ImportDecl = struct {
    loc: Loc,
    specifiers: []const ImportSpecifier,
    source: []const u8,
    attributes: []const ImportAttribute,

    pub fn parse(p: *Parser) ParseError!ImportDecl {
        const start = p.advanceTok().loc.start;
        var specifiers: [32]ImportSpecifier = undefined;
        var spec_count: usize = 0;

        if (p.peek() != .string and p.peek() != .lparen) {
            if (p.peek() == .identifier or p.peek().isKeyword()) {
                const local_tok = p.advanceTok();
                const local = p.tokenSlice(local_tok);
                specifiers[spec_count] = .{ .default = local };
                spec_count += 1;
                if (p.match(.comma)) {}
            }

            if (p.match(.@"*")) {
                try p.expect(.identifier);
                const ns_tok = try p.expectTok(.identifier);
                const ns = p.tokenSlice(ns_tok);
                specifiers[spec_count] = .{ .namespace = ns };
                spec_count += 1;
            } else if (p.peek() == .lbrace) {
                p.advance();
                if (p.peek() != .rbrace) {
                    while (true) {
                        const imported_tok = try p.expectTok(.identifier);
                        const imported = p.tokenSlice(imported_tok);
                        var local = imported;
                        if (p.match(.identifier)) {
                            local = p.tokenSlice(p.tokens[p.pos - 1]);
                        }
                        specifiers[spec_count] = .{ .named = .{ .imported = imported, .local = local } };
                        spec_count += 1;
                        if (!p.match(.comma)) break;
                    }
                }
                try p.expect(.rbrace);
            }
        }

        var source: []const u8 = "";
        var attrs: [8]ImportAttribute = undefined;
        var attr_count: usize = 0;

        if (p.matchKeyword(.from)) {
            const str_tok = try p.expectTok(.string);
            source = p.tokenSlice(str_tok);
        } else if (p.peek() == .string) {
            const str_tok = p.advanceTok();
            source = p.tokenSlice(str_tok);
        }

        if (p.matchKeyword(.with)) {
            try p.expect(.lbrace);
            while (p.peek() != .rbrace and p.peek() != .eof) {
                const key_tok = p.advanceTok();
                const key = p.tokenSlice(key_tok);
                try p.expect(.@":");
                const val_tok = try p.expectTok(.string);
                const val = p.tokenSlice(val_tok);
                attrs[attr_count] = .{ .key = key, .value = val };
                attr_count += 1;
                _ = p.match(.comma);
            }
            try p.expect(.rbrace);
        }

        try p.expect(.semicolon);
        return .{ .loc = .{ .start = start, .end = p.tok().loc.start }, .specifiers = specifiers[0..spec_count], .source = source, .attributes = attrs[0..attr_count] };
    }

    pub fn fmt(self: @This(), f: *Formatter) void {
        f.write("import ");
        if (self.specifiers.len > 0) {
            for (self.specifiers, 0..) |spec, j| {
                if (j > 0) f.write(", ");
                spec.fmt(f);
            }
            f.write(" from ");
        }
        f.writeChar('"');
        f.write(self.source);
        f.writeChar('"');
        for (self.attributes) |a| {
            f.write(" /* ");
            a.fmt(f);
            f.write(" */");
        }
        f.writeChar(';');
    }
};

pub const ImportSpecifier = union(enum) {
    default: []const u8,
    namespace: []const u8,
    named: struct { imported: []const u8, local: []const u8 },
};

pub const ImportAttribute = struct {
    key: []const u8,
    value: []const u8,

    pub fn fmt(self: @This(), f: *Formatter) void {
        f.write(self.key);
        f.write(": \"");
        f.write(self.value);
        f.writeChar('"');
    }
};

pub const ExportDecl = struct {
    loc: Loc,
    declaration: ?*const Decl,
    specifiers: ?[]const ExportSpecifier,
    source: ?[]const u8,

    pub fn parse(p: *Parser) ParseError!ExportDecl {
        const start = p.advanceTok().loc.start;

        if (p.matchKeyword(.default)) {
            if (p.peek() == .function or p.peek() == .async or p.peek() == .class) {
                const decl = try Stmt.parse(p);
                p.semicolon();
                return .{ .loc = .{ .start = start, .end = decl.loc.end }, .declaration = null, .specifiers = null, .source = null };
            }
            const expr = try Expr.parse(p, 0);
            p.semicolon();
            return .{ .loc = .{ .start = start, .end = expr.loc.end }, .declaration = null, .specifiers = null, .source = null };
        }

        if (p.peek() == .@"*") {
            p.advance();
            try p.expect(.identifier);
            const source_tok = try p.expectTok(.string);
            const src = p.tokenSlice(source_tok);
            try p.expect(.semicolon);
            return .{ .loc = .{ .start = start, .end = p.tok().loc.start }, .declaration = null, .specifiers = null, .source = src };
        }

        if (p.peek() == .lbrace) {
            p.advance();
            var specs: [32]ExportSpecifier = undefined;
            var spec_count: usize = 0;
            while (p.peek() != .rbrace and p.peek() != .eof) {
                const exported_tok = p.advanceTok();
                const exported = p.tokenSlice(exported_tok);
                var local = exported;
                if (p.match(.identifier)) {
                    local = p.tokenSlice(p.tokens[p.pos - 1]);
                }
                specs[spec_count] = .{ .loc = .{ .start = exported_tok.loc.start, .end = p.tok().loc.start }, .exported = exported, .local = local };
                spec_count += 1;
                if (!p.match(.comma)) break;
            }
            try p.expect(.rbrace);
            var source: ?[]const u8 = null;
            if (p.matchKeyword(.from)) {
                const src_tok = try p.expectTok(.string);
                source = p.tokenSlice(src_tok);
            }
            try p.expect(.semicolon);
            return .{ .loc = .{ .start = start, .end = p.tok().loc.start }, .declaration = null, .specifiers = specs[0..spec_count], .source = source };
        }

        const decl = try Stmt.parse(p);
        p.semicolon();
        return .{ .loc = .{ .start = start, .end = decl.loc.end }, .declaration = null, .specifiers = null, .source = null };
    }

    pub fn fmt(self: @This(), f: *Formatter) void {
        f.write("export ");
        if (self.declaration) |d| {
            d.*.fmt(f);
        } else if (self.specifiers) |s| {
            f.writeChar('{');
            for (s, 0..) |sp, i| {
                if (i > 0) f.write(", ");
                sp.fmt(f);
            }
            f.writeChar('}');
            if (self.source) |src| {
                f.write(" from \"");
                f.write(src);
                f.writeChar('"');
            }
            f.writeChar(';');
        } else if (self.source) |src| {
            f.write("* from \"");
            f.write(src);
            f.writeChar("\";");
        }
    }
};

pub const ExportSpecifier = struct {
    loc: Loc,
    exported: []const u8,
    local: []const u8,

    pub fn fmt(self: @This(), f: *Formatter) void {
        f.write(self.local);
        if (!std.mem.eql(u8, self.local, self.exported)) {
            f.write(" as ");
            f.write(self.exported);
        }
    }
};

pub const ExportDefault = struct {
    loc: Loc,
    declaration: *const Decl,

    pub fn fmt(self: @This(), f: *Formatter) void {
        f.write("export default ");
        self.declaration.*.fmt(f);
    }
};