Skip to content

Commit a67c2ab

Browse files
committed
GH#8 - preserve newlines when collapsing whitespace
When we collapse a series of whitespace characters, *if* that series of characters happens to contain a newline character in it then we will collapse *to* a newline character. That way, we don't accidentally break "semi-colons are optional in JavaScript" by collapsing multiple statements onto a single line.
1 parent 5f92c24 commit a67c2ab

3 files changed

Lines changed: 25 additions & 0 deletions

File tree

Changes

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
Revision history for Perl extension JavaScript::Minifier::XS.
22

33
{{$NEXT}}
4+
- GH#8 - preserve newlines when collapsing whitespace; if a block of
5+
whitespace contains a newline, then when collapsing we collapse to a
6+
newline character, not just "the first whitespace char we found"
47

58
0.14 2021-02-06 23:36:36-08:00 America/Vancouver
69
- rewrote test suite into a single ".t" test

XS.xs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,21 @@ void JsAppendNode(Node* element, Node* node) {
283283
/* collapses a node to a single whitespace character */
284284
void JsCollapseNodeToWhitespace(Node* node) {
285285
if (node->contents && (node->length > 1)) {
286+
/* does the node contain endspace? */
287+
size_t offset = 0;
288+
bool hasEndspace = 0;
289+
while (offset < node->length) {
290+
if (charIsEndspace(node->contents[offset++])) {
291+
hasEndspace = 1;
292+
break;
293+
}
294+
}
295+
296+
/* collapse node, either to endspace, or to the first whitespace char */
286297
node->length = 1;
298+
if (hasEndspace) {
299+
node->contents[0] = '\n';
300+
}
287301
node->contents[1] = '\0';
288302
}
289303
}

t/minify.t

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,14 @@ subtest 'trailing whitespace can be removed' => sub {
2121
is $got, $expect;
2222
};
2323

24+
###############################################################################
25+
subtest 'whitespace collapsing preserves newlines' => sub {
26+
my $given = qq{var a=3 \n\rvar a=5};
27+
my $expect = qq{var a=3\nvar a=5};
28+
my $got = minify($given);
29+
is $got, $expect;
30+
};
31+
2432
###############################################################################
2533
subtest 'comments' => sub {;
2634
subtest 'block comments' => sub {

0 commit comments

Comments
 (0)