summaryrefslogtreecommitdiffstats
path: root/devtools/client/debugger/src/workers/parser/utils/helpers.js
blob: 0045b541364f22dee52b76cca92da76cd8558e8a (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */

import * as t from "@babel/types";
import generate from "@babel/generator";

export function isFunction(node) {
  return (
    t.isFunction(node) ||
    t.isArrowFunctionExpression(node) ||
    t.isObjectMethod(node) ||
    t.isClassMethod(node)
  );
}

export function isAwaitExpression(path) {
  const { node, parent } = path;
  return (
    t.isAwaitExpression(node) ||
    t.isAwaitExpression(parent.init) ||
    t.isAwaitExpression(parent)
  );
}

export function isYieldExpression(path) {
  const { node, parent } = path;
  return (
    t.isYieldExpression(node) ||
    t.isYieldExpression(parent.init) ||
    t.isYieldExpression(parent)
  );
}

export function isObjectShorthand(parent) {
  if (!t.isObjectProperty(parent)) {
    return false;
  }

  if (parent.value && parent.value.left) {
    return (
      parent.value.type === "AssignmentPattern" &&
      parent.value.left.type === "Identifier"
    );
  }

  return (
    parent.value &&
    parent.key.start == parent.value.start &&
    parent.key.loc.identifierName === parent.value.loc.identifierName
  );
}

export function getObjectExpressionValue(node) {
  const { value } = node;

  if (t.isIdentifier(value)) {
    return value.name;
  }

  if (t.isCallExpression(value) || t.isFunctionExpression(value)) {
    return "";
  }
  const code = generate(value).code;

  const shouldWrap = t.isObjectExpression(value);
  return shouldWrap ? `(${code})` : code;
}

export function getCode(node) {
  return generate(node).code;
}

export function getComments(ast) {
  if (!ast || !ast.comments) {
    return [];
  }
  return ast.comments.map(comment => ({
    name: comment.location,
    location: comment.loc,
  }));
}

export function isComputedExpression(expression) {
  return /^\[/m.test(expression);
}

export function getMemberExpression(root) {
  function _getMemberExpression(node, expr) {
    if (t.isMemberExpression(node)) {
      expr = [node.property.name].concat(expr);
      return _getMemberExpression(node.object, expr);
    }

    if (t.isCallExpression(node)) {
      return [];
    }

    if (t.isThisExpression(node)) {
      return ["this"].concat(expr);
    }

    return [node.name].concat(expr);
  }

  const expr = _getMemberExpression(root, []);
  return expr.join(".");
}

export function getVariables(dec) {
  if (!dec.id) {
    return [];
  }

  if (t.isArrayPattern(dec.id)) {
    if (!dec.id.elements) {
      return [];
    }

    // NOTE: it's possible that an element is empty or has several variables
    // e.g. const [, a] = arr
    // e.g. const [{a, b }] = 2
    return dec.id.elements
      .filter(Boolean)
      .map(element => ({
        name: t.isAssignmentPattern(element)
          ? element.left.name
          : element.name || element.argument?.name,
        location: element.loc,
      }))
      .filter(({ name }) => name);
  }

  return [
    {
      name: dec.id.name,
      location: dec.loc,
    },
  ];
}

/**
 * Add the identifiers for a given object pattern.
 *
 * @param {Array.<Object>} identifiers
 *        the current list of identifiers where to push the new identifiers
 *        related to this path.
 * @param {Set<String>} identifiersKeys
 *        List of currently registered identifier location key.
 * @param {Object} pattern
 */
export function addPatternIdentifiers(identifiers, identifiersKeys, pattern) {
  let items;
  if (t.isObjectPattern(pattern)) {
    items = pattern.properties.map(({ value }) => value);
  }

  if (t.isArrayPattern(pattern)) {
    items = pattern.elements;
  }

  if (items) {
    addIdentifiers(identifiers, identifiersKeys, items);
  }
}

function addIdentifiers(identifiers, identifiersKeys, items) {
  for (const item of items) {
    if (t.isObjectPattern(item) || t.isArrayPattern(item)) {
      addPatternIdentifiers(identifiers, identifiersKeys, item);
    } else if (t.isIdentifier(item)) {
      if (!identifiersKeys.has(nodeLocationKey(item.loc))) {
        identifiers.push({
          name: item.name,
          expression: item.name,
          location: item.loc,
        });
      }
    }
  }
}

// Top Level checks the number of "body" nodes in the ancestor chain
// if the node is top-level, then it shoul only have one body.
export function isTopLevel(ancestors) {
  return ancestors.filter(ancestor => ancestor.key == "body").length == 1;
}

export function nodeLocationKey({ start, end }) {
  return `${start.line}:${start.column}:${end.line}:${end.column}`;
}

export function getFunctionParameterNames(path) {
  if (path.node.params != null) {
    return path.node.params.map(param => {
      if (param.type !== "AssignmentPattern") {
        return param.name;
      }

      // Parameter with default value
      if (
        param.left.type === "Identifier" &&
        param.right.type === "Identifier"
      ) {
        return `${param.left.name} = ${param.right.name}`;
      } else if (
        param.left.type === "Identifier" &&
        param.right.type === "StringLiteral"
      ) {
        return `${param.left.name} = ${param.right.value}`;
      } else if (
        param.left.type === "Identifier" &&
        param.right.type === "ObjectExpression"
      ) {
        return `${param.left.name} = {}`;
      } else if (
        param.left.type === "Identifier" &&
        param.right.type === "ArrayExpression"
      ) {
        return `${param.left.name} = []`;
      } else if (
        param.left.type === "Identifier" &&
        param.right.type === "NullLiteral"
      ) {
        return `${param.left.name} = null`;
      }

      return null;
    });
  }
  return [];
}