forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.zig
1445 lines (1245 loc) · 47.6 KB
/
logger.zig
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const Api = @import("./api/schema.zig").Api;
const js = @import("root").bun.JSC;
const ImportKind = @import("./import_record.zig").ImportKind;
const bun = @import("root").bun;
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
const Environment = bun.Environment;
const strings = bun.strings;
const MutableString = bun.MutableString;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
const JSC = @import("root").bun.JSC;
const fs = @import("fs.zig");
const unicode = std.unicode;
const Ref = @import("./ast/base.zig").Ref;
const expect = std.testing.expect;
const assert = std.debug.assert;
const ArrayList = std.ArrayList;
const StringBuilder = @import("./string_builder.zig");
const Index = @import("./ast/base.zig").Index;
pub const Kind = enum(i8) {
err,
warn,
note,
debug,
verbose,
pub inline fn shouldPrint(this: Kind, other: Log.Level) bool {
return switch (other) {
.err => switch (this) {
.err, .note => true,
else => false,
},
.warn => switch (this) {
.err, .warn, .note => true,
else => false,
},
.info, .debug => this != .verbose,
.verbose => true,
};
}
pub inline fn string(self: Kind) bun.string {
return switch (self) {
.err => "error",
.warn => "warn",
.note => "note",
.debug => "debug",
.verbose => "verbose",
};
}
pub inline fn toAPI(kind: Kind) Api.MessageLevel {
return switch (kind) {
.err => .err,
.warn => .warn,
.note => .note,
else => .debug,
};
}
};
// Do not mark these as packed
// https://github.com/ziglang/zig/issues/15715
pub const Loc = struct {
start: i32 = -1,
pub inline fn toNullable(loc: *Loc) ?Loc {
return if (loc.start == -1) null else loc.*;
}
pub const toUsize = i;
pub inline fn i(self: *const Loc) usize {
return @as(usize, @intCast(@max(self.start, 0)));
}
pub const Empty = Loc{ .start = -1 };
pub inline fn eql(loc: Loc, other: Loc) bool {
return loc.start == other.start;
}
pub fn jsonStringify(self: *const Loc, options: anytype, writer: anytype) !void {
return try std.json.stringify(self.start, options, writer);
}
};
pub const Location = struct {
file: string = "",
namespace: string = "file",
line: i32 = 1, // 1-based
column: i32 = 0, // 0-based, in bytes
length: usize = 0, // in bytes
line_text: ?string = null,
suggestion: ?string = null,
offset: usize = 0,
pub fn count(this: Location, builder: *StringBuilder) void {
builder.count(this.file);
builder.count(this.namespace);
if (this.line_text) |text| builder.count(text[0..@min(text.len, 690)]);
if (this.suggestion) |text| builder.count(text);
}
pub fn clone(this: Location, allocator: std.mem.Allocator) !Location {
// mostly to catch undefined memory
bun.assertDefined(this.namespace);
bun.assertDefined(this.file);
return Location{
.file = try allocator.dupe(u8, this.file),
.namespace = this.namespace,
.line = this.line,
.column = this.column,
.length = this.length,
.line_text = if (this.line_text != null) try allocator.dupe(u8, this.line_text.?) else null,
.suggestion = if (this.suggestion != null) try allocator.dupe(u8, this.suggestion.?) else null,
.offset = this.offset,
};
}
pub fn cloneWithBuilder(this: Location, string_builder: *StringBuilder) Location {
// mostly to catch undefined memory
bun.assertDefined(this.namespace);
bun.assertDefined(this.file);
return Location{
.file = string_builder.append(this.file),
.namespace = this.namespace,
.line = this.line,
.column = this.column,
.length = this.length,
.line_text = if (this.line_text != null) string_builder.append(this.line_text.?) else null,
.suggestion = if (this.suggestion != null) string_builder.append(this.suggestion.?) else null,
.offset = this.offset,
};
}
pub fn toAPI(this: *const Location) Api.Location {
bun.assertDefined(this.file);
bun.assertDefined(this.namespace);
return Api.Location{
.file = this.file,
.namespace = this.namespace,
.line = this.line,
.column = this.column,
.line_text = this.line_text orelse "",
.suggestion = this.suggestion orelse "",
.offset = @as(u32, @truncate(this.offset)),
};
}
// don't really know what's safe to deinit here!
pub fn deinit(_: *Location, _: std.mem.Allocator) void {}
pub fn init(file: string, namespace: string, line: i32, column: i32, length: u32, line_text: ?string, suggestion: ?string) Location {
// mostly to catch undefined memory
bun.assertDefined(file);
bun.assertDefined(namespace);
return Location{
.file = file,
.namespace = namespace,
.line = line,
.column = column,
.length = length,
.line_text = line_text,
.suggestion = suggestion,
.offset = length,
};
}
pub fn init_or_nil(_source: ?*const Source, r: Range) ?Location {
if (_source) |source| {
var data = source.initErrorPosition(r.loc);
var full_line = source.contents[data.line_start..data.line_end];
if (full_line.len > 80 + data.column_count) {
full_line = full_line[@max(data.column_count, 40) - 40 .. @min(data.column_count + 40, full_line.len - 40) + 40];
}
bun.assertDefined(source.path.text);
bun.assertDefined(source.path.namespace);
bun.assertDefined(full_line);
return Location{
.file = source.path.text,
.namespace = source.path.namespace,
.line = usize2Loc(data.line_count).start,
.column = usize2Loc(data.column_count).start,
.length = full_line.len,
.line_text = full_line,
.offset = @as(usize, @intCast(@max(r.loc.start, 0))),
};
} else {
return null;
}
}
};
pub const Data = struct {
text: string,
location: ?Location = null,
pub fn deinit(d: *Data, allocator: std.mem.Allocator) void {
if (d.location) |*loc| {
loc.deinit(allocator);
}
allocator.free(d.text);
}
pub fn cloneLineText(this: Data, should: bool, allocator: std.mem.Allocator) !Data {
if (!should or this.location == null or this.location.?.line_text == null)
return this;
var new_line_text = try allocator.dupe(u8, this.location.?.line_text.?);
var new_location = this.location.?;
new_location.line_text = new_line_text;
return Data{
.text = this.text,
.location = new_location,
};
}
pub fn clone(this: Data, allocator: std.mem.Allocator) !Data {
return Data{
.text = if (this.text.len > 0) try allocator.dupe(u8, this.text) else "",
.location = if (this.location != null) try this.location.?.clone(allocator) else null,
};
}
pub fn cloneWithBuilder(this: Data, builder: *StringBuilder) Data {
return Data{
.text = if (this.text.len > 0) builder.append(this.text) else "",
.location = if (this.location != null) this.location.?.cloneWithBuilder(builder) else null,
};
}
pub fn count(this: Data, builder: *StringBuilder) void {
builder.count(this.text);
if (this.location) |loc| loc.count(builder);
}
pub fn toAPI(this: *const Data) Api.MessageData {
return Api.MessageData{
.text = this.text,
.location = if (this.location != null) this.location.?.toAPI() else null,
};
}
pub fn writeFormat(
this: *const Data,
to: anytype,
kind: Kind,
comptime enable_ansi_colors: bool,
comptime is_note: bool,
) !void {
if (this.text.len == 0) return;
const message_color = switch (kind) {
.err => comptime Output.color_map.get("b").?,
.note => comptime Output.color_map.get("cyan").? ++ Output.color_map.get("d").?,
else => comptime Output.color_map.get("d").? ++ Output.color_map.get("b").?,
};
const color_name: string = switch (kind) {
.err => comptime Output.color_map.get("red").?,
.note => comptime Output.color_map.get("cyan").?,
else => comptime Output.color_map.get("d").?,
};
try to.writeAll("\n\n");
if (comptime enable_ansi_colors) {
try to.writeAll(color_name);
}
try to.writeAll(kind.string());
try std.fmt.format(to, comptime Output.prettyFmt("<r><d>: <r>", enable_ansi_colors), .{});
if (comptime enable_ansi_colors) {
try to.writeAll(message_color);
}
try std.fmt.format(to, comptime Output.prettyFmt("{s}<r>\n", enable_ansi_colors), .{this.text});
if (this.location) |location| {
if (location.line_text) |line_text_| {
const line_text = std.mem.trimRight(u8, line_text_, "\r\n\t");
const location_in_line_text = @as(u32, @intCast(@max(location.column, 1) - 1));
const has_position = location.column > -1 and line_text.len > 0 and location_in_line_text < line_text.len;
if (has_position) {
if (comptime enable_ansi_colors) {
const is_colored = message_color.len > 0;
const before_segment = line_text[0..location_in_line_text];
try to.writeAll(before_segment);
if (is_colored) {
try to.writeAll(color_name);
}
const rest_of_line = line_text[location_in_line_text..];
if (rest_of_line.len > 0) {
var end_of_segment: usize = 1;
var iter = strings.CodepointIterator.initOffset(rest_of_line, 1);
// extremely naive: we should really use IsIdentifierContinue || isIdentifierStart here
// highlight until we reach the next matching
switch (line_text[location_in_line_text]) {
'\'' => {
end_of_segment = iter.scanUntilQuotedValueOrEOF('\'');
},
'"' => {
end_of_segment = iter.scanUntilQuotedValueOrEOF('"');
},
'<' => {
end_of_segment = iter.scanUntilQuotedValueOrEOF('>');
},
'`' => {
end_of_segment = iter.scanUntilQuotedValueOrEOF('`');
},
else => {},
}
try to.writeAll(rest_of_line[0..end_of_segment]);
if (is_colored) {
try to.writeAll("\x1b[0m");
}
try to.writeAll(rest_of_line[end_of_segment..]);
} else if (is_colored) {
try to.writeAll("\x1b[0m");
}
} else {
try to.writeAll(line_text);
}
try to.writeAll("\n");
try to.writeByteNTimes(' ', location_in_line_text);
if (comptime enable_ansi_colors) {
const is_colored = message_color.len > 0;
if (is_colored) {
try to.writeAll(message_color);
try to.writeAll(color_name);
// always bold the ^
try to.writeAll(comptime Output.color_map.get("b").?);
}
try to.writeByte('^');
if (is_colored) {
try to.writeAll("\x1b[0m\n");
}
} else {
try to.writeAll("^\n");
}
}
}
if (location.file.len > 0) {
if (comptime enable_ansi_colors) {
if (!is_note and kind == .err) {
try to.writeAll(comptime Output.color_map.get("b").?);
} else {}
}
try std.fmt.format(to, comptime Output.prettyFmt("{s}<r>", enable_ansi_colors), .{
location.file,
});
if (location.line > -1 and location.column > -1) {
try std.fmt.format(to, comptime Output.prettyFmt("<d>:<r><yellow>{d}<r><d>:<r><yellow>{d}<r> <d>{d}<r>", enable_ansi_colors), .{
location.line,
location.column,
location.offset,
});
} else if (location.line > -1) {
try std.fmt.format(to, comptime Output.prettyFmt("<d>:<r><yellow>{d}<r> <d>{d}<r>", enable_ansi_colors), .{
location.line,
location.offset,
});
}
}
}
}
};
pub const BabyString = packed struct {
offset: u16,
len: u16,
pub fn in(parent: string, text: string) BabyString {
return BabyString{
.offset = @as(u16, @truncate(std.mem.indexOf(u8, parent, text) orelse unreachable)),
.len = @as(u16, @truncate(text.len)),
};
}
pub fn slice(this: BabyString, container: string) string {
return container[this.offset..][0..this.len];
}
};
pub const Msg = struct {
kind: Kind = Kind.err,
data: Data,
metadata: Metadata = .{ .build = 0 },
notes: ?[]Data = null,
pub fn fromJS(allocator: std.mem.Allocator, globalObject: *bun.JSC.JSGlobalObject, file: string, err: bun.JSC.JSValue) !Msg {
var zig_exception_holder: bun.JSC.ZigException.Holder = bun.JSC.ZigException.Holder.init();
if (err.toError()) |value| {
value.toZigException(globalObject, zig_exception_holder.zigException());
} else {
zig_exception_holder.zig_exception.message = err.toBunString(globalObject);
}
return Msg{
.data = .{
.text = try zig_exception_holder.zigException().message.toOwnedSlice(allocator),
.location = Location{
.file = file,
},
},
};
}
pub fn toJS(this: Msg, globalObject: *bun.JSC.JSGlobalObject, allocator: std.mem.Allocator) JSC.JSValue {
return switch (this.metadata) {
.build => JSC.BuildMessage.create(globalObject, allocator, this),
.resolve => JSC.ResolveMessage.create(globalObject, allocator, this, ""),
};
}
pub fn count(this: *const Msg, builder: *StringBuilder) void {
this.data.count(builder);
if (this.notes) |notes| {
for (notes) |note| {
note.count(builder);
}
}
}
pub fn clone(this: *const Msg, allocator: std.mem.Allocator) !Msg {
return Msg{
.kind = this.kind,
.data = try this.data.clone(allocator),
.metadata = this.metadata,
.notes = if (this.notes != null and this.notes.?.len > 0)
try bun.clone(this.notes.?, allocator)
else
null,
};
}
pub fn cloneWithBuilder(this: *const Msg, notes: []Data, builder: *StringBuilder) Msg {
return Msg{
.kind = this.kind,
.data = this.data.cloneWithBuilder(builder),
.metadata = this.metadata,
.notes = if (this.notes != null and this.notes.?.len > 0) brk: {
for (this.notes.?, 0..) |note, i| {
notes[i] = note.cloneWithBuilder(builder);
}
break :brk notes[0..this.notes.?.len];
} else null,
};
}
pub const Metadata = union(Tag) {
build: u0,
resolve: Resolve,
pub const Tag = enum(u8) {
build = 1,
resolve = 2,
};
pub const Resolve = struct {
specifier: BabyString,
import_kind: ImportKind,
err: anyerror = error.ModuleNotFound,
};
};
pub fn toAPI(this: *const Msg, allocator: std.mem.Allocator) !Api.Message {
const notes_len = if (this.notes != null) this.notes.?.len else 0;
var _notes = try allocator.alloc(
Api.MessageData,
notes_len,
);
var msg = Api.Message{
.level = this.kind.toAPI(),
.data = this.data.toAPI(),
.notes = _notes,
.on = Api.MessageMeta{
.resolve = if (this.metadata == .resolve) this.metadata.resolve.specifier.slice(this.data.text) else "",
.build = this.metadata == .build,
},
};
if (this.notes) |notes| {
if (notes.len > 0) {
for (notes, 0..) |note, i| {
_notes[i] = note.toAPI();
}
}
}
return msg;
}
pub fn toAPIFromList(comptime ListType: type, list: ListType, allocator: std.mem.Allocator) ![]Api.Message {
var out_list = try allocator.alloc(Api.Message, list.items.len);
for (list.items, 0..) |item, i| {
out_list[i] = try item.toAPI(allocator);
}
return out_list;
}
pub fn deinit(msg: *Msg, allocator: std.mem.Allocator) void {
msg.data.deinit(allocator);
if (msg.notes) |notes| {
for (notes) |*note| {
note.deinit(allocator);
}
}
msg.notes = null;
}
pub fn writeFormat(
msg: *const Msg,
to: anytype,
comptime enable_ansi_colors: bool,
) !void {
try msg.data.writeFormat(to, msg.kind, enable_ansi_colors, false);
if (msg.notes) |notes| {
for (notes) |note| {
try note.writeFormat(to, .note, enable_ansi_colors, true);
}
}
}
pub fn formatWriter(
msg: *const Msg,
comptime Writer: type,
writer: Writer,
comptime _: bool,
) !void {
if (msg.data.location) |location| {
try writer.print("{s}: {s}\n{s}\n{s}:{}:{} ({d})", .{
msg.kind.string(),
msg.data.text,
location.line_text,
location.file,
location.line,
location.column,
location.offset,
});
} else {
try writer.print("{s}: {s}", .{
msg.kind.string(),
msg.data.text,
});
}
}
pub fn formatNoWriter(msg: *const Msg, comptime formatterFunc: @TypeOf(Global.panic)) void {
formatterFunc("\n\n{s}: {s}\n{s}\n{s}:{}:{} ({d})", .{
msg.kind.string(),
msg.data.text,
msg.data.location.?.line_text,
msg.data.location.?.file,
msg.data.location.?.line,
msg.data.location.?.column,
msg.data.location.?.offset,
});
}
};
// Do not mark these as packed
// https://github.com/ziglang/zig/issues/15715
pub const Range = struct {
loc: Loc = Loc.Empty,
len: i32 = 0,
pub const None = Range{ .loc = Loc.Empty, .len = 0 };
pub fn in(this: Range, buf: []const u8) []const u8 {
if (this.loc.start < 0 or this.len <= 0) return "";
const slice = buf[@as(usize, @intCast(this.loc.start))..];
return slice[0..@min(@as(usize, @intCast(this.len)), buf.len)];
}
pub fn contains(this: Range, k: i32) bool {
return k >= this.loc.start and k < this.loc.start + this.len;
}
pub fn isEmpty(r: *const Range) bool {
return r.len == 0 and r.loc.start == Loc.Empty.start;
}
pub fn end(self: *const Range) Loc {
return Loc{ .start = self.loc.start + self.len };
}
pub fn endI(self: *const Range) usize {
return std.math.lossyCast(usize, self.loc.start + self.len);
}
pub fn jsonStringify(self: *const Range, options: anytype, writer: anytype) !void {
return try std.json.stringify([2]i32{ self.loc.start, self.len + self.loc.start }, options, writer);
}
};
pub const Log = struct {
debug: bool = false,
warnings: usize = 0,
errors: usize = 0,
msgs: ArrayList(Msg),
level: Level = if (Environment.isDebug) Level.info else Level.warn,
clone_line_text: bool = false,
pub inline fn hasErrors(this: *const Log) bool {
return this.errors > 0;
}
pub fn reset(this: *Log) void {
this.msgs.clearRetainingCapacity();
this.warnings = 0;
this.errors = 0;
}
pub var default_log_level = Level.warn;
pub fn hasAny(this: *const Log) bool {
return (this.warnings + this.errors) > 0;
}
pub fn toAPI(this: *const Log, allocator: std.mem.Allocator) !Api.Log {
var warnings: u32 = 0;
var errors: u32 = 0;
for (this.msgs.items) |msg| {
errors += @as(u32, @intCast(@intFromBool(msg.kind == .err)));
warnings += @as(u32, @intCast(@intFromBool(msg.kind == .warn)));
}
return Api.Log{
.warnings = warnings,
.errors = errors,
.msgs = try Msg.toAPIFromList(@TypeOf(this.msgs), this.msgs, allocator),
};
}
pub const Level = enum(i8) {
verbose,
debug,
info,
warn,
err,
pub fn atLeast(this: Level, other: Level) bool {
return @intFromEnum(this) <= @intFromEnum(other);
}
pub const label: std.EnumArray(Level, string) = brk: {
var map = std.EnumArray(Level, string).initFill("");
map.set(Level.verbose, "verbose");
map.set(Level.debug, "debug");
map.set(Level.info, "info");
map.set(Level.warn, "warn");
map.set(Level.err, "error");
break :brk map;
};
pub const Map = bun.ComptimeStringMap(Level, .{
.{ "verbose", Level.verbose },
.{ "debug", Level.debug },
.{ "info", Level.info },
.{ "warn", Level.warn },
.{ "error", Level.err },
});
};
pub fn init(allocator: std.mem.Allocator) Log {
return Log{
.msgs = ArrayList(Msg).init(allocator),
.level = default_log_level,
};
}
pub fn initComptime(allocator: std.mem.Allocator) Log {
return Log{
.msgs = ArrayList(Msg).init(allocator),
};
}
pub fn addVerbose(log: *Log, source: ?*const Source, loc: Loc, text: string) !void {
@setCold(true);
try log.addMsg(.{
.kind = .verbose,
.data = rangeData(source, Range{ .loc = loc }, text),
});
}
pub fn toJS(this: Log, global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, fmt: string) JSC.JSValue {
const msgs: []const Msg = this.msgs.items;
var errors_stack: [256]*anyopaque = undefined;
const count = @as(u16, @intCast(@min(msgs.len, errors_stack.len)));
switch (count) {
0 => return JSC.JSValue.jsUndefined(),
1 => {
const msg = msgs[0];
return switch (msg.metadata) {
.build => JSC.BuildMessage.create(global, allocator, msg),
.resolve => JSC.ResolveMessage.create(global, allocator, msg, ""),
};
},
else => {
for (msgs[0..count], 0..) |msg, i| {
errors_stack[i] = switch (msg.metadata) {
.build => JSC.BuildMessage.create(global, allocator, msg).asVoid(),
.resolve => JSC.ResolveMessage.create(global, allocator, msg, "").asVoid(),
};
}
const out = JSC.ZigString.init(fmt);
const agg = global.createAggregateError(errors_stack[0..count].ptr, count, &out);
return agg;
},
}
}
pub fn toJSArray(this: Log, global: *JSC.JSGlobalObject, allocator: std.mem.Allocator) JSC.JSValue {
const msgs: []const Msg = this.msgs.items;
var errors_stack: [256]*anyopaque = undefined;
const count = @as(u16, @intCast(@min(msgs.len, errors_stack.len)));
var arr = JSC.JSValue.createEmptyArray(global, count);
for (msgs[0..count], 0..) |msg, i| {
arr.putIndex(global, @as(u32, @intCast(i)), msg.toJS(global, allocator));
}
return arr;
}
pub fn cloneTo(self: *Log, other: *Log) !void {
var notes_count: usize = 0;
for (self.msgs.items) |msg_| {
const msg: Msg = msg_;
if (msg.notes) |notes| {
for (notes) |note| {
notes_count += @as(usize, @intCast(@intFromBool(note.text.len > 0)));
}
}
}
if (notes_count > 0) {
var notes = try other.msgs.allocator.alloc(Data, notes_count);
var note_i: usize = 0;
for (self.msgs.items) |*msg| {
if (msg.notes) |current_notes| {
var start_note_i: usize = note_i;
for (current_notes) |note| {
notes[note_i] = note;
note_i += 1;
}
msg.notes = notes[start_note_i..note_i];
}
}
}
try other.msgs.appendSlice(self.msgs.items);
other.warnings += self.warnings;
other.errors += self.errors;
}
pub fn appendTo(self: *Log, other: *Log) !void {
try self.cloneTo(other);
self.msgs.clearAndFree();
}
pub fn cloneToWithRecycled(self: *Log, other: *Log, recycled: bool) !void {
try other.msgs.appendSlice(self.msgs.items);
other.warnings += self.warnings;
other.errors += self.errors;
if (recycled) {
var string_builder = StringBuilder{};
var notes_count: usize = 0;
{
var i: usize = 0;
var j: usize = other.msgs.items.len - self.msgs.items.len;
while (i < self.msgs.items.len) : ({
i += 1;
j += 1;
}) {
const msg: Msg = self.msgs.items[i];
msg.count(&string_builder);
if (msg.notes) |notes| {
notes_count += notes.len;
}
}
}
try string_builder.allocate(other.msgs.allocator);
var notes_buf = try other.msgs.allocator.alloc(Data, notes_count);
var note_i: usize = 0;
{
var i: usize = 0;
var j: usize = other.msgs.items.len - self.msgs.items.len;
while (i < self.msgs.items.len) : ({
i += 1;
j += 1;
}) {
const msg: Msg = self.msgs.items[i];
other.msgs.items[j] = msg.cloneWithBuilder(notes_buf[note_i..], &string_builder);
note_i += (msg.notes orelse &[_]Data{}).len;
}
}
}
}
pub fn appendToWithRecycled(self: *Log, other: *Log, recycled: bool) !void {
try self.cloneToWithRecycled(other, recycled);
self.msgs.clearAndFree();
}
pub fn appendToMaybeRecycled(self: *Log, other: *Log, source: *const Source) !void {
return self.appendToWithRecycled(other, source.contents_is_recycled);
}
pub fn deinit(self: *Log) void {
self.msgs.clearAndFree();
}
pub fn addVerboseWithNotes(log: *Log, source: ?*const Source, loc: Loc, text: string, notes: []Data) !void {
@setCold(true);
if (!Kind.shouldPrint(.verbose, log.level)) return;
try log.addMsg(.{
.kind = .verbose,
.data = rangeData(source, Range{ .loc = loc }, text),
.notes = notes,
});
}
inline fn allocPrint(allocator: std.mem.Allocator, comptime fmt: string, args: anytype) !string {
return try switch (Output.enable_ansi_colors) {
inline else => |enable_ansi_colors| std.fmt.allocPrint(allocator, Output.prettyFmt(fmt, enable_ansi_colors), args),
};
}
inline fn _addResolveErrorWithLevel(
log: *Log,
source: ?*const Source,
r: Range,
allocator: std.mem.Allocator,
comptime fmt: string,
args: anytype,
import_kind: ImportKind,
comptime dupe_text: bool,
comptime is_error: bool,
err: anyerror,
) !void {
const text = try allocPrint(allocator, fmt, args);
// TODO: fix this. this is stupid, it should be returned in allocPrint.
const specifier = BabyString.in(text, args.@"0");
if (comptime is_error) {
log.errors += 1;
} else {
log.warnings += 1;
}
const data = if (comptime dupe_text) brk: {
var _data = rangeData(
source,
r,
text,
);
if (_data.location != null) {
if (_data.location.?.line_text) |line| {
_data.location.?.line_text = allocator.dupe(u8, line) catch unreachable;
}
}
break :brk _data;
} else rangeData(
source,
r,
text,
);
const msg = Msg{
.kind = if (comptime is_error) Kind.err else Kind.warn,
.data = data,
.metadata = .{ .resolve = Msg.Metadata.Resolve{
.specifier = specifier,
.import_kind = import_kind,
.err = err,
} },
};
try log.addMsg(msg);
}
inline fn _addResolveError(
log: *Log,
source: ?*const Source,
r: Range,
allocator: std.mem.Allocator,
comptime fmt: string,
args: anytype,
import_kind: ImportKind,
comptime dupe_text: bool,
err: anyerror,
) !void {
return _addResolveErrorWithLevel(log, source, r, allocator, fmt, args, import_kind, dupe_text, true, err);
}
inline fn _addResolveWarn(
log: *Log,
source: ?*const Source,
r: Range,
allocator: std.mem.Allocator,
comptime fmt: string,
args: anytype,
import_kind: ImportKind,
comptime dupe_text: bool,
err: anyerror,
) !void {
return _addResolveErrorWithLevel(log, source, r, allocator, fmt, args, import_kind, dupe_text, false, err);
}
pub fn addResolveError(
log: *Log,
source: ?*const Source,
r: Range,
allocator: std.mem.Allocator,
comptime fmt: string,
args: anytype,
import_kind: ImportKind,
err: anyerror,
) !void {
@setCold(true);
return try _addResolveError(log, source, r, allocator, fmt, args, import_kind, false, err);
}
pub fn addResolveErrorWithTextDupe(
log: *Log,
source: ?*const Source,
r: Range,
allocator: std.mem.Allocator,
comptime fmt: string,
args: anytype,
import_kind: ImportKind,
) !void {
@setCold(true);
return try _addResolveError(log, source, r, allocator, fmt, args, import_kind, true, error.ModuleNotFound);
}
pub fn addResolveErrorWithTextDupeMaybeWarn(
log: *Log,
source: ?*const Source,
r: Range,
allocator: std.mem.Allocator,
comptime fmt: string,
args: anytype,
import_kind: ImportKind,
warn: bool,
) !void {
@setCold(true);
if (warn) {
return try _addResolveError(log, source, r, allocator, fmt, args, import_kind, true, error.ModuleNotFound);
} else {
return try _addResolveWarn(log, source, r, allocator, fmt, args, import_kind, true, error.ModuleNotFound);
}
}
pub fn addRangeError(log: *Log, source: ?*const Source, r: Range, text: string) !void {
@setCold(true);
log.errors += 1;
try log.addMsg(.{
.kind = .err,
.data = rangeData(source, r, text),
});
}