Debian Codegraph @

src/com/google/debugging/sourcemap/SourceMapConsumerV3.java

raw symbols SCIP
1 /*
2 * Copyright 2011 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.Lists;
21 import com.google.debugging.sourcemap.Base64VLQ.CharIterator;
22 import com.google.debugging.sourcemap.proto.Mapping.OriginalMapping;
23 import com.google.debugging.sourcemap.proto.Mapping.OriginalMapping.Builder;
24
25 import org.json.JSONArray;
26 import org.json.JSONException;
27 import org.json.JSONObject;
28
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashMap;
35 import java.util.Map;
36
37 /**
38 * Class for parsing version 3 of the SourceMap format, as produced by the
39 * Closure Compiler, etc.
40 * http://code.google.com/p/closure-compiler/wiki/SourceMaps
41 * @author [email protected] (John Lenz)
42 */
43 public class SourceMapConsumerV3 implements SourceMapConsumer,
44 SourceMappingReversable {
45 static final int UNMAPPED = -1;
46
47 private String[] sources;
48 private String[] names;
49 private int lineCount;
50 // Slots in the lines list will be null if the line does not have any entries.
51 private ArrayList<ArrayList<Entry>> lines = null;
52 /** originalFile path ==> original line ==> target mappings */
53 private Map<String, Map<Integer, Collection<OriginalMapping>>>
54 reverseSourceMapping;
55
56 public SourceMapConsumerV3() {
57
58 }
59
60 static class DefaultSourceMapSupplier implements SourceMapSupplier {
61 @Override
62 public String getSourceMap(String url) {
63 return null;
64 }
65 }
66
67 /**
68 * Parses the given contents containing a source map.
69 */
70 @Override
71 public void parse(String contents) throws SourceMapParseException {
72 parse(contents, null);
73 }
74
75 /**
76 * Parses the given contents containing a source map.
77 */
78 public void parse(String contents, SourceMapSupplier sectionSupplier)
79 throws SourceMapParseException {
80 try {
81 JSONObject sourceMapRoot = new JSONObject(contents);
82 parse(sourceMapRoot, sectionSupplier);
83 } catch (JSONException ex) {
84 throw new SourceMapParseException("JSON parse exception: " + ex);
85 }
86 }
87
88 /**
89 * Parses the given contents containing a source map.
90 */
91 public void parse(JSONObject sourceMapRoot) throws SourceMapParseException {
92 parse(sourceMapRoot, null);
93 }
94
95 /**
96 * Parses the given contents containing a source map.
97 */
98 public void parse(JSONObject sourceMapRoot, SourceMapSupplier sectionSupplier)
99 throws SourceMapParseException {
100 try {
101 // Check basic assertions about the format.
102 int version = sourceMapRoot.getInt("version");
103 if (version != 3) {
104 throw new SourceMapParseException("Unknown version: " + version);
105 }
106
107 String file = sourceMapRoot.getString("file");
108 if (file.isEmpty()) {
109 throw new SourceMapParseException("File entry is missing or empty");
110 }
111
112 if (sourceMapRoot.has("sections")) {
113 // Looks like a index map, try to parse it that way.
114 parseMetaMap(sourceMapRoot, sectionSupplier);
115 return;
116 }
117
118 lineCount = sourceMapRoot.getInt("lineCount");
119 String lineMap = sourceMapRoot.getString("mappings");
120
121 sources = getJavaStringArray(sourceMapRoot.getJSONArray("sources"));
122 names = getJavaStringArray(sourceMapRoot.getJSONArray("names"));
123
124 lines = Lists.newArrayListWithCapacity(lineCount);
125
126 new MappingBuilder(lineMap).build();
127 } catch (JSONException ex) {
128 throw new SourceMapParseException("JSON parse exception: " + ex);
129 }
130 }
131
132 /**
133 * @param sourceMapRoot
134 * @throws SourceMapParseException
135 */
136 private void parseMetaMap(
137 JSONObject sourceMapRoot, SourceMapSupplier sectionSupplier)
138 throws SourceMapParseException {
139 if (sectionSupplier == null) {
140 sectionSupplier = new DefaultSourceMapSupplier();
141 }
142
143 try {
144 // Check basic assertions about the format.
145 int version = sourceMapRoot.getInt("version");
146 if (version != 3) {
147 throw new SourceMapParseException("Unknown version: " + version);
148 }
149
150 String file = sourceMapRoot.getString("file");
151 if (file.isEmpty()) {
152 throw new SourceMapParseException("File entry is missing or empty");
153 }
154
155 if (sourceMapRoot.has("lineCount")
156 || sourceMapRoot.has("mappings")
157 || sourceMapRoot.has("sources")
158 || sourceMapRoot.has("names")) {
159 throw new SourceMapParseException("Invalid map format");
160 }
161
162 SourceMapGeneratorV3 generator = new SourceMapGeneratorV3();
163 JSONArray sections = sourceMapRoot.getJSONArray("sections");
164 for (int i = 0, count = sections.length(); i < count; i++) {
165 JSONObject section = sections.getJSONObject(i);
166 if (section.has("map") && section.has("url")) {
167 throw new SourceMapParseException(
168 "Invalid map format: section may not have both 'map' and 'url'");
169 }
170 JSONObject offset = section.getJSONObject("offset");
171 int line = offset.getInt("line");
172 int column = offset.getInt("column");
173 String mapSectionContents;
174 if (section.has("url")) {
175 String url = section.getString("url");
176 mapSectionContents = sectionSupplier.getSourceMap(url);
177 if (mapSectionContents == null) {
178 throw new SourceMapParseException("Unable to retrieve: " + url);
179 }
180 } else if (section.has("map")) {
181 mapSectionContents = section.getString("map");
182 } else {
183 throw new SourceMapParseException(
184 "Invalid map format: section must have either 'map' or 'url'");
185 }
186 generator.mergeMapSection(line, column, mapSectionContents);
187 }
188
189 StringBuilder sb = new StringBuilder();
190 try {
191 generator.appendTo(sb, file);
192 } catch (IOException e) {
193 // Can't happen.
194 throw new RuntimeException(e);
195 }
196
197 parse(sb.toString());
198 } catch (IOException ex) {
199 throw new SourceMapParseException("IO exception: " + ex);
200 } catch (JSONException ex) {
201 throw new SourceMapParseException("JSON parse exception: " + ex);
202 }
203 }
204
205 @Override
206 public OriginalMapping getMappingForLine(int lineNumber, int column) {
207 // Normalize the line and column numbers to 0.
208 lineNumber--;
209 column--;
210
211 if (lineNumber < 0 || lineNumber >= lines.size()) {
212 return null;
213 }
214
215 Preconditions.checkState(lineNumber >= 0);
216 Preconditions.checkState(column >= 0);
217
218
219 // If the line is empty return the previous mapping.
220 if (lines.get(lineNumber) == null) {
221 return getPreviousMapping(lineNumber);
222 }
223
224 ArrayList<Entry> entries = lines.get(lineNumber);
225 // No empty lists.
226 Preconditions.checkState(entries.size() > 0);
227 if (entries.get(0).getGeneratedColumn() > column) {
228 return getPreviousMapping(lineNumber);
229 }
230
231 int index = search(entries, column, 0, entries.size() - 1);
232 Preconditions.checkState(index >= 0, "unexpected:%s", index);
233 return getOriginalMappingForEntry(entries.get(index));
234 }
235
236 @Override
237 public Collection<String> getOriginalSources() {
238 return Arrays.asList(sources);
239 }
240
241 @Override
242 public Collection<OriginalMapping> getReverseMapping(String originalFile,
243 int line, int column) {
244 // TODO(user): This implementation currently does not make use of the column
245 // parameter.
246
247 // Synchronization needs to be handled by callers.
248 if (reverseSourceMapping == null) {
249 createReverseMapping();
250 }
251
252 Map<Integer, Collection<OriginalMapping>> sourceLineToCollectionMap =
253 reverseSourceMapping.get(originalFile);
254
255 if (sourceLineToCollectionMap == null) {
256 return Collections.emptyList();
257 } else {
258 Collection<OriginalMapping> mappings =
259 sourceLineToCollectionMap.get(line);
260
261 if (mappings == null) {
262 return Collections.emptyList();
263 } else {
264 return mappings;
265 }
266 }
267 }
268
269 private String[] getJavaStringArray(JSONArray array) throws JSONException {
270 int len = array.length();
271 String[] result = new String[len];
272 for(int i = 0; i < len; i++) {
273 result[i] = array.getString(i);
274 }
275 return result;
276 }
277
278 private class MappingBuilder {
279 private static final int MAX_ENTRY_VALUES = 5;
280 private final StringCharIterator content;
281 private int line = 0;
282 private int previousCol = 0;
283 private int previousSrcId = 0;
284 private int previousSrcLine = 0;
285 private int previousSrcColumn = 0;
286 private int previousNameId = 0;
287
288 MappingBuilder(String lineMap) {
289 this.content = new StringCharIterator(lineMap);
290 }
291
292 void build() {
293 int [] temp = new int[MAX_ENTRY_VALUES];
294 ArrayList<Entry> entries = new ArrayList<Entry>();
295 while (content.hasNext()) {
296 // ';' denotes a new line.
297 if (tryConsumeToken(';')) {
298 // The line is complete, store the result for the line,
299 // null if the line is empty.
300 ArrayList<Entry> result;
301 if (entries.size() > 0) {
302 result = entries;
303 // A new array list for the next line.
304 entries = new ArrayList<Entry>();
305 } else {
306 result = null;
307 }
308 lines.add(result);
309 entries.clear();
310 line++;
311 previousCol = 0;
312 } else {
313 // grab the next entry for the current line.
314 int entryValues = 0;
315 while (!entryComplete()) {
316 temp[entryValues] = nextValue();
317 entryValues++;
318 }
319 Entry entry = decodeEntry(temp, entryValues);
320
321 validateEntry(entry);
322 entries.add(entry);
323
324 // Consume the separating token, if there is one.
325 tryConsumeToken(',');
326 }
327 }
328 }
329
330 /**
331 * Sanity check the entry.
332 */
333 private void validateEntry(Entry entry) {
334 Preconditions.checkState(line < lineCount);
335 Preconditions.checkState(entry.getSourceFileId() == UNMAPPED
336 || entry.getSourceFileId() < sources.length);
337 Preconditions.checkState(entry.getNameId() == UNMAPPED
338 || entry.getNameId() < names.length);
339 }
340
341 /**
342 * Decodes the next entry, using the previous encountered values to
343 * decode the relative values.
344 *
345 * @param vals An array of integers that represent values in the entry.
346 * @param entryValues The number of entries in the array.
347 * @return The entry object.
348 */
349 private Entry decodeEntry(int[] vals, int entryValues) {
350 Entry entry;
351 switch (entryValues) {
352 // The first values, if present are in the following order:
353 // 0: the starting column in the current line of the generated file
354 // 1: the id of the original source file
355 // 2: the starting line in the original source
356 // 3: the starting column in the original source
357 // 4: the id of the original symbol name
358 // The values are relative to the last encountered value for that field.
359 // Note: the previously column value for the generated file is reset
360 // to '0' when a new line is encountered. This is done in the 'build'
361 // method.
362
363 case 1:
364 // An unmapped section of the generated file.
365 entry = new UnmappedEntry(
366 vals[0] + previousCol);
367 // Set the values see for the next entry.
368 previousCol = entry.getGeneratedColumn();
369 return entry;
370
371 case 4:
372 // A mapped section of the generated file.
373 entry = new UnnamedEntry(
374 vals[0] + previousCol,
375 vals[1] + previousSrcId,
376 vals[2] + previousSrcLine,
377 vals[3] + previousSrcColumn);
378 // Set the values see for the next entry.
379 previousCol = entry.getGeneratedColumn();
380 previousSrcId = entry.getSourceFileId();
381 previousSrcLine = entry.getSourceLine();
382 previousSrcColumn = entry.getSourceColumn();
383 return entry;
384
385 case 5:
386 // A mapped section of the generated file, that has an associated
387 // name.
388 entry = new NamedEntry(
389 vals[0] + previousCol,
390 vals[1] + previousSrcId,
391 vals[2] + previousSrcLine,
392 vals[3] + previousSrcColumn,
393 vals[4] + previousNameId);
394 // Set the values see for the next entry.
395 previousCol = entry.getGeneratedColumn();
396 previousSrcId = entry.getSourceFileId();
397 previousSrcLine = entry.getSourceLine();
398 previousSrcColumn = entry.getSourceColumn();
399 previousNameId = entry.getNameId();
400 return entry;
401
402 default:
403 throw new IllegalStateException(
404 "Unexpected number of values for entry:" + entryValues);
405 }
406 }
407
408 private boolean tryConsumeToken(char token) {
409 if (content.hasNext() && content.peek() == token) {
410 // consume the comma
411 content.next();
412 return true;
413 }
414 return false;
415 }
416
417 private boolean entryComplete() {
418 if (!content.hasNext()) {
419 return true;
420 }
421
422 char c = content.peek();
423 return (c == ';' || c == ',');
424 }
425
426 private int nextValue() {
427 return Base64VLQ.decode(content);
428 }
429 }
430
431 /**
432 * Perform a binary search on the array to find a section that covers
433 * the target column.
434 */
435 private int search(ArrayList<Entry> entries, int target, int start, int end) {
436 while (true) {
437 int mid = ((end - start) / 2) + start;
438 int compare = compareEntry(entries, mid, target);
439 if (compare == 0) {
440 return mid;
441 } else if (compare < 0) {
442 // it is in the upper half
443 start = mid + 1;
444 if (start > end) {
445 return end;
446 }
447 } else {
448 // it is in the lower half
449 end = mid - 1;
450 if (end < start) {
451 return end;
452 }
453 }
454 }
455 }
456
457 /**
458 * Compare an array entry's column value to the target column value.
459 */
460 private int compareEntry(ArrayList<Entry> entries, int entry, int target) {
461 return entries.get(entry).getGeneratedColumn() - target;
462 }
463
464 /**
465 * Returns the mapping entry that proceeds the supplied line or null if no
466 * such entry exists.
467 */
468 private OriginalMapping getPreviousMapping(int lineNumber) {
469 do {
470 if (lineNumber == 0) {
471 return null;
472 }
473 lineNumber--;
474 } while (lines.get(lineNumber) == null);
475 ArrayList<Entry> entries = lines.get(lineNumber);
476 return getOriginalMappingForEntry(entries.get(entries.size() - 1));
477 }
478
479 /**
480 * Creates an "OriginalMapping" object for the given entry object.
481 */
482 private OriginalMapping getOriginalMappingForEntry(Entry entry) {
483 if (entry.getSourceFileId() == UNMAPPED) {
484 return null;
485 } else {
486 // Adjust the line/column here to be start at 1.
487 Builder x = OriginalMapping.newBuilder()
488 .setOriginalFile(sources[entry.getSourceFileId()])
489 .setLineNumber(entry.getSourceLine() + 1)
490 .setColumnPosition(entry.getSourceColumn() + 1);
491 if (entry.getNameId() != UNMAPPED) {
492 x.setIdentifier(names[entry.getNameId()]);
493 }
494 return x.build();
495 }
496 }
497
498 /**
499 * Reverse the source map; the created mapping will allow us to quickly go
500 * from a source file and line number to a collection of target
501 * OriginalMappings.
502 */
503 private void createReverseMapping() {
504 reverseSourceMapping =
505 new HashMap<String, Map<Integer, Collection<OriginalMapping>>>();
506
507 for (int targetLine = 0; targetLine < lines.size(); targetLine++) {
508 ArrayList<Entry> entries = lines.get(targetLine);
509
510 if (entries != null) {
511 for (Entry entry : entries) {
512 if (entry.getSourceFileId() != UNMAPPED
513 && entry.getSourceLine() != UNMAPPED) {
514 String originalFile = sources[entry.getSourceFileId()];
515
516 if (!reverseSourceMapping.containsKey(originalFile)) {
517 reverseSourceMapping.put(originalFile,
518 new HashMap<Integer, Collection<OriginalMapping>>());
519 }
520
521 Map<Integer, Collection<OriginalMapping>> lineToCollectionMap =
522 reverseSourceMapping.get(originalFile);
523
524 int sourceLine = entry.getSourceLine();
525
526 if (!lineToCollectionMap.containsKey(sourceLine)) {
527 lineToCollectionMap.put(sourceLine,
528 new ArrayList<OriginalMapping>(1));
529 }
530
531 Collection<OriginalMapping> mappings =
532 lineToCollectionMap.get(sourceLine);
533
534 Builder builder = OriginalMapping.newBuilder().setLineNumber(
535 targetLine).setColumnPosition(entry.getGeneratedColumn());
536
537 mappings.add(builder.build());
538 }
539 }
540 }
541 }
542 }
543
544 /**
545 * A implementation of the Base64VLQ CharIterator used for decoding the
546 * mappings encoded in the JSON string.
547 */
548 private static class StringCharIterator implements CharIterator {
549 final String content;
550 final int length;
551 int current = 0;
552
553 StringCharIterator(String content) {
554 this.content = content;
555 this.length = content.length();
556 }
557
558 @Override
559 public char next() {
560 return content.charAt(current++);
561 }
562
563 char peek() {
564 return content.charAt(current);
565 }
566
567 @Override
568 public boolean hasNext() {
569 return current < length;
570 }
571 }
572
573 /**
574 * Represents a mapping entry in the source map.
575 */
576 private interface Entry {
577 int getGeneratedColumn();
578 int getSourceFileId();
579 int getSourceLine();
580 int getSourceColumn();
581 int getNameId();
582 }
583
584 /**
585 * This class represents a portion of the generated file, that is not mapped
586 * to a section in the original source.
587 */
588 private static class UnmappedEntry implements Entry {
589 private final int column;
590
591 UnmappedEntry(int column) {
592 this.column = column;
593 }
594
595 @Override
596 public int getGeneratedColumn() {
597 return column;
598 }
599
600 @Override
601 public int getSourceFileId() {
602 return UNMAPPED;
603 }
604
605 @Override
606 public int getSourceLine() {
607 return UNMAPPED;
608 }
609
610 @Override
611 public int getSourceColumn() {
612 return UNMAPPED;
613 }
614
615 @Override
616 public int getNameId() {
617 return UNMAPPED;
618 }
619 }
620
621 /**
622 * This class represents a portion of the generated file, that is mapped
623 * to a section in the original source.
624 */
625 private static class UnnamedEntry extends UnmappedEntry {
626 private final int srcFile;
627 private final int srcLine;
628 private final int srcColumn;
629
630 UnnamedEntry(int column, int srcFile, int srcLine, int srcColumn) {
631 super(column);
632 this.srcFile = srcFile;
633 this.srcLine = srcLine;
634 this.srcColumn = srcColumn;
635 }
636
637 @Override
638 public int getSourceFileId() {
639 return srcFile;
640 }
641
642 @Override
643 public int getSourceLine() {
644 return srcLine;
645 }
646
647 @Override
648 public int getSourceColumn() {
649 return srcColumn;
650 }
651
652 @Override
653 public int getNameId() {
654 return UNMAPPED;
655 }
656 }
657
658 /**
659 * This class represents a portion of the generated file, that is mapped
660 * to a section in the original source, and is associated with a name.
661 */
662 private static class NamedEntry extends UnnamedEntry {
663 private final int name;
664
665 NamedEntry(int column, int srcFile, int srcLine, int srcColumn, int name) {
666 super(column, srcFile, srcLine, srcColumn);
667 this.name = name;
668 }
669
670 @Override
671 public int getNameId() {
672 return name;
673 }
674 }
675
676 public static interface EntryVisitor {
677 void visit(String sourceName,
678 String symbolName,
679 FilePosition sourceStartPosition,
680 FilePosition startPosition,
681 FilePosition endPosition);
682 }
683
684 public void visitMappings(EntryVisitor visitor) {
685 boolean pending = false;
686 String sourceName = null;
687 String symbolName = null;
688 FilePosition sourceStartPosition = null;
689 FilePosition startPosition = null;
690
691 final int lineCount = lines.size();
692 for (int i = 0; i < lineCount; i++) {
693 ArrayList<Entry> line = lines.get(i);
694 if (line != null) {
695 final int entryCount = line.size();
696 for (int j = 0; j < entryCount; j++) {
697 Entry entry = line.get(j);
698 if (pending) {
699 FilePosition endPosition = new FilePosition(
700 i, entry.getGeneratedColumn());
701 visitor.visit(
702 sourceName,
703 symbolName,
704 sourceStartPosition,
705 startPosition,
706 endPosition);
707 pending = false;
708 }
709
710 if (entry.getSourceFileId() != UNMAPPED) {
711 pending = true;
712 sourceName = sources[entry.getSourceFileId()];
713 symbolName = (entry.getNameId() != UNMAPPED)
714 ? names[entry.getNameId()] : null;
715 sourceStartPosition = new FilePosition(
716 entry.getSourceLine(), entry.getSourceColumn());
717 startPosition = new FilePosition(
718 i, entry.getGeneratedColumn());
719 }
720 }
721 }
722 }
723 }
724 }