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
|
//! Expects to run after a C preprocessor step that preserves comments.
//!
//! `rc` has a peculiar quirk where something like `blah/**/blah` will be
//! transformed into `blahblah` during parsing. However, `clang -E` will
//! transform it into `blah blah`, so in order to match `rc`, we need
//! to remove comments ourselves after the preprocessor runs.
//! Note: Multiline comments that actually span more than one line do
//! get translated to a space character by `rc`.
//!
//! Removing comments before lexing also allows the lexer to not have to
//! deal with comments which would complicate its implementation (this is something
//! of a tradeoff, as removing comments in a separate pass means that we'll
//! need to iterate the source twice instead of once, but having to deal with
//! comments when lexing would be a pain).
const std = @import("std");
const Allocator = std.mem.Allocator;
const UncheckedSliceWriter = @import("utils.zig").UncheckedSliceWriter;
const SourceMappings = @import("source_mapping.zig").SourceMappings;
const LineHandler = @import("lex.zig").LineHandler;
const formsLineEndingPair = @import("source_mapping.zig").formsLineEndingPair;
/// `buf` must be at least as long as `source`
/// In-place transformation is supported (i.e. `source` and `buf` can be the same slice)
pub fn removeComments(source: []const u8, buf: []u8, source_mappings: ?*SourceMappings) []u8 {
std.debug.assert(buf.len >= source.len);
var result = UncheckedSliceWriter{ .slice = buf };
const State = enum {
start,
forward_slash,
line_comment,
multiline_comment,
multiline_comment_end,
single_quoted,
single_quoted_escape,
double_quoted,
double_quoted_escape,
};
var state: State = .start;
var index: usize = 0;
var pending_start: ?usize = null;
var line_handler = LineHandler{ .buffer = source };
while (index < source.len) : (index += 1) {
const c = source[index];
// TODO: Disallow \x1A, \x00, \x7F in comments. At least \x1A and \x00 can definitely
// cause errors or parsing weirdness in the Win32 RC compiler. These are disallowed
// in the lexer, but comments are stripped before getting to the lexer.
switch (state) {
.start => switch (c) {
'/' => {
state = .forward_slash;
pending_start = index;
},
'\r', '\n' => {
_ = line_handler.incrementLineNumber(index);
result.write(c);
},
else => {
switch (c) {
'"' => state = .double_quoted,
'\'' => state = .single_quoted,
else => {},
}
result.write(c);
},
},
.forward_slash => switch (c) {
'/' => state = .line_comment,
'*' => {
state = .multiline_comment;
},
else => {
_ = line_handler.maybeIncrementLineNumber(index);
result.writeSlice(source[pending_start.? .. index + 1]);
pending_start = null;
state = .start;
},
},
.line_comment => switch (c) {
'\r', '\n' => {
_ = line_handler.incrementLineNumber(index);
result.write(c);
state = .start;
},
else => {},
},
.multiline_comment => switch (c) {
'\r' => handleMultilineCarriageReturn(source, &line_handler, index, &result, source_mappings),
'\n' => {
_ = line_handler.incrementLineNumber(index);
result.write(c);
},
'*' => state = .multiline_comment_end,
else => {},
},
.multiline_comment_end => switch (c) {
'\r' => {
handleMultilineCarriageReturn(source, &line_handler, index, &result, source_mappings);
// We only want to treat this as a newline if it's part of a CRLF pair. If it's
// not, then we still want to stay in .multiline_comment_end, so that e.g. `*<\r>/` still
// functions as a `*/` comment ending. Kinda crazy, but that's how the Win32 implementation works.
if (formsLineEndingPair(source, '\r', index + 1)) {
state = .multiline_comment;
}
},
'\n' => {
_ = line_handler.incrementLineNumber(index);
result.write(c);
state = .multiline_comment;
},
'/' => {
state = .start;
},
else => {
state = .multiline_comment;
},
},
.single_quoted => switch (c) {
'\r', '\n' => {
_ = line_handler.incrementLineNumber(index);
state = .start;
result.write(c);
},
'\\' => {
state = .single_quoted_escape;
result.write(c);
},
'\'' => {
state = .start;
result.write(c);
},
else => {
result.write(c);
},
},
.single_quoted_escape => switch (c) {
'\r', '\n' => {
_ = line_handler.incrementLineNumber(index);
state = .start;
result.write(c);
},
else => {
state = .single_quoted;
result.write(c);
},
},
.double_quoted => switch (c) {
'\r', '\n' => {
_ = line_handler.incrementLineNumber(index);
state = .start;
result.write(c);
},
'\\' => {
state = .double_quoted_escape;
result.write(c);
},
'"' => {
state = .start;
result.write(c);
},
else => {
result.write(c);
},
},
.double_quoted_escape => switch (c) {
'\r', '\n' => {
_ = line_handler.incrementLineNumber(index);
state = .start;
result.write(c);
},
else => {
state = .double_quoted;
result.write(c);
},
},
}
}
return result.getWritten();
}
inline fn handleMultilineCarriageReturn(
source: []const u8,
line_handler: *LineHandler,
index: usize,
result: *UncheckedSliceWriter,
source_mappings: ?*SourceMappings,
) void {
// Note: Bare \r within a multiline comment should *not* be treated as a line ending for the
// purposes of removing comments, but *should* be treated as a line ending for the
// purposes of line counting/source mapping
_ = line_handler.incrementLineNumber(index);
// So only write the \r if it's part of a CRLF pair
if (formsLineEndingPair(source, '\r', index + 1)) {
result.write('\r');
}
// And otherwise, we want to collapse the source mapping so that we can still know which
// line came from where.
else {
// Because the line gets collapsed, we need to decrement line number so that
// the next collapse acts on the first of the collapsed line numbers
line_handler.line_number -= 1;
if (source_mappings) |mappings| {
mappings.collapse(line_handler.line_number, 1);
}
}
}
pub fn removeCommentsAlloc(allocator: Allocator, source: []const u8, source_mappings: ?*SourceMappings) ![]u8 {
const buf = try allocator.alloc(u8, source.len);
errdefer allocator.free(buf);
const result = removeComments(source, buf, source_mappings);
return allocator.realloc(buf, result.len);
}
fn testRemoveComments(expected: []const u8, source: []const u8) !void {
const result = try removeCommentsAlloc(std.testing.allocator, source, null);
defer std.testing.allocator.free(result);
try std.testing.expectEqualStrings(expected, result);
}
test "basic" {
try testRemoveComments("", "// comment");
try testRemoveComments("", "/* comment */");
}
test "mixed" {
try testRemoveComments("hello", "hello// comment");
try testRemoveComments("hello", "hel/* comment */lo");
}
test "within a string" {
// escaped " is \"
try testRemoveComments(
\\blah"//som\"/*ething*/"BLAH
,
\\blah"//som\"/*ething*/"BLAH
);
}
test "line comments retain newlines" {
try testRemoveComments(
\\
\\
\\
,
\\// comment
\\// comment
\\// comment
);
try testRemoveComments("\r\n", "//comment\r\n");
}
test "crazy" {
try testRemoveComments(
\\blah"/*som*/\""BLAH
,
\\blah"/*som*/\""/*ething*/BLAH
);
try testRemoveComments(
\\blah"/*som*/"BLAH RCDATA "BEGIN END
\\
\\
\\hello
\\"
,
\\blah"/*som*/"/*ething*/BLAH RCDATA "BEGIN END
\\// comment
\\//"blah blah" RCDATA {}
\\hello
\\"
);
}
test "multiline comment with newlines" {
// bare \r is not treated as a newline
try testRemoveComments("blahblah", "blah/*some\rthing*/blah");
try testRemoveComments(
\\blah
\\blah
,
\\blah/*some
\\thing*/blah
);
try testRemoveComments(
"blah\r\nblah",
"blah/*some\r\nthing*/blah",
);
// handle *<not /> correctly
try testRemoveComments(
\\blah
\\
\\
,
\\blah/*some
\\thing*
\\/bl*ah*/
);
}
test "comments appended to a line" {
try testRemoveComments(
\\blah
\\blah
,
\\blah // line comment
\\blah
);
try testRemoveComments(
"blah \r\nblah",
"blah // line comment\r\nblah",
);
}
test "remove comments with mappings" {
const allocator = std.testing.allocator;
var mut_source = "blah/*\rcommented line*\r/blah".*;
var mappings = SourceMappings{};
_ = try mappings.files.put(allocator, "test.rc");
try mappings.set(allocator, 1, .{ .start_line = 1, .end_line = 1, .filename_offset = 0 });
try mappings.set(allocator, 2, .{ .start_line = 2, .end_line = 2, .filename_offset = 0 });
try mappings.set(allocator, 3, .{ .start_line = 3, .end_line = 3, .filename_offset = 0 });
defer mappings.deinit(allocator);
const result = removeComments(&mut_source, &mut_source, &mappings);
try std.testing.expectEqualStrings("blahblah", result);
try std.testing.expectEqual(@as(usize, 1), mappings.mapping.items.len);
try std.testing.expectEqual(@as(usize, 3), mappings.mapping.items[0].end_line);
}
test "in place" {
var mut_source = "blah /* comment */ blah".*;
const result = removeComments(&mut_source, &mut_source, null);
try std.testing.expectEqualStrings("blah blah", result);
}
|