Debian Codegraph @

src/com/google/debugging/sourcemap/SourceMapConsumerV1.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.debugging.sourcemap;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.Interner;
22 import com.google.common.collect.Interners;
23 import com.google.common.collect.Lists;
24 import com.google.common.primitives.Bytes;
25 import com.google.common.primitives.Shorts;
26 import com.google.debugging.sourcemap.proto.Mapping.OriginalMapping;
27
28 import org.json.JSONArray;
29 import org.json.JSONException;
30 import org.json.JSONObject;
31
32 import java.util.ArrayList;
33 import java.util.List;
34
35 /**
36 * Class for parsing and representing a SourceMap, as produced by the
37 * Closure Compiler, Caja-Compiler, etc.
38 */
39 public class SourceMapConsumerV1 implements SourceMapConsumer {
40 private static final String LINEMAP_HEADER = "/** Begin line maps. **/";
41 private static final String FILEINFO_HEADER =
42 "/** Begin file information. **/";
43
44 private static final String DEFINITION_HEADER =
45 "/** Begin mapping definitions. **/";
46
47 /**
48 * Internal class for parsing the SourceMap. Used to maintain parser
49 * state in an easy to use instance.
50 */
51 private static class ParseState {
52 final String contents;
53 int currentPosition = 0;
54
55 ParseState(String contents) {
56 this.contents = contents;
57 }
58
59 /** Reads a line, returning null at EOF. */
60 String readLineOrNull() {
61 if (currentPosition >= contents.length()) {
62 return null;
63 }
64 int index = contents.indexOf('\n', currentPosition);
65 if (index < 0) {
66 index = contents.length();
67 }
68 String line = contents.substring(currentPosition, index);
69 currentPosition = index + 1;
70 return line;
71 }
72
73 /** Reads a line, throwing a parse exception at EOF. */
74 String readLine() throws SourceMapParseException {
75 String line = readLineOrNull();
76 if (line == null) {
77 fail("EOF");
78 }
79 return line;
80 }
81
82 /**
83 * Reads a line and throws an parse exception if the line does not
84 * equal the argument.
85 */
86 void expectLine(String expect) throws SourceMapParseException {
87 String line = readLine();
88 if (!expect.equals(line)) {
89 fail("Expected " + expect + " got " + line);
90 }
91 }
92
93 /**
94 * Indicates that parsing has failed by throwing a parse exception.
95 */
96 void fail(String message) throws SourceMapParseException {
97 throw new SourceMapParseException(message);
98 }
99 }
100
101 /**
102 * Mapping from a line number (0-indexed), to a list of mapping IDs, one for
103 * each character on the line. For example, if the array for line 2 is
104 * {@code [4,,,,5,6,,,7]}, then there will be the entry:
105 *
106 * <pre>
107 * 1 => {4, 4, 4, 4, 5, 6, 6, 6, 7}
108 * </pre>
109 */
110 private ImmutableList<ImmutableList<LineFragment>> characterMap;
111
112 /**
113 * Map of Mapping IDs to the actual mapping object.
114 */
115 private ImmutableList<SourceFile> mappings;
116
117 /**
118 * Parses the given contents containing a source map.
119 */
120 @Override
121 public void parse(String contents) throws SourceMapParseException {
122 ParseState parser = new ParseState(contents);
123 try {
124 parseInternal(parser);
125 } catch (JSONException ex) {
126 parser.fail("JSON parse exception: " + ex);
127 }
128 }
129
130 /**
131 * Parses the first section of the source map file that has character
132 * mappings.
133 * @param parser The parser to use
134 * @param lineCount The number of lines in the generated JS
135 * @return The max id found in the file
136 */
137 private int parseCharacterMap(
138 ParseState parser, int lineCount,
139 ImmutableList.Builder<ImmutableList<LineFragment>> characterMapBuilder)
140 throws SourceMapParseException, JSONException {
141 int maxID = -1;
142 // [0,,,,,,1,2]
143 for (int i = 0; i < lineCount; ++i) {
144 String currentLine = parser.readLine();
145
146 // Blank lines are allowed in the spec to indicate no mapping
147 // information for the line.
148 if (currentLine.isEmpty()) {
149 continue;
150 }
151
152 ImmutableList.Builder<LineFragment> fragmentList =
153 ImmutableList.builder();
154 // We need the start index to initialize this, needs to be done in the
155 // loop.
156 LineFragment myLineFragment = null;
157
158 JSONArray charArray = new JSONArray(currentLine);
159 int lastID = -1;
160 int startID = Integer.MIN_VALUE;
161 List<Byte> currentOffsets = Lists.newArrayList();
162 for (int j = 0; j < charArray.length(); ++j) {
163 // Keep track of the current mappingID, if the next element in the
164 // array is empty we reuse the existing mappingID for the column.
165 int mappingID = lastID;
166 if (!charArray.isNull(j)) {
167 mappingID = charArray.optInt(j);
168 if (mappingID > maxID) {
169 maxID = mappingID;
170 }
171 }
172
173 if (startID == Integer.MIN_VALUE) {
174 startID = mappingID;
175 } else {
176 // If the difference is bigger than a byte we need to keep track of
177 // a new line fragment with a new start value.
178 if (mappingID - lastID > Byte.MAX_VALUE
179 || mappingID - lastID < Byte.MIN_VALUE) {
180 myLineFragment = new LineFragment(
181 startID, Bytes.toArray(currentOffsets));
182 currentOffsets.clear();
183 // Start a new section.
184 fragmentList.add(myLineFragment);
185 startID = mappingID;
186 } else {
187 currentOffsets.add((byte) (mappingID - lastID));
188 }
189 }
190
191 lastID = mappingID;
192 }
193 if (startID != Integer.MIN_VALUE) {
194 myLineFragment = new LineFragment(
195 startID, Bytes.toArray(currentOffsets));
196 fragmentList.add(myLineFragment);
197 }
198 characterMapBuilder.add(fragmentList.build());
199 }
200 return maxID;
201 }
202
203 private class FileName {
204 private final String dir;
205 private final String name;
206
207 FileName(String directory, String name) {
208 this.dir = directory;
209 this.name = name;
210 }
211 }
212
213 /**
214 * Split the file into a filename/directory pair.
215 *
216 * @param interner The interner to use for interning the strings.
217 * @param input The input to split.
218 * @return The pair of directory, filename.
219 */
220 private FileName splitFileName(
221 Interner<String> interner, String input) {
222 int hashIndex = input.lastIndexOf('/');
223 String dir = interner.intern(input.substring(0, hashIndex + 1));
224 String fileName = interner.intern(input.substring(hashIndex + 1));
225 return new FileName(dir, fileName);
226 }
227
228 /**
229 * Parse the file mappings section of the source map file. This maps the
230 * ids to the filename, line number and column number in the original
231 * files.
232 * @param parser The parser to get the data from.
233 * @param maxID The maximum id found in the character mapping section.
234 */
235 private void parseFileMappings(ParseState parser, int maxID)
236 throws SourceMapParseException, JSONException {
237 // ['d.js', 3, 78, 'foo']
238 // Intern the strings to save memory.
239 Interner<String> interner = Interners.newStrongInterner();
240 ImmutableList.Builder<SourceFile> mappingsBuilder = ImmutableList.builder();
241
242 // Setup all the arrays to keep track of the various details about the
243 // source file.
244 ArrayList<Byte> lineOffsets = Lists.newArrayList();
245 ArrayList<Short> columns = Lists.newArrayList();
246 ArrayList<String> identifiers = Lists.newArrayList();
247
248 // The indexes and details about the current position in the file to do
249 // diffs against.
250 String currentFile = null;
251 int lastLine = -1;
252 int startLine = -1;
253 int startMapId = -1;
254 for (int mappingId = 0; mappingId <= maxID; ++mappingId) {
255 String currentLine = parser.readLine();
256 JSONArray mapArray = new JSONArray(currentLine);
257 if (mapArray.length() < 3) {
258 parser.fail("Invalid mapping array");
259 }
260
261 // Split up the file and directory names to reduce memory usage.
262 String myFile = mapArray.getString(0);
263 int line = mapArray.getInt(1);
264 if (!myFile.equals(currentFile) || (line - lastLine) > Byte.MAX_VALUE
265 || (line - lastLine) < Byte.MIN_VALUE) {
266 if (currentFile != null) {
267 FileName dirFile = splitFileName(interner, currentFile);
268 SourceFile.Builder builder = SourceFile.newBuilder()
269 .setDir(dirFile.dir)
270 .setFileName(dirFile.name)
271 .setStartLine(startLine)
272 .setStartMapId(startMapId)
273 .setLineOffsets(lineOffsets)
274 .setColumns(columns)
275 .setIdentifiers(identifiers);
276 mappingsBuilder.add(builder.build());
277 }
278 // Reset all the positions back to the start and clear out the arrays
279 // to start afresh.
280 currentFile = myFile;
281 startLine = line;
282 lastLine = line;
283 startMapId = mappingId;
284 columns.clear();
285 lineOffsets.clear();
286 identifiers.clear();
287 }
288 // We need to add on the columns and identifiers for all the lines, even
289 // for the first line.
290 lineOffsets.add((byte) (line - lastLine));
291 columns.add((short) mapArray.getInt(2));
292 identifiers.add(interner.intern(mapArray.optString(3, "")));
293 lastLine = line;
294 }
295 if (currentFile != null) {
296 FileName dirFile = splitFileName(interner, currentFile);
297 SourceFile.Builder builder = SourceFile.newBuilder()
298 .setDir(dirFile.dir)
299 .setFileName(dirFile.name)
300 .setStartLine(startLine)
301 .setStartMapId(startMapId)
302 .setLineOffsets(lineOffsets)
303 .setColumns(columns)
304 .setIdentifiers(identifiers);
305 mappingsBuilder.add(builder.build());
306 }
307 mappings = mappingsBuilder.build();
308 }
309
310 private void parseInternal(ParseState parser)
311 throws SourceMapParseException, JSONException {
312
313 // /** Begin line maps. **/{ count: 2 }
314 String headerCount = parser.readLine();
315 Preconditions.checkArgument(headerCount.startsWith(LINEMAP_HEADER),
316 "Expected %s", LINEMAP_HEADER);
317 JSONObject countObject = new JSONObject(
318 headerCount.substring(LINEMAP_HEADER.length()));
319 if (!countObject.has("count")) {
320 parser.fail("Missing 'count'");
321 }
322
323 int lineCount = countObject.getInt("count");
324 if (lineCount <= 0) {
325 parser.fail("Count must be >= 1");
326 }
327 ImmutableList.Builder<ImmutableList<LineFragment>> characterMapBuilder =
328 ImmutableList.builder();
329 int maxId = parseCharacterMap(parser, lineCount, characterMapBuilder);
330 characterMap = characterMapBuilder.build();
331
332 // /** Begin file information. **/
333 parser.expectLine(FILEINFO_HEADER);
334
335 // File information. Not used, so we just consume it.
336 for (int i = 0; i < lineCount; i++) {
337 parser.readLine();
338 }
339
340 // /** Begin mapping definitions. **/
341 parser.expectLine(DEFINITION_HEADER);
342
343 parseFileMappings(parser, maxId);
344 }
345
346 @Override
347 public OriginalMapping getMappingForLine(int lineNumber, int columnIndex) {
348 Preconditions.checkNotNull(characterMap, "parse() must be called first");
349
350 if (lineNumber < 1 || lineNumber > characterMap.size() || columnIndex < 1) {
351 return null;
352 }
353
354 List<LineFragment> lineFragments = characterMap.get(lineNumber - 1);
355 if (lineFragments == null || lineFragments.isEmpty()) {
356 return null;
357 }
358
359 int columnOffset = 0;
360 // The code assumes everything past the end is the same as the last item
361 // so we default to the last item in the line.
362 LineFragment lastFragment = lineFragments.get(lineFragments.size() - 1);
363 int mapId = lastFragment.valueAtColumn(lastFragment.length());
364 for (LineFragment lineFragment : lineFragments) {
365 int columnPosition = columnIndex - columnOffset;
366 if (columnPosition <= lineFragment.length()) {
367 mapId = lineFragment.valueAtColumn(columnPosition);
368 break;
369 }
370 columnOffset += lineFragment.length();
371 }
372
373 if (mapId < 0) {
374 return null;
375 }
376
377 return getMappingFromId(mapId);
378 }
379
380 /**
381 * Do a binary search for the correct mapping array to use.
382 *
383 * @param mapId The mapping array to find
384 * @return The source file mapping to use.
385 */
386 private SourceFile binarySearch(int mapId) {
387 int lower = 0;
388 int upper = mappings.size() - 1;
389
390 while (lower <= upper) {
391 int middle = lower + (upper - lower) / 2;
392 SourceFile middleCompare = mappings.get(middle);
393 if (mapId < middleCompare.getStartMapId()) {
394 upper = middle - 1;
395 } else if (mapId < (middleCompare.getStartMapId()
396 + middleCompare.getLength())) {
397 return middleCompare;
398 } else {
399 lower = middle + 1;
400 }
401 }
402
403 return null;
404 }
405
406 /**
407 * Find the original mapping for the specified mapping id.
408 *
409 * @param mapID The mapID to lookup.
410 * @return The originalMapping protocol buffer for the id.
411 */
412 private OriginalMapping getMappingFromId(int mapID) {
413 SourceFile match = binarySearch(mapID);
414 if (match == null) {
415 return null;
416 }
417 int pos = mapID - match.getStartMapId();
418 return match.getOriginalMapping(pos);
419 }
420
421 /**
422 * Keeps track of the information about the line in a more compact way. It
423 * represents a fragment of the line starting at a specific index and then
424 * looks at offsets from that index stored as a byte, this dramatically
425 * reduces the memory usage of this array.
426 */
427 private static final class LineFragment {
428 private final int startIndex;
429 private final byte[] offsets;
430
431 /**
432 * Create a new line fragment to store information about.
433 *
434 * @param startIndex The start index for this line.
435 * @param offsets The byte array of offsets to store.
436 */
437 LineFragment(int startIndex, byte[] offsets) {
438 this.startIndex = startIndex;
439 this.offsets = offsets;
440 }
441
442 /**
443 * The length of columns stored in the line. One is added because we
444 * store the start index outside of the offsets array.
445 */
446 int length() {
447 return offsets.length + 1;
448 }
449
450 /**
451 * Find the mapping id at the specified column.
452 *
453 * @param column The column to lookup
454 * @return the value at that point in the column
455 */
456 int valueAtColumn(int column) {
457 Preconditions.checkArgument(column > 0);
458 int pos = startIndex;
459 for (int i = 0; i < column - 1; i++) {
460 pos += offsets[i];
461 }
462 return pos;
463 }
464 }
465
466 /**
467 * Keeps track of data about the source file itself. This is contains a list
468 * of line offsets and columns to track down where exactly a line falls into
469 * the data.
470 */
471 private static final class SourceFile {
472 final String dir;
473 final String fileName;
474 final int startMapId;
475 final int startLine;
476 final byte[] lineOffsets;
477 final short[] columns;
478 final String[] identifiers;
479
480 private SourceFile(
481 String dir, String fileName, int startLine, int startMapId,
482 byte[] lineOffsets, short[] columns, String[] identifiers) {
483 this.fileName = Preconditions.checkNotNull(fileName);
484 this.dir = Preconditions.checkNotNull(dir);
485 this.startLine = startLine;
486 this.startMapId = startMapId;
487 this.lineOffsets = Preconditions.checkNotNull(lineOffsets);
488 this.columns = Preconditions.checkNotNull(columns);
489 this.identifiers = Preconditions.checkNotNull(identifiers);
490 Preconditions.checkArgument(lineOffsets.length == columns.length &&
491 columns.length == identifiers.length);
492 }
493
494 private SourceFile(int startMapId) {
495 // Only used for binary searches.
496 this.startMapId = startMapId;
497
498 this.fileName = null;
499 this.dir = null;
500 this.startLine = 0;
501 this.lineOffsets = null;
502 this.columns = null;
503 this.identifiers = null;
504 }
505
506 /**
507 * Returns the number of elements in this source file.
508 */
509 int getLength() {
510 return lineOffsets.length;
511 }
512
513 /**
514 * Returns the number of elements in this source file.
515 */
516 int getStartMapId() {
517 return startMapId;
518 }
519
520 /**
521 * Creates an original mapping from the data.
522 *
523 * @param offset The offset into the array to find the mapping for.
524 * @return A new original mapping object.
525 */
526 OriginalMapping getOriginalMapping(int offset) {
527 int lineNumber = this.startLine;
528 // Offset is an index into this array and we need to include it.
529 for (int i = 0; i <= offset; i++) {
530 lineNumber += lineOffsets[i];
531 }
532 OriginalMapping.Builder builder = OriginalMapping.newBuilder()
533 .setOriginalFile(dir + fileName)
534 .setLineNumber(lineNumber)
535 .setColumnPosition(columns[offset])
536 .setIdentifier(identifiers[offset]);
537 return builder.build();
538 }
539
540 /**
541 * Builder to make a new SourceFile object.
542 */
543 static final class Builder {
544 String dir;
545 String fileName;
546 int startMapId;
547 int startLine;
548 byte[] lineOffsets;
549 short[] columns;
550 String[] identifiers;
551
552 Builder setDir(String dir) {
553 this.dir = dir;
554 return this;
555 }
556
557 Builder setFileName(String fileName) {
558 this.fileName = fileName;
559 return this;
560 }
561
562 Builder setStartMapId(int startMapId) {
563 this.startMapId = startMapId;
564 return this;
565 }
566
567 Builder setStartLine(int startLine) {
568 this.startLine = startLine;
569 return this;
570 }
571
572 Builder setLineOffsets(List<Byte> lineOffsets) {
573 this.lineOffsets = Bytes.toArray(lineOffsets);
574 return this;
575 }
576
577 Builder setColumns(List<Short> columns) {
578 this.columns = Shorts.toArray(columns);
579 return this;
580 }
581
582 Builder setIdentifiers(List<String> identifiers) {
583 this.identifiers = identifiers.toArray(new String[0]);
584 return this;
585 }
586
587 /**
588 * Creates a new SourceFile from the parameters.
589 */
590 SourceFile build() {
591 return new SourceFile(dir, fileName, startLine, startMapId,
592 lineOffsets, columns, identifiers);
593 }
594 }
595
596 static Builder newBuilder() {
597 return new Builder();
598 }
599 }
600 }