Debian Codegraph @

src/com/google/javascript/jscomp/CompilerInput.java

raw symbols SCIP
1 /*
2 * Copyright 2009 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Sets;
23 import com.google.javascript.jscomp.deps.DependencyInfo;
24 import com.google.javascript.jscomp.deps.JsFileParser;
25 import com.google.javascript.rhino.InputId;
26 import com.google.javascript.rhino.Node;
27 import java.io.IOException;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.List;
31 import java.util.Set;
32
33 /**
34 * A class for the internal representation of an input to the compiler.
35 * Wraps a {@link SourceAst} and maintain state such as module for the input and
36 * whether the input is an extern. Also calculates provided and required types.
37 *
38 */
39 public class CompilerInput
40 implements SourceAst, DependencyInfo {
41
42 private static final long serialVersionUID = 1L;
43
44 // Info about where the file lives.
45 private JSModule module;
46 final private InputId id;
47
48 // The AST.
49 private final SourceAst ast;
50
51 // Provided and required symbols.
52 private final Set<String> provides = Sets.newHashSet();
53 private final Set<String> requires = Sets.newHashSet();
54 private boolean generatedDependencyInfoFromSource = false;
55
56 // An AbstractCompiler for doing parsing.
57 // We do not want to persist this across serialized state.
58 private transient AbstractCompiler compiler;
59
60 public CompilerInput(SourceAst ast) {
61 this(ast, ast.getSourceFile().getName(), false);
62 }
63
64 public CompilerInput(SourceAst ast, boolean isExtern) {
65 this(ast, ast.getInputId(), isExtern);
66 }
67
68 public CompilerInput(SourceAst ast, String inputId, boolean isExtern) {
69 this(ast, new InputId(inputId), isExtern);
70 }
71
72 public CompilerInput(SourceAst ast, InputId inputId, boolean isExtern) {
73 this.ast = ast;
74 this.id = inputId;
75
76 // TODO(nicksantos): Add a precondition check here. People are passing
77 // in null, but they should not be.
78 if (ast != null && ast.getSourceFile() != null) {
79 ast.getSourceFile().setIsExtern(isExtern);
80 }
81 }
82
83 public CompilerInput(SourceFile file) {
84 this(file, false);
85 }
86
87 public CompilerInput(SourceFile file, boolean isExtern) {
88 this(new JsAst(file), isExtern);
89 }
90
91 /** Returns a name for this input. Must be unique across all inputs. */
92 @Override
93 public InputId getInputId() {
94 return id;
95 }
96
97 /** Returns a name for this input. Must be unique across all inputs. */
98 @Override
99 public String getName() {
100 return id.getIdName();
101 }
102
103 public SourceAst getAst() {
104 return ast;
105 }
106
107 /** Gets the path relative to closure-base, if one is available. */
108 @Override
109 public String getPathRelativeToClosureBase() {
110 // TODO(nicksantos): Implement me.
111 throw new UnsupportedOperationException();
112 }
113
114 @Override
115 public Node getAstRoot(AbstractCompiler compiler) {
116 Node root = ast.getAstRoot(compiler);
117 // The root maybe null if the AST can not be created.
118 if (root != null) {
119 Preconditions.checkState(root.isScript());
120 Preconditions.checkNotNull(root.getInputId());
121 }
122 return root;
123 }
124
125 @Override
126 public void clearAst() {
127 ast.clearAst();
128 }
129
130 @Override
131 public SourceFile getSourceFile() {
132 return ast.getSourceFile();
133 }
134
135 @Override
136 public void setSourceFile(SourceFile file) {
137 ast.setSourceFile(file);
138 }
139
140 /** Returns the SourceAst object on which this input is based. */
141 public SourceAst getSourceAst() {
142 return ast;
143 }
144
145 /** Sets an abstract compiler for doing parsing. */
146 public void setCompiler(AbstractCompiler compiler) {
147 this.compiler = compiler;
148 }
149
150 private void checkErrorManager() {
151 Preconditions.checkNotNull(compiler,
152 "Expected setCompiler to be called first: " + this);
153 Preconditions.checkNotNull(compiler.getErrorManager(),
154 "Expected compiler to call an error manager: " + this);
155 }
156
157 /** Gets a list of types depended on by this input. */
158 @Override
159 public Collection<String> getRequires() {
160 checkErrorManager();
161 try {
162 regenerateDependencyInfoIfNecessary();
163 return Collections.<String>unmodifiableSet(requires);
164 } catch (IOException e) {
165 compiler.getErrorManager().report(CheckLevel.ERROR,
166 JSError.make(AbstractCompiler.READ_ERROR, getName()));
167 return ImmutableList.<String>of();
168 }
169 }
170
171 /** Gets a list of types provided by this input. */
172 @Override
173 public Collection<String> getProvides() {
174 checkErrorManager();
175 try {
176 regenerateDependencyInfoIfNecessary();
177 return Collections.<String>unmodifiableSet(provides);
178 } catch (IOException e) {
179 compiler.getErrorManager().report(CheckLevel.ERROR,
180 JSError.make(AbstractCompiler.READ_ERROR, getName()));
181 return ImmutableList.<String>of();
182 }
183 }
184
185 // TODO(nicksantos): Remove addProvide/addRequire/removeRequire once
186 // there is better support for discovering non-closure dependencies.
187 void addProvide(String provide) {
188 getProvides();
189 provides.add(provide);
190 }
191
192 void addRequire(String require) {
193 getRequires();
194 requires.add(require);
195 }
196
197 public void removeRequire(String require) {
198 getRequires();
199 requires.remove(require);
200 }
201
202 /**
203 * Regenerates the provides/requires if we need to do so.
204 */
205 private void regenerateDependencyInfoIfNecessary() throws IOException {
206 // If the code is NOT a JsAst, then it was not originally JS code.
207 // Look at the Ast for dependency info.
208 if (!(ast instanceof JsAst)) {
209 Preconditions.checkNotNull(compiler,
210 "Expected setCompiler to be called first");
211 DepsFinder finder = new DepsFinder();
212 Node root = getAstRoot(compiler);
213 if (root == null) {
214 return;
215 }
216
217 finder.visitTree(getAstRoot(compiler));
218
219 // TODO(nicksantos|user): This caching behavior is a bit
220 // odd, and only works if you assume the exact call flow that
221 // clients are currently using. In that flow, they call
222 // getProvides(), then remove the goog.provide calls from the
223 // AST, and then call getProvides() again.
224 //
225 // This won't work for any other call flow, or any sort of incremental
226 // compilation scheme. The API needs to be fixed so callers aren't
227 // doing weird things like this, and then we should get rid of the
228 // multiple-scan strategy.
229
230 provides.addAll(finder.provides);
231 requires.addAll(finder.requires);
232 } else {
233 // Otherwise, look at the source code.
234 if (!generatedDependencyInfoFromSource) {
235 // Note: it's OK to use getName() instead of
236 // getPathRelativeToClosureBase() here because we're not using
237 // this to generate deps files. (We're only using it for
238 // symbol dependencies.)
239 DependencyInfo info =
240 (new JsFileParser(compiler.getErrorManager()))
241 .setIncludeGoogBase(true)
242 .parseFile(getName(), getName(), getCode());
243
244 provides.addAll(info.getProvides());
245 requires.addAll(info.getRequires());
246
247 generatedDependencyInfoFromSource = true;
248 }
249 }
250 }
251
252 private static class DepsFinder {
253 private final List<String> provides = Lists.newArrayList();
254 private final List<String> requires = Lists.newArrayList();
255 private final CodingConvention codingConvention =
256 new ClosureCodingConvention();
257
258 void visitTree(Node n) {
259 visitSubtree(n, null);
260 }
261
262 void visitSubtree(Node n, Node parent) {
263 if (n.isCall()) {
264 String require =
265 codingConvention.extractClassNameIfRequire(n, parent);
266 if (require != null) {
267 requires.add(require);
268 }
269
270 String provide =
271 codingConvention.extractClassNameIfProvide(n, parent);
272 if (provide != null) {
273 provides.add(provide);
274 }
275 return;
276 } else if (parent != null &&
277 !parent.isExprResult() &&
278 !parent.isScript()) {
279 return;
280 }
281
282 for (Node child = n.getFirstChild();
283 child != null; child = child.getNext()) {
284 visitSubtree(child, n);
285 }
286 }
287 }
288
289 /**
290 * Gets the source line for the indicated line number.
291 *
292 * @param lineNumber the line number, 1 being the first line of the file.
293 * @return The line indicated. Does not include the newline at the end
294 * of the file. Returns {@code null} if it does not exist,
295 * or if there was an IO exception.
296 */
297 public String getLine(int lineNumber) {
298 return getSourceFile().getLine(lineNumber);
299 }
300
301 /**
302 * Get a region around the indicated line number. The exact definition of a
303 * region is implementation specific, but it must contain the line indicated
304 * by the line number. A region must not start or end by a carriage return.
305 *
306 * @param lineNumber the line number, 1 being the first line of the file.
307 * @return The line indicated. Returns {@code null} if it does not exist,
308 * or if there was an IO exception.
309 */
310 public Region getRegion(int lineNumber) {
311 return getSourceFile().getRegion(lineNumber);
312 }
313
314 public String getCode() throws IOException {
315 return getSourceFile().getCode();
316 }
317
318 /** Returns the module to which the input belongs. */
319 public JSModule getModule() {
320 return module;
321 }
322
323 /** Sets the module to which the input belongs. */
324 public void setModule(JSModule module) {
325 // An input may only belong to one module.
326 Preconditions.checkArgument(
327 module == null || this.module == null || this.module == module);
328 this.module = module;
329 }
330
331 /** Overrides the module to which the input belongs. */
332 void overrideModule(JSModule module) {
333 this.module = module;
334 }
335
336 public boolean isExtern() {
337 if (ast == null || ast.getSourceFile() == null) {
338 return false;
339 }
340 return ast.getSourceFile().isExtern();
341 }
342
343 void setIsExtern(boolean isExtern) {
344 if (ast == null || ast.getSourceFile() == null) {
345 return;
346 }
347 ast.getSourceFile().setIsExtern(isExtern);
348 }
349
350 public int getLineOffset(int lineno) {
351 return ast.getSourceFile().getLineOffset(lineno);
352 }
353
354 /** @return The number of lines in this input. */
355 public int getNumLines() {
356 return ast.getSourceFile().getNumLines();
357 }
358
359 @Override
360 public String toString() {
361 return getName();
362 }
363 }