Skip to content

Commit

Permalink
Improve regex printing (#1341)
Browse files Browse the repository at this point in the history
- Print the raw regex for Flow, just like for Babylon.
- Sort regex flags.

Fixes #1334.
  • Loading branch information
lydell authored and vjeux committed Apr 19, 2017
1 parent e2fbaaf commit 938f0e3
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/printer.js
Expand Up @@ -878,11 +878,13 @@ function genericPrintNoParens(path, options, print, args) {
case "ThisExpression":
return "this";
case "Super":
return "super"; // Babel 6 Literal split
return "super";
// Babel 6 Literal split
case "NullLiteral":
return "null"; // Babel 6 Literal split
return "null";
// Babel 6 Literal split
case "RegExpLiteral":
return n.extra.raw;
return printRegex(n);
// Babel 6 Literal split
case "NumericLiteral":
return printNumber(n.extra.raw);
Expand All @@ -892,6 +894,7 @@ function genericPrintNoParens(path, options, print, args) {
case "StringLiteral":
case "Literal":
if (typeof n.value === "number") return printNumber(n.raw);
if (n.regex) return printRegex(n.regex);
if (typeof n.value !== "string") return "" + n.value;

return nodeStr(n, options); // Babel 6
Expand Down Expand Up @@ -3335,6 +3338,11 @@ function makeString(rawContent, enclosingQuote) {
return enclosingQuote + newContent + enclosingQuote;
}

function printRegex(node) {
const flags = node.flags.split('').sort().join('');
return `/${node.pattern}/${flags}`;
}

function printNumber(rawNumber) {
return (
rawNumber
Expand Down
8 changes: 8 additions & 0 deletions tests/regex/__snapshots__/jsfmt.spec.js.snap
@@ -0,0 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`test.js 1`] = `
/[/]\\/\\u0aBc/mgi;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/[/]\\/\\u0aBc/gim;
`;
1 change: 1 addition & 0 deletions tests/regex/jsfmt.spec.js
@@ -0,0 +1 @@
run_spec(__dirname, null, ["babylon"]);
1 change: 1 addition & 0 deletions tests/regex/test.js
@@ -0,0 +1 @@
/[/]\/\u0aBc/mgi;

0 comments on commit 938f0e3

Please sign in to comment.