Debian Codegraph @

src/com/google/javascript/jscomp/SourceFile.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.annotations.VisibleForTesting;
20 import com.google.common.base.Charsets;
21 import com.google.common.io.CharStreams;
22 import com.google.common.io.Files;
23 import com.google.javascript.rhino.jstype.StaticSourceFile;
24
25 import java.io.File;
26 import java.io.FileReader;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.io.Reader;
31 import java.io.Serializable;
32 import java.io.StringReader;
33 import java.nio.charset.Charset;
34 import java.util.Arrays;
35
36 /**
37 * An abstract representation of a source file that provides access to
38 * language-neutral features. The source file can be loaded from various
39 * locations, such as from disk or from a preloaded string.
40 *
41 * @author [email protected] (Nick Santos)
42 */
43 public class SourceFile implements StaticSourceFile, Serializable {
44 private static final long serialVersionUID = 1L;
45
46 /** A JavaScript source code provider. The value should
47 * be cached so that the source text stays consistent throughout a single
48 * compile. */
49 public interface Generator {
50 public String getCode();
51 }
52
53 /**
54 * Number of lines in the region returned by {@link #getRegion(int)}.
55 * This length must be odd.
56 */
57 private static final int SOURCE_EXCERPT_REGION_LENGTH = 5;
58
59 private final String fileName;
60 private boolean isExternFile = false;
61
62 // The fileName may not always identify the original file - for example,
63 // supersourced Java inputs, or Java inputs that come from Jar files. This
64 // is an optional field that the creator of an AST or SourceFile can set.
65 // It could be a path to the original file, or in case this SourceFile came
66 // from a Jar, it could be the path to the Jar.
67 private String originalPath = null;
68
69 // Source Line Information
70 private int[] lineOffsets = null;
71
72 private String code = null;
73
74 /**
75 * Construct a new abstract source file.
76 *
77 * @param fileName The file name of the source file. It does not necessarily
78 * need to correspond to a real path. But it should be unique. Will
79 * appear in warning messages emitted by the compiler.
80 */
81 public SourceFile(String fileName) {
82 if (fileName == null || fileName.isEmpty()) {
83 throw new IllegalArgumentException("a source must have a name");
84 }
85 this.fileName = fileName;
86 }
87
88 @Override
89 public int getLineOffset(int lineno) {
90 findLineOffsets();
91 if (lineno < 1 || lineno > lineOffsets.length) {
92 throw new IllegalArgumentException(
93 "Expected line number between 1 and " + lineOffsets.length +
94 "\nActual: " + lineno);
95 }
96 return lineOffsets[lineno - 1];
97 }
98
99 /** @return The number of lines in this source file. */
100 int getNumLines() {
101 findLineOffsets();
102 return lineOffsets.length;
103 }
104
105
106 private void findLineOffsets() {
107 if (lineOffsets != null) {
108 return;
109 }
110 try {
111 String[] sourceLines = getCode().split("\n");
112 lineOffsets = new int[sourceLines.length];
113 for (int ii = 1; ii < sourceLines.length; ++ii) {
114 lineOffsets[ii] =
115 lineOffsets[ii - 1] + sourceLines[ii - 1].length() + 1;
116 }
117 } catch (IOException e) {
118 lineOffsets = new int[1];
119 lineOffsets[0] = 0;
120 }
121 }
122
123
124 //////////////////////////////////////////////////////////////////////////////
125 // Implementation
126
127 /**
128 * Gets all the code in this source file.
129 * @throws IOException
130 */
131 public String getCode() throws IOException {
132 return code;
133 }
134
135 /**
136 * Gets a reader for the code in this source file.
137 */
138 public Reader getCodeReader() throws IOException {
139 return new StringReader(getCode());
140 }
141
142 @VisibleForTesting
143 String getCodeNoCache() {
144 return code;
145 }
146
147 private void setCode(String sourceCode) {
148 code = sourceCode;
149 }
150
151 public String getOriginalPath() {
152 return originalPath != null ? originalPath : fileName;
153 }
154
155 public void setOriginalPath(String originalPath) {
156 this.originalPath = originalPath;
157 }
158
159 // For SourceFile types which cache source code that can be regenerated
160 // easily, flush the cache. We maintain the cache mostly to speed up
161 // generating source when displaying error messages, so dumping the file
162 // contents after the compile is a fine thing to do.
163 public void clearCachedSource() {
164 // By default, do nothing. Not all kinds of SourceFiles can regenerate
165 // code.
166 }
167
168 boolean hasSourceInMemory() {
169 return code != null;
170 }
171
172 /** Returns a unique name for the source file. */
173 @Override
174 public String getName() {
175 return fileName;
176 }
177
178 /** Returns whether this is an extern. */
179 @Override
180 public boolean isExtern() {
181 return isExternFile;
182 }
183
184 /** Sets that this is an extern. */
185 void setIsExtern(boolean newVal) {
186 isExternFile = newVal;
187 }
188
189 @Override
190 public int getLineOfOffset(int offset) {
191 findLineOffsets();
192 int search = Arrays.binarySearch(lineOffsets, offset);
193 if (search >= 0) {
194 return search + 1; // lines are 1-based.
195 } else {
196 int insertionPoint = -1 * (search + 1);
197 return Math.min(insertionPoint - 1, lineOffsets.length - 1) + 1;
198 }
199 }
200
201 @Override
202 public int getColumnOfOffset(int offset) {
203 int line = getLineOfOffset(offset);
204 return offset - lineOffsets[line - 1];
205 }
206
207 /**
208 * Gets the source line for the indicated line number.
209 *
210 * @param lineNumber the line number, 1 being the first line of the file.
211 * @return The line indicated. Does not include the newline at the end
212 * of the file. Returns {@code null} if it does not exist,
213 * or if there was an IO exception.
214 */
215 public String getLine(int lineNumber) {
216 findLineOffsets();
217 if (lineNumber > lineOffsets.length) {
218 return null;
219 }
220
221 if (lineNumber < 1) {
222 lineNumber = 1;
223 }
224
225 int pos = lineOffsets[lineNumber - 1];
226 String js = "";
227 try {
228 // NOTE(nicksantos): Right now, this is optimized for few warnings.
229 // This is probably the right trade-off, but will be slow if there
230 // are lots of warnings in one file.
231 js = getCode();
232 } catch (IOException e) {
233 return null;
234 }
235
236 if (js.indexOf('\n', pos) == -1) {
237 // If next new line cannot be found, there are two cases
238 // 1. pos already reaches the end of file, then null should be returned
239 // 2. otherwise, return the contents between pos and the end of file.
240 if (pos >= js.length()) {
241 return null;
242 } else {
243 return js.substring(pos, js.length());
244 }
245 } else {
246 return js.substring(pos, js.indexOf('\n', pos));
247 }
248 }
249
250 /**
251 * Get a region around the indicated line number. The exact definition of a
252 * region is implementation specific, but it must contain the line indicated
253 * by the line number. A region must not start or end by a carriage return.
254 *
255 * @param lineNumber the line number, 1 being the first line of the file.
256 * @return The line indicated. Returns {@code null} if it does not exist,
257 * or if there was an IO exception.
258 */
259 public Region getRegion(int lineNumber) {
260 String js = "";
261 try {
262 js = getCode();
263 } catch (IOException e) {
264 return null;
265 }
266 int pos = 0;
267 int startLine = Math.max(1,
268 lineNumber - (SOURCE_EXCERPT_REGION_LENGTH + 1) / 2 + 1);
269 for (int n = 1; n < startLine; n++) {
270 int nextpos = js.indexOf('\n', pos);
271 if (nextpos == -1) {
272 break;
273 }
274 pos = nextpos + 1;
275 }
276 int end = pos;
277 int endLine = startLine;
278 for (int n = 0; n < SOURCE_EXCERPT_REGION_LENGTH; n++, endLine++) {
279 end = js.indexOf('\n', end);
280 if (end == -1) {
281 break;
282 }
283 end++;
284 }
285 if (lineNumber >= endLine) {
286 return null;
287 }
288 if (end == -1) {
289 int last = js.length() - 1;
290 if (js.charAt(last) == '\n') {
291 return
292 new SimpleRegion(startLine, endLine, js.substring(pos, last));
293 } else {
294 return new SimpleRegion(startLine, endLine, js.substring(pos));
295 }
296 } else {
297 return new SimpleRegion(startLine, endLine, js.substring(pos, end));
298 }
299 }
300
301 @Override
302 public String toString() {
303 return fileName;
304 }
305
306 public static SourceFile fromFile(String fileName, Charset c) {
307 return builder().withCharset(c).buildFromFile(fileName);
308 }
309
310 public static SourceFile fromFile(String fileName) {
311 return builder().buildFromFile(fileName);
312 }
313
314 public static SourceFile fromFile(File file, Charset c) {
315 return builder().withCharset(c).buildFromFile(file);
316 }
317
318 public static SourceFile fromFile(File file) {
319 return builder().buildFromFile(file);
320 }
321
322 public static SourceFile fromCode(String fileName, String code) {
323 return builder().buildFromCode(fileName, code);
324 }
325
326 public static SourceFile fromCode(String fileName,
327 String originalPath, String code) {
328 return builder().withOriginalPath(originalPath)
329 .buildFromCode(fileName, code);
330 }
331
332 public static SourceFile fromInputStream(String fileName, InputStream s)
333 throws IOException {
334 return builder().buildFromInputStream(fileName, s);
335 }
336
337 public static SourceFile fromInputStream(String fileName,
338 String originalPath, InputStream s) throws IOException {
339 return builder().withOriginalPath(originalPath)
340 .buildFromInputStream(fileName, s);
341 }
342
343 public static SourceFile fromReader(String fileName, Reader r)
344 throws IOException {
345 return builder().buildFromReader(fileName, r);
346 }
347
348 public static SourceFile fromGenerator(String fileName,
349 Generator generator) {
350 return builder().buildFromGenerator(fileName, generator);
351 }
352
353 /** Create a new builder for source files. */
354 public static Builder builder() {
355 return new Builder();
356 }
357
358 /**
359 * A builder interface for source files.
360 *
361 * Allows users to customize the Charset, and the original path of
362 * the source file (if it differs from the path on disk).
363 */
364 public static class Builder {
365 private Charset charset = Charsets.UTF_8;
366 private String originalPath = null;
367
368 public Builder() {}
369
370 /** Set the charset to use when reading from an input stream or file. */
371 public Builder withCharset(Charset charset) {
372 this.charset = charset;
373 return this;
374 }
375
376 /** Set the original path to use. */
377 public Builder withOriginalPath(String originalPath) {
378 this.originalPath = originalPath;
379 return this;
380 }
381
382 public SourceFile buildFromFile(String fileName) {
383 return buildFromFile(new File(fileName));
384 }
385
386 public SourceFile buildFromFile(File file) {
387 return new OnDisk(file, originalPath, charset);
388 }
389
390 public SourceFile buildFromCode(String fileName, String code) {
391 return new Preloaded(fileName, originalPath, code);
392 }
393
394 public SourceFile buildFromInputStream(String fileName, InputStream s)
395 throws IOException {
396 return buildFromCode(fileName,
397 CharStreams.toString(new InputStreamReader(s, charset)));
398 }
399
400 public SourceFile buildFromReader(String fileName, Reader r)
401 throws IOException {
402 return buildFromCode(fileName, CharStreams.toString(r));
403 }
404
405 public SourceFile buildFromGenerator(String fileName,
406 Generator generator) {
407 return new Generated(fileName, originalPath, generator);
408 }
409 }
410
411
412 //////////////////////////////////////////////////////////////////////////////
413 // Implementations
414
415 /**
416 * A source file where the code has been preloaded.
417 */
418 static class Preloaded extends SourceFile {
419 private static final long serialVersionUID = 1L;
420
421 Preloaded(String fileName, String originalPath, String code) {
422 super(fileName);
423 super.setOriginalPath(originalPath);
424 super.setCode(code);
425 }
426 }
427
428 /**
429 * A source file where the code will be dynamically generated
430 * from the injected interface.
431 */
432 static class Generated extends SourceFile {
433 private static final long serialVersionUID = 1L;
434 private final Generator generator;
435
436 // Not private, so that LazyInput can extend it.
437 Generated(String fileName, String originalPath, Generator generator) {
438 super(fileName);
439 super.setOriginalPath(originalPath);
440 this.generator = generator;
441 }
442
443 @Override
444 public synchronized String getCode() throws IOException {
445 String cachedCode = super.getCode();
446
447 if (cachedCode == null) {
448 cachedCode = generator.getCode();
449 super.setCode(cachedCode);
450 }
451 return cachedCode;
452 }
453
454 // Clear out the generated code when finished with a compile; we can
455 // regenerate it if we ever need it again.
456 @Override
457 public void clearCachedSource() {
458 super.setCode(null);
459 }
460 }
461
462 /**
463 * A source file where the code is only read into memory if absolutely
464 * necessary. We will try to delay loading the code into memory as long as
465 * possible.
466 */
467 static class OnDisk extends SourceFile {
468 private static final long serialVersionUID = 1L;
469 private final File file;
470
471 // This is stored as a String, but passed in and out as a Charset so that
472 // we can serialize the class.
473 // Default input file format for JSCompiler has always been UTF_8.
474 private String inputCharset = Charsets.UTF_8.name();
475
476 OnDisk(File file, String originalPath, Charset c) {
477 super(file.getPath());
478 this.file = file;
479 super.setOriginalPath(originalPath);
480 if (c != null) {
481 this.setCharset(c);
482 }
483 }
484
485 @Override
486 public synchronized String getCode() throws IOException {
487 String cachedCode = super.getCode();
488
489 if (cachedCode == null) {
490 cachedCode = Files.toString(file, this.getCharset());
491 super.setCode(cachedCode);
492 }
493 return cachedCode;
494 }
495
496 /**
497 * Gets a reader for the code in this source file.
498 */
499 @Override
500 public Reader getCodeReader() throws IOException {
501 if (hasSourceInMemory()) {
502 return super.getCodeReader();
503 } else {
504 // If we haven't pulled the code into memory yet, don't.
505 return new FileReader(file);
506 }
507 }
508
509 // Flush the cached code after the compile; we can read it off disk
510 // if we need it again.
511 @Override
512 public void clearCachedSource() {
513 super.setCode(null);
514 }
515
516 /**
517 * Store the Charset specification as the string version of the name,
518 * rather than the Charset itself. This allows us to serialize the
519 * SourceFile class.
520 * @param c charset to use when reading the input.
521 */
522 public void setCharset(Charset c) {
523 inputCharset = c.name();
524 }
525
526 /**
527 * Get the Charset specifying how we're supposed to read the file
528 * in off disk and into UTF-16. This is stored as a strong to allow
529 * SourceFile to be serialized.
530 * @return Charset object representing charset to use.
531 */
532 public Charset getCharset() {
533 return Charset.forName(inputCharset);
534 }
535 }
536 }