forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbraces.zig
More file actions
740 lines (646 loc) · 23.4 KB
/
Copy pathbraces.zig
File metadata and controls
740 lines (646 loc) · 23.4 KB
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
const log = bun.Output.scoped(.BRACES, .visible);
/// Using u16 because anymore tokens than that results in an unreasonably high
/// amount of brace expansion (like around 32k variants to expand)
const ExpansionVariant = packed struct(u32) {
start: u16 = 0,
end: u16 = 0, // must be >= start
};
const Token = union(enum) {
open: ExpansionVariants,
comma,
text: SmolStr,
close,
eof,
const Tag = @typeInfo(Token).@"union".tag_type.?;
const ExpansionVariants = struct {
idx: u16 = 0,
end: u16 = 0,
};
pub fn toText(self: *Token) SmolStr {
return switch (self.*) {
.open => SmolStr.fromChar('{'),
.comma => SmolStr.fromChar(','),
.text => |txt| txt,
.close => SmolStr.fromChar('}'),
.eof => SmolStr.empty(),
};
}
};
pub const AST = struct {
pub const Atom = union(enum) {
text: SmolStr,
expansion: Expansion,
};
const Group = struct {
bubble_up: ?*Group = null,
bubble_up_next: ?u16 = null,
atoms: union(enum) { single: Atom, many: []Atom },
};
const Expansion = struct {
variants: []AST.Group,
};
};
const MAX_NESTED_BRACES = 10;
const ExpandError = ParserError;
/// `out` is preallocated by using the result from `calculateExpandedAmount`
pub fn expand(
allocator: Allocator,
tokens: []Token,
out: []std.array_list.Managed(u8),
contains_nested: bool,
) ExpandError!void {
var out_key_counter: u16 = 1;
if (!contains_nested) {
var expansions_table = try buildExpansionTableAlloc(allocator, tokens);
return try expandFlat(tokens, expansions_table.items[0..], out, 0, &out_key_counter, 0, 0, tokens.len);
}
var parser = Parser.init(tokens, allocator);
var root_node = try parser.parse();
try expandNested(&root_node, out, 0, &out_key_counter, 0);
}
fn expandNested(
root: *AST.Group,
out: []std.array_list.Managed(u8),
out_key: u16,
out_key_counter: *u16,
start: u32,
) ExpandError!void {
if (root.atoms == .single) {
if (start > 0) {
if (root.bubble_up) |bubble_up| {
return expandNested(bubble_up, out, out_key, out_key_counter, root.bubble_up_next.?);
}
return;
}
return switch (root.atoms.single) {
.text => |txt| try {
try out[out_key].appendSlice(txt.slice());
if (root.bubble_up) |bubble_up| {
return expandNested(bubble_up, out, out_key, out_key_counter, root.bubble_up_next.?);
}
return;
},
.expansion => |expansion| {
const length = out[out_key].items.len;
for (expansion.variants, 0..) |*group, j| {
group.bubble_up = root;
group.bubble_up_next = 1;
const new_key = if (j == 0) out_key else brk: {
const new_key = out_key_counter.*;
try out[new_key].appendSlice(out[out_key].items[0..length]);
out_key_counter.* += 1;
break :brk new_key;
};
try expandNested(group, out, new_key, out_key_counter, 0);
}
return;
},
};
}
if (start >= root.atoms.many.len) {
if (root.bubble_up) |bubble_up| {
return expandNested(bubble_up, out, out_key, out_key_counter, root.bubble_up_next.?);
}
return;
}
for (root.atoms.many[start..], start..) |atom, i_| {
const i: u16 = @intCast(i_);
switch (atom) {
.text => |txt| {
try out[out_key].appendSlice(txt.slice());
},
.expansion => |expansion| {
const length = out[out_key].items.len;
for (expansion.variants, 0..) |*group, j| {
group.bubble_up = root;
group.bubble_up_next = i + 1;
const new_key = if (j == 0) out_key else brk: {
const new_key = out_key_counter.*;
try out[new_key].appendSlice(out[out_key].items[0..length]);
out_key_counter.* += 1;
break :brk new_key;
};
try expandNested(group, out, new_key, out_key_counter, 0);
}
return;
},
}
}
// After execution we need to go up a level
if (root.bubble_up) |bubble_up| {
return try expandNested(bubble_up, out, out_key, out_key_counter, root.bubble_up_next.?);
}
}
/// This function is fast but does not work for nested brace expansions
/// TODO optimization: allocate into one buffer of chars
fn expandFlat(
tokens: []const Token,
expansion_table: []const ExpansionVariant,
out: []std.array_list.Managed(u8),
out_key: u16,
out_key_counter: *u16,
depth_: u8,
start: usize,
end: usize,
) !void {
log("expandFlat [{d}, {d}]", .{ start, end });
if (start >= tokens.len or end > tokens.len) return;
var depth = depth_;
for (tokens[start..end], start..) |atom, j| {
_ = j;
switch (atom) {
.text => |txt| {
try out[out_key].appendSlice(txt.slice());
},
.close => {
depth -= 1;
},
.open => |expansion_variants| {
depth += 1;
if (bun.Environment.allow_assert) {
assert(expansion_variants.end - expansion_variants.idx >= 1);
}
var variants = expansion_table[expansion_variants.idx..expansion_variants.end];
const skip_over_idx = variants[variants.len - 1].end;
const starting_len = out[out_key].items.len;
for (variants[0..], 0..) |*variant, i| {
const new_key = if (i == 0) out_key else brk: {
const new_key = out_key_counter.*;
try out[new_key].appendSlice(out[out_key].items[0..starting_len]);
out_key_counter.* += 1;
break :brk new_key;
};
try expandFlat(tokens, expansion_table, out, new_key, out_key_counter, depth, variant.start, variant.end);
try expandFlat(tokens, expansion_table, out, new_key, out_key_counter, depth, skip_over_idx, end);
}
return;
},
else => {},
}
}
}
fn calculateVariantsAmount(tokens: []const Token) u32 {
var brace_count: u32 = 0;
var count: u32 = 0;
for (tokens) |tok| {
switch (tok) {
.comma => count += 1,
.open => brace_count += 1,
.close => {
if (brace_count == 1) {
count += 1;
}
brace_count -= 1;
},
else => {},
}
}
return count;
}
const ParserError = bun.OOM || error{
UnexpectedToken,
};
pub const Parser = struct {
current: usize = 0,
tokens: []const Token,
alloc: Allocator,
errors: std.array_list.Managed(Error),
// FIXME error location
const Error = struct { msg: []const u8 };
pub fn init(tokens: []const Token, alloc: Allocator) Parser {
return .{
.tokens = tokens,
.alloc = alloc,
.errors = std.array_list.Managed(Error).init(alloc),
};
}
pub fn parse(self: *Parser) !AST.Group {
var group_alloc_ = std.heap.stackFallback(@sizeOf(AST.Atom), self.alloc);
const group_alloc = group_alloc_.get();
var nodes = std.array_list.Managed(AST.Atom).init(group_alloc);
while (!self.match(.eof)) {
try nodes.append(try self.parseAtom() orelse break);
}
if (nodes.items.len == 1) {
return .{ .atoms = .{ .single = nodes.items[0] } };
} else {
return .{ .atoms = .{ .many = nodes.items[0..] } };
}
}
fn parseAtom(self: *Parser) ParserError!?AST.Atom {
switch (self.advance()) {
.open => {
const expansion_ptr = try self.parseExpansion();
return .{ .expansion = expansion_ptr };
},
.text => |txt| return .{ .text = txt },
.eof => return null,
.close, .comma => return ParserError.UnexpectedToken,
}
}
fn parseExpansion(self: *Parser) !AST.Expansion {
var variants = std.array_list.Managed(AST.Group).init(self.alloc);
while (!self.match_any(&.{ .close, .eof })) {
if (self.match(.eof)) break;
var group_alloc_ = std.heap.stackFallback(@sizeOf(AST.Atom), self.alloc);
const group_alloc = group_alloc_.get();
var group = std.array_list.Managed(AST.Atom).init(group_alloc);
var close = false;
while (!self.match(.eof)) {
if (self.match(.close)) {
close = true;
break;
}
if (self.match(.comma)) break;
const group_atom = try self.parseAtom() orelse break;
try group.append(group_atom);
}
if (group.items.len == 1) {
try variants.append(.{ .atoms = .{ .single = group.items[0] } });
} else {
try variants.append(.{ .atoms = .{ .many = group.items[0..] } });
}
if (close) break;
}
return .{ .variants = variants.items[0..] };
}
fn has_eq_sign(self: *Parser, str: []const u8) ?u32 {
_ = self;
return @import("../runtime/shell/shell.zig").hasEqSign(str);
}
fn advance(self: *Parser) Token {
if (!self.is_at_end()) {
self.current += 1;
}
return if (self.current > 0) self.prev() else self.peek();
}
fn is_at_end(self: *Parser) bool {
return self.peek() == .eof;
}
fn expect(self: *Parser, toktag: Token.Tag) Token {
assert(toktag == @as(Token.Tag, self.peek()));
if (self.check(toktag)) {
return self.advance();
}
unreachable;
}
/// Consumes token if it matches
fn match(self: *Parser, toktag: Token.Tag) bool {
if (@as(Token.Tag, self.peek()) == toktag) {
_ = self.advance();
return true;
}
return false;
}
fn match_any2(self: *Parser, comptime toktags: []const Token.Tag) ?Token {
const peeked = self.peek();
inline for (toktags) |tag| {
if (peeked == tag) {
_ = self.advance();
return peeked;
}
}
return null;
}
fn match_any(self: *Parser, comptime toktags: []const Token.Tag) bool {
const peeked = @as(Token.Tag, self.peek());
inline for (toktags) |tag| {
if (peeked == tag) {
_ = self.advance();
return true;
}
}
return false;
}
fn check(self: *Parser, toktag: Token.Tag) bool {
return @as(Token.Tag, self.peek()) == @as(Token.Tag, toktag);
}
fn peek(self: *Parser) Token {
return self.tokens[self.current];
}
fn peek_n(self: *Parser, n: u32) Token {
if (self.current + n >= self.tokens.len) {
return self.tokens[self.tokens.len - 1];
}
return self.tokens[self.current + n];
}
fn prev(self: *Parser) Token {
return self.tokens[self.current - 1];
}
fn add_error(self: *Parser, comptime fmt: []const u8, args: anytype) !void {
const error_msg = try std.fmt.allocPrint(self.alloc, fmt, args);
try self.errors.append(.{ .msg = error_msg });
}
};
pub fn calculateExpandedAmount(tokens: []const Token) u32 {
const StackEntry = struct {
segment_product: u32 = 1,
accumulator: u32 = 0,
};
var nested_brace_stack = bun.SmallList(StackEntry, MAX_NESTED_BRACES){};
defer nested_brace_stack.deinit(bun.default_allocator);
var variant_count: u32 = 0;
for (tokens) |tok| {
switch (tok) {
.open => nested_brace_stack.append(bun.default_allocator, .{}),
.comma => {
const top = nested_brace_stack.lastMut().?;
top.accumulator +|= top.segment_product;
top.segment_product = 1;
},
.close => {
const entry = nested_brace_stack.pop().?;
const total = entry.accumulator +| entry.segment_product;
if (nested_brace_stack.len() > 0) {
const parent = nested_brace_stack.lastMut().?;
parent.segment_product *|= total;
} else if (variant_count == 0) {
variant_count = total;
} else {
variant_count *|= total;
}
},
else => {},
}
}
return variant_count;
}
fn buildExpansionTableAlloc(alloc: Allocator, tokens: []Token) !std.array_list.Managed(ExpansionVariant) {
var table = std.array_list.Managed(ExpansionVariant).init(alloc);
try buildExpansionTable(tokens, &table);
return table;
}
fn buildExpansionTable(tokens: []Token, table: *std.array_list.Managed(ExpansionVariant)) !void {
const BraceState = struct {
tok_idx: u16,
variants: u16,
prev_tok_end: u16,
};
var brace_stack = bun.SmallList(BraceState, MAX_NESTED_BRACES){};
defer brace_stack.deinit(bun.default_allocator);
var i: u16 = 0;
var prev_close = false;
while (i < tokens.len) : (i += 1) {
switch (tokens[i]) {
.open => {
const table_idx: u16 = @intCast(table.items.len);
tokens[i].open.idx = table_idx;
brace_stack.append(bun.default_allocator, .{
.tok_idx = i,
.variants = 0,
.prev_tok_end = i,
});
},
.close => {
var top = brace_stack.pop().?;
try table.append(.{
.end = i,
.start = top.prev_tok_end + 1,
});
top.prev_tok_end = i;
top.variants += 1;
tokens[top.tok_idx].open.end = @intCast(table.items.len);
prev_close = true;
},
.comma => {
var top = brace_stack.lastMut().?;
try table.append(.{
.end = i,
.start = top.prev_tok_end + 1,
});
prev_close = false;
top.prev_tok_end = i;
top.variants += 1;
},
else => {
prev_close = false;
},
}
}
if (bun.Environment.allow_assert) {
for (table.items[0..], 0..) |variant, kdjsd| {
_ = kdjsd;
assert(variant.start != 0 and variant.end != 0);
}
}
}
pub const Lexer = NewLexer(.ascii);
pub fn NewLexer(comptime encoding: Encoding) type {
const Chars = NewChars(encoding);
return struct {
chars: Chars,
alloc: Allocator,
tokens: ArrayList(Token),
contains_nested: bool = false,
pub const Output = struct {
tokens: ArrayList(Token),
contains_nested: bool,
};
pub fn tokenize(alloc: Allocator, src: []const u8) BraceLexerError!Output {
var this = @This(){
.chars = Chars.init(src),
.tokens = ArrayList(Token).init(alloc),
.alloc = alloc,
};
const contains_nested = try this.tokenize_impl();
return .{
.tokens = this.tokens,
.contains_nested = contains_nested,
};
}
// FIXME: implement rollback on invalid brace
fn tokenize_impl(self: *@This()) BraceLexerError!bool {
// Unclosed brace expansion algorithm
// {hi,hey
// *xx*xxx
// {hi, hey
// *xxx$
// {hi,{a,b} sdkjfs}
// *xx**x*x*$
// 00000100000000000010000000000000
// echo {foo,bar,baz,{hi,hey},oh,no
// xxxxx*xxx*xxx*xxx**xx*xxx**xx*xx
//
// {hi,h{ey }
// *xx*x*xx$
//
// - Replace chars with special tokens
// - If unclosed or encounter bad token:
// - Start at beginning of brace, replacing special tokens back with
// chars, skipping over actual closed braces
var brace_stack = bun.SmallList(u32, MAX_NESTED_BRACES){};
defer brace_stack.deinit(bun.default_allocator);
while (true) {
const input = self.eat() orelse break;
const char = input.char;
const escaped = input.escaped;
if (!escaped) {
switch (char) {
'{' => {
brace_stack.append(bun.default_allocator, @intCast(self.tokens.items.len));
try self.tokens.append(.{ .open = .{} });
continue;
},
'}' => {
if (brace_stack.len() > 0) {
_ = brace_stack.pop();
try self.tokens.append(.close);
continue;
}
},
',' => {
if (brace_stack.len() > 0) {
try self.tokens.append(.comma);
continue;
}
},
else => {},
}
}
// if (char_stack.push(char) == char_stack.Error.StackFull) {
// try self.app
// }
try self.appendChar(char);
}
// Unclosed braces
while (brace_stack.len() > 0) {
const top_idx = brace_stack.pop().?;
self.rollbackBraces(top_idx);
}
try self.flattenTokens();
try self.tokens.append(.eof);
return self.contains_nested;
}
fn flattenTokens(self: *@This()) Allocator.Error!void {
if (self.tokens.items.len == 0) return;
var brace_count: u32 = if (self.tokens.items[0] == .open) 1 else 0;
var i: u32 = 0;
var j: u32 = 1;
while (i < self.tokens.items.len and j < self.tokens.items.len) {
var itok = &self.tokens.items[i];
var jtok = &self.tokens.items[j];
if (itok.* == .text and jtok.* == .text) {
try itok.text.appendSlice(self.alloc, jtok.toText().slice());
_ = self.tokens.orderedRemove(j);
} else {
if (jtok.* == .close) {
brace_count -= 1;
} else if (jtok.* == .open) {
brace_count += 1;
if (brace_count > 1) {
self.contains_nested = true;
}
}
i += 1;
j += 1;
}
}
}
fn rollbackBraces(self: *@This(), starting_idx: u32) void {
if (bun.Environment.allow_assert) {
const first = &self.tokens.items[starting_idx];
assert(first.* == .open);
}
var braces: u8 = 0;
self.replaceTokenWithString(starting_idx);
var i: u32 = starting_idx + 1;
while (i < self.tokens.items.len) : (i += 1) {
if (braces > 0) {
switch (self.tokens.items[i]) {
.open => {
braces += 1;
},
.close => {
braces -= 1;
},
else => {},
}
continue;
}
switch (self.tokens.items[i]) {
.open => {
braces += 1;
continue;
},
.close, .comma, .text => {
self.replaceTokenWithString(i);
},
.eof => {},
}
}
}
fn replaceTokenWithString(self: *@This(), token_idx: u32) void {
var tok = &self.tokens.items[token_idx];
const tok_text = tok.toText();
tok.* = .{ .text = tok_text };
}
fn appendChar(self: *@This(), char: Chars.CodepointType) Allocator.Error!void {
if (self.tokens.items.len > 0) {
var last = &self.tokens.items[self.tokens.items.len - 1];
if (last.* == .text) {
if (comptime encoding == .ascii) {
try last.text.appendChar(self.alloc, char);
return;
}
var buf = [4]u8{ 0, 0, 0, 0 };
const len = bun.strings.encodeWTF8Rune(&buf, @bitCast(char));
try last.text.appendSlice(self.alloc, buf[0..len]);
return;
}
}
if (comptime encoding == .ascii) {
try self.tokens.append(.{
.text = try SmolStr.fromSlice(self.alloc, &[_]u8{char}),
});
} else {
var buf = [4]u8{ 0, 0, 0, 0 };
const len = bun.strings.encodeWTF8Rune(&buf, @bitCast(char));
try self.tokens.append(.{
.text = try SmolStr.fromSlice(self.alloc, buf[0..len]),
});
}
}
fn eat(self: *@This()) ?Chars.InputChar {
return self.chars.eat();
}
fn read_char(self: *@This()) ?Chars.InputChar {
return self.chars.read_char();
}
};
}
test Lexer {
var arena = std.heap.ArenaAllocator.init(t.allocator);
defer arena.deinit();
const TestCase = struct { []const u8, []const Token };
const test_cases: []const TestCase = &[_]TestCase{
.{
"{}",
&[_]Token{ .{ .open = .{} }, .close, .eof },
},
.{
"{foo}",
&[_]Token{ .{ .open = .{} }, .{ .text = try SmolStr.fromSlice(arena.allocator(), "foo") }, .close, .eof },
},
};
for (test_cases) |test_case| {
const src, const expected = test_case;
// NOTE: don't use arena here so that we can test for memory leaks
var result = try Lexer.tokenize(t.allocator, src);
defer result.tokens.deinit();
try t.expectEqualSlices(
Token,
expected,
result.tokens.items,
);
}
}
const SmolStr = @import("../string/string.zig").SmolStr;
const Encoding = @import("../runtime/shell/shell.zig").StringEncoding;
const NewChars = @import("../runtime/shell/shell.zig").ShellCharIter;
const bun = @import("bun");
const assert = bun.assert;
const std = @import("std");
const t = std.testing;
const ArrayList = std.array_list.Managed;
const Allocator = std.mem.Allocator;
const BraceLexerError = Allocator.Error;