-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
JsFileParser.java
296 lines (260 loc) · 10.2 KB
/
JsFileParser.java
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
* Copyright 2008 The Closure Compiler Authors.
*
* 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.
*/
package com.google.javascript.jscomp.deps;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.CharMatcher;
import com.google.javascript.jscomp.CheckLevel;
import com.google.javascript.jscomp.ErrorManager;
import com.google.javascript.jscomp.JSError;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A parser that can extract dependency information from a .js file, including
* goog.require, goog.provide, goog.module, import statements, and export statements.
*
* @author agrieve@google.com (Andrew Grieve)
*/
@GwtIncompatible("java.util.regex")
public final class JsFileParser extends JsFileLineParser {
private static final Logger logger = Logger.getLogger(JsFileParser.class.getName());
/** Pattern for matching goog.provide(*) and goog.require(*). */
private static final Pattern GOOG_PROVIDE_REQUIRE_PATTERN =
Pattern.compile(
"(?:^|;)(?:[a-zA-Z0-9$_,:{}\\s]+=)?\\s*"
+ "goog\\.(provide|module|require|addDependency)\\s*\\((.*?)\\)");
/**
* Pattern for matching import ... from './path/to/file'.
*
* <p>Unlike the goog.require() pattern above, this pattern does not
* allow multiple statements per line. The import/export <b>must</b>
* be at the beginning of the line to match.
*/
private static final Pattern ES6_MODULE_PATTERN =
Pattern.compile(
// Require the import/export to be at the beginning of the line
"^"
// Either an import or export, but we don't care which, followed by at least one space
+ "(?:import|export)\\b\\s*"
// Skip any identifier chars, as well as star, comma, braces, and spaces
// This should match, e.g., "* as foo from ", or "Foo, {Bar as Baz} from ".
// The 'from' keyword is required except in the case of "import '...';",
// where there's nothing between 'import' and the module key string literal.
+ "(?:[a-zA-Z0-9$_*,{}\\s]+\\bfrom\\s*|)"
// Imports require a string literal at the end; it's optional for exports
// (e.g. "export * from './other';", which is effectively also an import).
// This optionally captures group #1, which is the imported module name.
+ "(?:['\"]([^'\"]+)['\"])?"
// Finally, this should be the entire statement, so ensure there's a semicolon.
+ "\\s*;");
/**
* Pattern for 'export' keyword, e.g. "export default class ..." or "export {blah}".
* The '\b' ensures we don't also match "exports = ...", which is not an ES6 module.
*/
private static final Pattern ES6_EXPORT_PATTERN = Pattern.compile("^export\\b");
/** The first non-comment line of base.js */
private static final String BASE_JS_START = "var COMPILED = false;";
/** The start of a bundled goog.module, i.e. one that is wrapped in a goog.loadModule call */
private static final String BUNDLED_GOOG_MODULE_START = "goog.loadModule(function(";
/** Matchers used in the parsing. */
private final Matcher googMatcher = GOOG_PROVIDE_REQUIRE_PATTERN.matcher("");
/** Matchers used in the parsing. */
private final Matcher es6Matcher = ES6_MODULE_PATTERN.matcher("");
/** The info for the file we are currently parsing. */
private List<String> provides;
private List<String> requires;
private boolean fileHasProvidesOrRequires;
private ModuleLoader loader = ModuleLoader.EMPTY;
private ModuleLoader.ModulePath file;
private enum ModuleType {
NON_MODULE,
UNWRAPPED_GOOG_MODULE,
WRAPPED_GOOG_MODULE,
ES6_MODULE,
}
private ModuleType moduleType;
/** Whether to provide/require the root namespace. */
private boolean includeGoogBase = false;
/**
* Constructor
*
* @param errorManager Handles parse errors.
*/
public JsFileParser(ErrorManager errorManager) {
super(errorManager);
}
/**
* Sets whether we should create implicit provides and requires of the
* root namespace.
*
* When generating deps files, you do not want this behavior. Deps files
* need base.js to run anyway, so they don't need information about it.
*
* When generating abstract build graphs, you probably do want this behavior.
* It will create an implicit dependency of all files with provides/requires
* on base.js.
*
* @return this for easy chaining.
*/
public JsFileParser setIncludeGoogBase(boolean include) {
includeGoogBase = include;
return this;
}
/**
* Sets a list of "module root" URIs, which allow relativizing filenames
* for modules.
*
* @return this for easy chaining.
*/
public JsFileParser setModuleLoader(ModuleLoader loader) {
this.loader = loader;
return this;
}
/**
* Parses the given file and returns the dependency information that it
* contained.
*
* @param filePath Path to the file to parse.
* @param closureRelativePath Path of the file relative to closure.
* @param fileContents The contents to parse.
* @return A DependencyInfo containing all provides/requires found in the
* file.
*/
public DependencyInfo parseFile(String filePath, String closureRelativePath,
String fileContents) {
return parseReader(filePath, closureRelativePath,
new StringReader(fileContents));
}
private DependencyInfo parseReader(String filePath,
String closureRelativePath, Reader fileContents) {
this.provides = new ArrayList<>();
this.requires = new ArrayList<>();
this.fileHasProvidesOrRequires = false;
this.file = loader.resolve(filePath);
this.moduleType = ModuleType.NON_MODULE;
logger.fine("Parsing Source: " + filePath);
doParse(filePath, fileContents);
if (moduleType == ModuleType.ES6_MODULE) {
provides.add(file.toModuleName());
}
Map<String, String> loadFlags = new LinkedHashMap<>();
switch (moduleType) {
case UNWRAPPED_GOOG_MODULE:
loadFlags.put("module", "goog");
break;
case ES6_MODULE:
loadFlags.put("module", "es6");
break;
default:
// Nothing to do here.
}
DependencyInfo dependencyInfo = new SimpleDependencyInfo(
closureRelativePath, filePath, provides, requires, loadFlags);
logger.fine("DepInfo: " + dependencyInfo);
return dependencyInfo;
}
private void setModuleType(ModuleType type) {
if (moduleType != type && moduleType != ModuleType.NON_MODULE) {
errorManager.report(
CheckLevel.ERROR, JSError.make(ModuleLoader.MODULE_CONFLICT, file.toString()));
}
moduleType = type;
}
/**
* Parses a line of JavaScript, extracting goog.provide and goog.require
* information.
*/
@Override
protected boolean parseLine(String line) throws ParseException {
boolean lineHasProvidesOrRequires = false;
// Quick sanity check that will catch most cases. This is a performance
// win for people with a lot of JS.
if (line.contains("provide")
|| line.contains("require")
|| line.contains("module")
|| line.contains("addDependency")) {
// Iterate over the provides/requires.
googMatcher.reset(line);
while (googMatcher.find()) {
lineHasProvidesOrRequires = true;
if (includeGoogBase && !fileHasProvidesOrRequires) {
fileHasProvidesOrRequires = true;
requires.add("goog");
}
// See if it's a require or provide.
char firstChar = googMatcher.group(1).charAt(0);
boolean isProvide = (firstChar == 'p' || firstChar == 'm');
boolean isModule = firstChar == 'm';
boolean isRequire = firstChar == 'r';
if (isModule && this.moduleType != ModuleType.WRAPPED_GOOG_MODULE) {
setModuleType(ModuleType.UNWRAPPED_GOOG_MODULE);
}
if (isProvide || isRequire) {
// Parse the param.
String arg = parseJsString(googMatcher.group(2));
// Add the dependency.
if (isRequire) {
// goog is always implicit.
// TODO(nicksantos): I'm pretty sure we don't need this anymore.
// Remove this later.
if (!"goog".equals(arg)) {
requires.add(arg);
}
} else {
provides.add(arg);
}
}
}
} else if (includeGoogBase && line.startsWith(BASE_JS_START) &&
provides.isEmpty() && requires.isEmpty()) {
provides.add("goog");
// base.js can't provide or require anything else.
return false;
} else if (line.startsWith(BUNDLED_GOOG_MODULE_START)) {
setModuleType(ModuleType.WRAPPED_GOOG_MODULE);
}
if (line.startsWith("import") || line.startsWith("export")) {
es6Matcher.reset(line);
while (es6Matcher.find()) {
setModuleType(ModuleType.ES6_MODULE);
lineHasProvidesOrRequires = true;
String arg = es6Matcher.group(1);
if (arg != null) {
if (arg.startsWith("goog:")) {
requires.add(arg.substring(5)); // cut off the "goog:" prefix
} else {
requires.add(file.resolveEs6Module(arg).toModuleName());
}
}
}
// This check is only relevant for modules that don't import anything.
if (moduleType != ModuleType.ES6_MODULE && ES6_EXPORT_PATTERN.matcher(line).lookingAt()) {
setModuleType(ModuleType.ES6_MODULE);
}
}
return !shortcutMode || lineHasProvidesOrRequires
|| CharMatcher.whitespace().matchesAllOf(line)
|| !line.contains(";")
|| line.contains("goog.setTestOnly")
|| line.contains("goog.module.declareLegacyNamespace");
}
}