Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🚀 Flatten Literals in TemplateLiterals #27516

Merged
Expand Up @@ -77,7 +77,7 @@ module.exports = function ({types: t}) {
function containsThisExpression(path) {
let containsThis = false;
path.traverse({
ThisExpression() {
ThisExpression(path) {
containsThis = true;
path.stop();
},
Expand Down
@@ -0,0 +1,148 @@
/**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

const MERGEABLE_TYPES = ['StringLiteral', 'NumericLiteral', 'TemplateLiteral'];

module.exports = function ({types: t}) {
const cloneNodes = (nodes) => nodes.map((node) => t.cloneNode(node));
const escapeStringForTemplateLiteral = (value) =>
String(value).replace(/\x60/g, '\\`');
const canMergeBinaryExpression = (binaryExpression) =>
MERGEABLE_TYPES.includes(binaryExpression.left.type) &&
MERGEABLE_TYPES.includes(binaryExpression.right.type) &&
binaryExpression.operator === '+';

function whichCloneQuasi(clonedQuasis, index) {
for (let i = index; i >= 0; i--) {
const quasi = clonedQuasis[i];
if (quasi !== null) {
return index;
}
}
}

return {
name: 'flatten-stringish-literals',
visitor: {
BinaryExpression: {
exit(path) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Absolutely. Good idea, will address in a followup.

if (!canMergeBinaryExpression(path.node)) {
return;
}

const {left, right} = path.node;
if (t.isTemplateLiteral(right)) {
const rightQuasis = cloneNodes(right.quasis);

if (t.isTemplateLiteral(left)) {
const leftQuasis = cloneNodes(left.quasis);
const finalLeftQuasi = leftQuasis[leftQuasis.length - 1];
leftQuasis[leftQuasis.length - 1].value = {
raw: finalLeftQuasi.value.raw + rightQuasis[0].value.raw,
cooked: finalLeftQuasi.value.cooked + rightQuasis[0].value.raw,
};
rightQuasis[0] = null;

path.replaceWith(
t.templateLiteral(
[...leftQuasis, ...rightQuasis.filter(Boolean)],
[
...cloneNodes(left.expressions),
...cloneNodes(right.expressions),
]
)
);
return;
}

// Left is a literal, containing a value to merge into the right.
const leftValue = escapeStringForTemplateLiteral(left.value);
rightQuasis[0].value = {
raw: leftValue + rightQuasis[0].value.raw,
cooked: leftValue + rightQuasis[0].value.cooked,
};
path.replaceWith(
t.templateLiteral(rightQuasis, cloneNodes(right.expressions))
);
}

// Right is a literal containing a value to merge into the left.
if (t.isTemplateLiteral(left)) {
const rightValue = escapeStringForTemplateLiteral(right.value);
const leftQuasis = cloneNodes(left.quasis);
const finalLeftQuasi = leftQuasis[leftQuasis.length - 1];
leftQuasis[leftQuasis.length - 1].value = {
raw: finalLeftQuasi.value.raw + rightValue,
cooked: finalLeftQuasi.value.cooked + rightValue,
};

path.replaceWith(
t.templateLiteral(leftQuasis, cloneNodes(left.expressions))
);
return;
}

// Merge two string literals
if (t.isStringLiteral(left) && t.isStringLiteral(right)) {
const newLiteral = t.cloneNode(left);
newLiteral.value = left.value + String(right.value);
path.replaceWith(newLiteral);
}
},
},
TemplateLiteral(path) {
const {expressions, quasis} = path.node;
const newQuasis = cloneNodes(quasis);
const newExpressions = cloneNodes(expressions);
let conversions = 0;

for (let index = expressions.length; index >= 0; index--) {
const expression = expressions[index];
if (
t.isStringLiteral(expression) ||
t.isNumericLiteral(expression) ||
t.isBooleanLiteral(expression)
) {
const {value} = expression;
const readIndex = whichCloneQuasi(newQuasis, index + 1);
const modifyIndex = whichCloneQuasi(newQuasis, index);
const {value: changedValue} = newQuasis[readIndex];
const {value: previousValue} = newQuasis[modifyIndex];

newQuasis[modifyIndex] = t.templateElement({
raw: previousValue.raw + value + changedValue.raw,
cooked: previousValue.cooked + value + changedValue.cooked,
});
newQuasis[index + 1] = null;
newExpressions[index] = null;
conversions++;
}
}

if (conversions === 0) {
return;
}

path.replaceWith(
t.templateLiteral(
newQuasis.filter(Boolean),
newExpressions.filter(Boolean)
)
);
},
},
};
};
@@ -0,0 +1,33 @@
/**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

let add = `/rtv` + `/bar`;
let multipleAdd = `/rtv` + `/bar` + `/`;
let subtract = `/rtv` - `r`;
let multiply = `/rtv` * `r`;
let divide = `/rtv` / `r`;

let numberStart = 1 + `/foo`;
let stringStart = '1' + `/foo`;
let numberEnd = `foo/` + 1;
let stringEnd = `foo/` + '1';
let illegalCharacter = `Invalid share providers configuration for in bookend. ` + 'Value must be `true` or a params object.';

let stringLiterals = '1' + '2';
let numberLiterals = 1 + 2;
let booleanLiterals = false + true;

let identifiers = `${foo}` + `${bar}`;
@@ -0,0 +1,3 @@
{
"plugins": ["../../../../../babel-plugin-transform-stringish-literals"]
}
@@ -0,0 +1,29 @@
/**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
let add = `/rtv/bar`;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Terser seems to accomplish all of these.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at the output of our build process, it is not for us. Would prefer to have less reliance on terser for these kinds of changes.

let multipleAdd = `/rtv/bar/`;
let subtract = `/rtv` - `r`;
let multiply = `/rtv` * `r`;
let divide = `/rtv` / `r`;
let numberStart = `1/foo`;
let stringStart = `1/foo`;
let numberEnd = `foo/1`;
let stringEnd = `foo/1`;
let illegalCharacter = `Invalid share providers configuration for in bookend. Value must be \`true\` or a params object.`;
let stringLiterals = "12";
let numberLiterals = 1 + 2;
let booleanLiterals = false + true;
let identifiers = `${foo}${bar}`;
@@ -0,0 +1,22 @@
/**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

let none = `/rtv/100/log-messages.simple.json`;
let start = `${'123'}/foo`;
let middle = `/rtv/${'012003312116250'}/log-messages.simple.json`;
let end = `rtv/${'123'}`;
let number = `${123}/foo`;
let boolean = `${true}/foo`;
@@ -0,0 +1,3 @@
{
"plugins": ["../../../../../babel-plugin-transform-stringish-literals"]
}
@@ -0,0 +1,21 @@
/**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
let none = `/rtv/100/log-messages.simple.json`;
let start = `123/foo`;
let middle = `/rtv/012003312116250/log-messages.simple.json`;
let end = `rtv/123`;
let number = `123/foo`;
let boolean = `true/foo`;
@@ -0,0 +1,19 @@
/**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

const runner = require('@babel/helper-plugin-test-runner').default;

runner(__dirname);
1 change: 1 addition & 0 deletions build-system/compile/build.conf.js
Expand Up @@ -46,6 +46,7 @@ const postCompilationPlugins = (isEsmBuild) =>
? [
localPlugin('transform-minified-comments'),
localPlugin('transform-function-declarations'),
localPlugin('transform-stringish-literals'),
]
: [];

Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Expand Up @@ -16700,4 +16700,4 @@ yeast@0.1.2:
zeparser@0.0.5:
version "0.0.5"
resolved "https://registry.yarnpkg.com/zeparser/-/zeparser-0.0.5.tgz#03726561bc268f2e5444f54c665b7fd4a8c029e2"
integrity sha1-A3JlYbwmjy5URPVMZlt/1KjAKeI=
integrity sha1-A3JlYbwmjy5URPVMZlt/1KjAKeI=