UNPKG

2.8 kBJavaScriptView Raw
1"use strict";
2
3const util = require("./util");
4
5/**
6 * This function takes the existing ast node and a copy, by reference
7 * We use it for testing, so that we can compare pre-post versions of the AST,
8 * excluding things we don't care about (like node location, case that will be
9 * changed by the printer, etc.)
10 */
11function clean(node, newObj) {
12 [
13 "loc",
14 "range",
15 "raw",
16 "comments",
17 "leadingComments",
18 "trailingComments",
19 "parenthesizedExpression",
20 "parent",
21 "prev",
22 "start",
23 "end",
24 "tokens",
25 "errors",
26 "extra",
27 ].forEach((name) => {
28 delete newObj[name];
29 });
30
31 if (node.kind === "string") {
32 // TODO if options are available in this method, replace with
33 // newObj.isDoubleQuote = !util.useSingleQuote(node, options);
34 delete newObj.isDoubleQuote;
35 }
36
37 if (node.kind === "array") {
38 // TODO if options are available in this method, assign instead of delete
39 delete newObj.shortForm;
40 }
41
42 if (node.kind === "inline") {
43 if (node.value.includes("___PSEUDO_INLINE_PLACEHOLDER___")) {
44 return null;
45 }
46
47 newObj.value = newObj.value.replace(/\r\n?|\n/g, "");
48 }
49
50 // continue ((2)); -> continue 2;
51 // continue 1; -> continue;
52 if ((node.kind === "continue" || node.kind === "break") && node.level) {
53 const { level } = newObj;
54
55 if (level.kind === "number") {
56 newObj.level = level.value === "1" ? null : level;
57 }
58 }
59
60 // if () {{ }} -> if () {}
61 if (node.kind === "block") {
62 if (node.children.length === 1 && node.children[0].kind === "block") {
63 while (newObj.children[0].kind === "block") {
64 newObj.children = newObj.children[0].children;
65 }
66 }
67 }
68
69 // Normalize numbers
70 if (node.kind === "number") {
71 newObj.value = util.printNumber(node.value);
72 }
73
74 const statements = ["foreach", "for", "if", "while", "do"];
75
76 if (statements.includes(node.kind)) {
77 if (node.body && node.body.kind !== "block") {
78 newObj.body = {
79 kind: "block",
80 children: [newObj.body],
81 };
82 } else {
83 newObj.body = newObj.body ? newObj.body : null;
84 }
85
86 if (node.alternate && node.alternate.kind !== "block") {
87 newObj.alternate = {
88 kind: "block",
89 children: [newObj.alternate],
90 };
91 } else {
92 newObj.alternate = newObj.alternate ? newObj.alternate : null;
93 }
94 }
95
96 if (node.kind === "usegroup" && typeof node.name === "string") {
97 newObj.name = newObj.name.replace(/^\\/, "");
98 }
99
100 if (node.kind === "useitem") {
101 newObj.name = newObj.name.replace(/^\\/, "");
102 }
103
104 if (node.kind === "method" && node.name.kind === "identifier") {
105 newObj.name.name = util.normalizeMagicMethodName(newObj.name.name);
106 }
107
108 if (node.kind === "noop") {
109 return null;
110 }
111}
112
113module.exports = clean;