Debian Codegraph @

src/com/google/debugging/sourcemap/SourceMapGeneratorV3.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.common.collect.Maps;
22 import com.google.debugging.sourcemap.SourceMapConsumerV3.EntryVisitor;
23
24 import java.io.IOException;
25 import java.util.ArrayDeque;
26 import java.util.Deque;
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31
32 import javax.annotation.Nullable;
33
34 /**
35 * Collects information mapping the generated (compiled) source back to
36 * its original source for debugging purposes.
37 *
38 * @author [email protected] (John Lenz)
39 */
40 public class SourceMapGeneratorV3 implements SourceMapGenerator {
41
42 private static final int UNMAPPED = -1;
43
44
45 /**
46 * A pre-order traversal ordered list of mappings stored in this map.
47 */
48 private List<Mapping> mappings = Lists.newArrayList();
49
50 /**
51 * A map of source names to source name index
52 */
53 private LinkedHashMap<String, Integer> sourceFileMap =
54 Maps.newLinkedHashMap();
55
56 /**
57 * A map of source names to source name index
58 */
59 private LinkedHashMap<String, Integer> originalNameMap =
60 Maps.newLinkedHashMap();
61
62 /**
63 * Cache of the last mappings source name.
64 */
65 private String lastSourceFile = null;
66
67 /**
68 * Cache of the last mappings source name index.
69 */
70 private int lastSourceFileIndex = -1;
71
72 /**
73 * For validation store the last mapping added.
74 */
75 private Mapping lastMapping;
76
77 /**
78 * The position that the current source map is offset in the
79 * buffer being used to generated the compiled source file.
80 */
81 private FilePosition offsetPosition = new FilePosition(0, 0);
82
83 /**
84 * The position that the current source map is offset in the
85 * generated the compiled source file by the addition of a
86 * an output wrapper prefix.
87 */
88 private FilePosition prefixPosition = new FilePosition(0, 0);
89
90
91 /**
92 * {@inheritDoc}
93 */
94 @Override
95 public void reset() {
96 mappings.clear();
97 lastMapping = null;
98 sourceFileMap.clear();
99 originalNameMap.clear();
100 lastSourceFile = null;
101 lastSourceFileIndex = -1;
102 offsetPosition = new FilePosition(0, 0);
103 prefixPosition = new FilePosition(0, 0);
104 }
105
106 /**
107 * @param validate Whether to perform (potentially costly) validation on the
108 * generated source map.
109 */
110 @Override
111 public void validate(boolean validate) {
112 // Nothing currently.
113 }
114
115 /**
116 * Sets the prefix used for wrapping the generated source file before
117 * it is written. This ensures that the source map is adjusted for the
118 * change in character offsets.
119 *
120 * @param prefix The prefix that is added before the generated source code.
121 */
122 @Override
123 public void setWrapperPrefix(String prefix) {
124 // Determine the current line and character position.
125 int prefixLine = 0;
126 int prefixIndex = 0;
127
128 for (int i = 0; i < prefix.length(); ++i) {
129 if (prefix.charAt(i) == '\n') {
130 prefixLine++;
131 prefixIndex = 0;
132 } else {
133 prefixIndex++;
134 }
135 }
136
137 prefixPosition = new FilePosition(prefixLine, prefixIndex);
138 }
139
140 /**
141 * Sets the source code that exists in the buffer for which the
142 * generated code is being generated. This ensures that the source map
143 * accurately reflects the fact that the source is being appended to
144 * an existing buffer and as such, does not start at line 0, position 0
145 * but rather some other line and position.
146 *
147 * @param offsetLine The index of the current line being printed.
148 * @param offsetIndex The column index of the current character being printed.
149 */
150 @Override
151 public void setStartingPosition(int offsetLine, int offsetIndex) {
152 Preconditions.checkState(offsetLine >= 0);
153 Preconditions.checkState(offsetIndex >= 0);
154 offsetPosition = new FilePosition(offsetLine, offsetIndex);
155 }
156
157 /**
158 * Adds a mapping for the given node. Mappings must be added in order.
159 * @param startPosition The position on the starting line
160 * @param endPosition The position on the ending line.
161 */
162 @Override
163 public void addMapping(
164 String sourceName, @Nullable String symbolName,
165 FilePosition sourceStartPosition,
166 FilePosition startPosition, FilePosition endPosition) {
167
168 // Don't bother if there is not sufficient information to be useful.
169 if (sourceName == null || sourceStartPosition.getLine() < 0) {
170 return;
171 }
172
173 FilePosition adjustedStart = startPosition;
174 FilePosition adjustedEnd = endPosition;
175
176 if (offsetPosition.getLine() != 0
177 || offsetPosition.getColumn() != 0) {
178 // If the mapping is found on the first line, we need to offset
179 // its character position by the number of characters found on
180 // the *last* line of the source file to which the code is
181 // being generated.
182 int offsetLine = offsetPosition.getLine();
183 int startOffsetPosition = offsetPosition.getColumn();
184 int endOffsetPosition = offsetPosition.getColumn();
185
186 if (startPosition.getLine() > 0) {
187 startOffsetPosition = 0;
188 }
189
190 if (endPosition.getLine() > 0) {
191 endOffsetPosition = 0;
192 }
193
194 adjustedStart = new FilePosition(
195 startPosition.getLine() + offsetLine,
196 startPosition.getColumn() + startOffsetPosition);
197
198 adjustedEnd = new FilePosition(
199 endPosition.getLine() + offsetLine,
200 endPosition.getColumn() + endOffsetPosition);
201 }
202
203 // Create the new mapping.
204 Mapping mapping = new Mapping();
205 mapping.sourceFile = sourceName;
206 mapping.originalPosition = sourceStartPosition;
207 mapping.originalName = symbolName;
208 mapping.startPosition = adjustedStart;
209 mapping.endPosition = adjustedEnd;
210
211 // Validate the mappings are in a proper order.
212 if (lastMapping != null) {
213 int lastLine = lastMapping.startPosition.getLine();
214 int lastColumn = lastMapping.startPosition.getColumn();
215 int nextLine = mapping.startPosition.getLine();
216 int nextColumn = mapping.startPosition.getColumn();
217 Preconditions.checkState(nextLine > lastLine
218 || (nextLine == lastLine && nextColumn >= lastColumn),
219 "Incorrect source mappings order, previous : (%s,%s)\n"
220 + "new : (%s,%s)\nnode : %s",
221 lastLine, lastColumn, nextLine, nextColumn);
222 }
223
224 lastMapping = mapping;
225 mappings.add(mapping);
226 }
227
228 class ConsumerEntryVisitor implements EntryVisitor {
229
230 @Override
231 public void visit(
232 String sourceName, String symbolName,
233 FilePosition sourceStartPosition,
234 FilePosition startPosition, FilePosition endPosition) {
235 addMapping(sourceName, symbolName,
236 sourceStartPosition, startPosition, endPosition);
237 }
238 }
239
240 public void mergeMapSection(int line, int column, String mapSectionContents)
241 throws SourceMapParseException {
242 setStartingPosition(line, column);
243 SourceMapConsumerV3 section = new SourceMapConsumerV3();
244 section.parse(mapSectionContents);
245 section.visitMappings(new ConsumerEntryVisitor());
246 }
247
248 /**
249 * Writes out the source map in the following format (line numbers are for
250 * reference only and are not part of the format):
251 *
252 * 1. {
253 * 2. version: 3,
254 * 3. file: "out.js",
255 * 4. lineCount: 2,
256 * 5. sourceRoot: "",
257 * 6. sources: ["foo.js", "bar.js"],
258 * 7. names: ["src", "maps", "are", "fun"],
259 * 8. mappings: "a;;abcde,abcd,a;"
260 * 9. }
261 *
262 * Line 1: The entire file is a single JSON object
263 * Line 2: File revision (always the first entry in the object)
264 * Line 3: The name of the file that this source map is associated with.
265 * Line 4: The number of lines represented in the source map.
266 * Line 5: An optional source root, useful for relocating source files on a
267 * server or removing repeated prefix values in the "sources" entry.
268 * Line 6: A list of sources used by the "mappings" entry relative to the
269 * sourceRoot.
270 * Line 7: A list of symbol names used by the "mapping" entry. This list
271 * may be incomplete.
272 * Line 8: The mappings field.
273 */
274 @Override
275 public void appendTo(Appendable out, String name) throws IOException {
276 int maxLine = prepMappings();
277
278 // Add the header fields.
279 out.append("{\n");
280 appendFirstField(out, "version", "3");
281 appendField(out, "file", escapeString(name));
282 appendField(out, "lineCount", String.valueOf(maxLine + 1));
283
284 // Add the mappings themselves.
285 appendFieldStart(out, "mappings");
286 // out.append("[");
287 (new LineMapper(out)).appendLineMappings();
288 // out.append("]");
289 appendFieldEnd(out);
290
291 // Files names
292 appendFieldStart(out, "sources");
293 out.append("[");
294 addSourceNameMap(out);
295 out.append("]");
296 appendFieldEnd(out);
297
298 // Files names
299 appendFieldStart(out, "names");
300 out.append("[");
301 addSymbolNameMap(out);
302 out.append("]");
303 appendFieldEnd(out);
304
305 out.append("\n}\n");
306 }
307
308 /**
309 * Writes the source name map to 'out'.
310 */
311 private void addSourceNameMap(Appendable out) throws IOException {
312 addNameMap(out, sourceFileMap);
313 }
314
315 /**
316 * Writes the source name map to 'out'.
317 */
318 private void addSymbolNameMap(Appendable out) throws IOException {
319 addNameMap(out, originalNameMap);
320 }
321
322 private void addNameMap(Appendable out, Map<String, Integer> map)
323 throws IOException {
324 int i = 0;
325 for (Entry<String, Integer> entry : map.entrySet()) {
326 String key = entry.getKey();
327 if (i != 0) {
328 out.append(",");
329 }
330 out.append(escapeString(key));
331 i++;
332 }
333 }
334
335 /**
336 * Escapes the given string for JSON.
337 */
338 private static String escapeString(String value) {
339 return Util.escapeString(value);
340 }
341
342 // Source map field helpers.
343
344 private static void appendFirstField(
345 Appendable out, String name, CharSequence value)
346 throws IOException {
347 out.append("\"");
348 out.append(name);
349 out.append("\"");
350 out.append(":");
351 out.append(value);
352 }
353
354 private static void appendField(
355 Appendable out, String name, CharSequence value)
356 throws IOException {
357 out.append(",\n");
358 out.append("\"");
359 out.append(name);
360 out.append("\"");
361 out.append(":");
362 out.append(value);
363 }
364
365 private static void appendFieldStart(Appendable out, String name)
366 throws IOException {
367 appendField(out, name, "");
368 }
369
370 @SuppressWarnings("unused")
371 private static void appendFieldEnd(Appendable out)
372 throws IOException {
373 }
374
375 /**
376 * Assigns sequential ids to used mappings, and returns the last line mapped.
377 */
378 private int prepMappings() throws IOException {
379 // Mark any unused mappings.
380 (new MappingTraversal()).traverse(new UsedMappingCheck());
381
382 // Renumber used mappings and keep track of the last line.
383 int id = 0;
384 int maxLine = 0;
385 for (Mapping m : mappings) {
386 if (m.used) {
387 m.id = id++;
388 int endPositionLine = m.endPosition.getLine();
389 maxLine = Math.max(maxLine, endPositionLine);
390 }
391 }
392
393 // Adjust for the prefix.
394 return maxLine + prefixPosition.getLine();
395 }
396
397 /**
398 * A mapping from a given position in an input source file to a given position
399 * in the generated code.
400 */
401 static class Mapping {
402 /**
403 * A unique ID for this mapping for record keeping purposes.
404 */
405 int id = UNMAPPED;
406
407 /**
408 * The source file index.
409 */
410 String sourceFile;
411
412 /**
413 * The position of the code in the input source file. Both
414 * the line number and the character index are indexed by
415 * 1 for legacy reasons via the Rhino Node class.
416 */
417 FilePosition originalPosition;
418
419 /**
420 * The starting position of the code in the generated source
421 * file which this mapping represents. Indexed by 0.
422 */
423 FilePosition startPosition;
424
425 /**
426 * The ending position of the code in the generated source
427 * file which this mapping represents. Indexed by 0.
428 */
429 FilePosition endPosition;
430
431 /**
432 * The original name of the token found at the position
433 * represented by this mapping (if any).
434 */
435 String originalName;
436
437 /**
438 * Whether the mapping is actually used by the source map.
439 */
440 boolean used = false;
441 }
442
443 /**
444 * Mark any visited mapping as "used".
445 */
446 private class UsedMappingCheck implements MappingVisitor {
447 /**
448 * @throws IOException
449 */
450 @Override
451 public void visit(Mapping m, int line, int col, int nextLine, int nextCol)
452 throws IOException {
453 if (m != null) {
454 m.used = true;
455 }
456 }
457 }
458
459 private interface MappingVisitor {
460 /**
461 * @param m The mapping for the current code segment. null if the segment
462 * is unmapped.
463 * @param line The starting line for this code segment.
464 * @param col The starting column for this code segment.
465 * @param endLine The ending line
466 * @param endCol The ending column
467 * @throws IOException
468 */
469 void visit(Mapping m, int line, int col, int endLine, int endCol)
470 throws IOException;
471 }
472
473 /**
474 * Walk the mappings and visit each segment of the mappings, unmapped
475 * segments are visited with a null mapping, unused mapping are not visited.
476 */
477 private class MappingTraversal {
478 // The last line and column written
479 private int line;
480 private int col;
481
482 MappingTraversal() {
483 }
484
485 // Append the line mapping entries.
486 void traverse(MappingVisitor v) throws IOException {
487 // The mapping list is ordered as a pre-order traversal. The mapping
488 // positions give us enough information to rebuild the stack and this
489 // allows the building of the source map in O(n) time.
490 Deque<Mapping> stack = new ArrayDeque<Mapping>();
491 for (Mapping m : mappings) {
492 // Find the closest ancestor of the current mapping:
493 // An overlapping mapping is an ancestor of the current mapping, any
494 // non-overlapping mappings are siblings (or cousins) and must be
495 // closed in the reverse order of when they encountered.
496 while (!stack.isEmpty() && !isOverlapped(stack.peek(), m)) {
497 Mapping previous = stack.pop();
498 maybeVisit(v, previous);
499 }
500
501 // Any gaps between the current line position and the start of the
502 // current mapping belong to the parent.
503 Mapping parent = stack.peek();
504 maybeVisitParent(v, parent, m);
505
506 stack.push(m);
507 }
508
509 // There are no more children to be had, simply close the remaining
510 // mappings in the reverse order of when they encountered.
511 while (!stack.isEmpty()) {
512 Mapping m = stack.pop();
513 maybeVisit(v, m);
514 }
515 }
516
517 /**
518 * @return The line adjusted for the prefix position.
519 */
520 private int getAdjustedLine(FilePosition p) {
521 return p.getLine() + prefixPosition.getLine();
522 }
523
524 /**
525 * @return The column adjusted for the prefix position.
526 */
527 private int getAdjustedCol(FilePosition p) {
528 int rawLine = p.getLine();
529 int rawCol = p.getColumn();
530 // Only the first line needs the character position adjusted.
531 return (rawLine != 0)
532 ? rawCol : rawCol + prefixPosition.getColumn();
533 }
534
535 /**
536 * @return Whether m1 ends before m2 starts.
537 */
538 private boolean isOverlapped(Mapping m1, Mapping m2) {
539 // No need to use adjusted values here, relative positions are sufficient.
540 int l1 = m1.endPosition.getLine();
541 int l2 = m2.startPosition.getLine();
542 int c1 = m1.endPosition.getColumn();
543 int c2 = m2.startPosition.getColumn();
544
545 return (l1 == l2 && c1 >= c2) || l1 > l2;
546 }
547
548 /**
549 * Write any needed entries from the current position to the end of the
550 * provided mapping.
551 */
552 private void maybeVisit(MappingVisitor v, Mapping m) throws IOException {
553 int nextLine = getAdjustedLine(m.endPosition);
554 int nextCol = getAdjustedCol(m.endPosition);
555 // If this anything remaining in this mapping beyond the
556 // current line and column position, write it out now.
557 if (line < nextLine || (line == nextLine && col < nextCol)) {
558 visit(v, m, nextLine, nextCol);
559 }
560 }
561
562 /**
563 * Write any needed entries to complete the provided mapping.
564 */
565 private void maybeVisitParent(MappingVisitor v, Mapping parent, Mapping m)
566 throws IOException {
567 int nextLine = getAdjustedLine(m.startPosition);
568 int nextCol = getAdjustedCol(m.startPosition);
569 // If the previous value is null, no mapping exists.
570 Preconditions.checkState(line < nextLine || col <= nextCol);
571 if (line < nextLine || (line == nextLine && col < nextCol)) {
572 visit(v, parent, nextLine, nextCol);
573 }
574 }
575
576 /**
577 * Write any entries needed between the current position the next position
578 * and update the current position.
579 */
580 private void visit(MappingVisitor v, Mapping m,
581 int nextLine, int nextCol)
582 throws IOException {
583 Preconditions.checkState(line <= nextLine);
584 Preconditions.checkState(line < nextLine || col < nextCol);
585
586 if (line == nextLine && col == nextCol) {
587 // Nothing to do.
588 Preconditions.checkState(false);
589 return;
590 }
591
592 v.visit(m, line, col, nextLine, nextCol);
593
594 line = nextLine;
595 col = nextCol;
596 }
597 }
598
599 /**
600 * Appends the index source map to the given buffer.
601 *
602 * @param out The stream to which the map will be appended.
603 * @param name The name of the generated source file that this source map
604 * represents.
605 * @param sections An ordered list of map sections to include in the index.
606 * @throws IOException
607 */
608 @Override
609 public void appendIndexMapTo(
610 Appendable out, String name, List<SourceMapSection> sections)
611 throws IOException {
612 // Add the header fields.
613 out.append("{\n");
614 appendFirstField(out, "version", "3");
615 appendField(out, "file", escapeString(name));
616
617 // Add the line character maps.
618 appendFieldStart(out, "sections");
619 out.append("[\n");
620 boolean first = true;
621 for (SourceMapSection section : sections) {
622 if (first) {
623 first = false;
624 } else {
625 out.append(",\n");
626 }
627 out.append("{\n");
628 appendFirstField(out, "offset",
629 offsetValue(section.getLine(), section.getColumn()));
630 if (section.getSectionType() == SourceMapSection.SectionType.URL) {
631 appendField(out, "url", escapeString(section.getSectionValue()));
632 } else if (section.getSectionType() == SourceMapSection.SectionType.MAP) {
633 appendField(out, "map", section.getSectionValue());
634 } else {
635 throw new IOException("Unexpected section type");
636 }
637 out.append("\n}");
638 }
639
640 out.append("\n]");
641 appendFieldEnd(out);
642
643 out.append("\n}\n");
644 }
645
646 private CharSequence offsetValue(int line, int column) throws IOException {
647 StringBuilder out = new StringBuilder();
648 out.append("{\n");
649 appendFirstField(out, "line", String.valueOf(line));
650 appendField(out, "column", String.valueOf(column));
651 out.append("\n}");
652 return out;
653 }
654
655 private int getSourceId(String sourceName) {
656 if (sourceName != lastSourceFile) {
657 lastSourceFile = sourceName;
658 Integer index = sourceFileMap.get(sourceName);
659 if (index != null) {
660 lastSourceFileIndex = index;
661 } else {
662 lastSourceFileIndex = sourceFileMap.size();
663 sourceFileMap.put(sourceName, lastSourceFileIndex);
664 }
665 }
666 return lastSourceFileIndex;
667 }
668
669 private int getNameId(String symbolName) {
670 int originalNameIndex;
671 Integer index = originalNameMap.get(symbolName);
672 if (index != null) {
673 originalNameIndex = index;
674 } else {
675 originalNameIndex = originalNameMap.size();
676 originalNameMap.put(symbolName, originalNameIndex);
677 }
678 return originalNameIndex;
679 }
680
681 private class LineMapper implements MappingVisitor {
682 // The destination.
683 private final Appendable out;
684
685 private int previousLine = -1;
686 private int previousColumn = 0;
687
688 // Previous values used for storing relative ids.
689 private int previousSourceFileId;
690 private int previousSourceLine;
691 private int previousSourceColumn;
692 private int previousNameId;
693
694 LineMapper(Appendable out) {
695 this.out = out;
696 }
697
698 /**
699 * As each segment is visited write out the appropriate line mapping.
700 */
701 @Override
702 public void visit(Mapping m, int line, int col, int nextLine, int nextCol)
703 throws IOException {
704
705 if (previousLine != line) {
706 previousColumn = 0;
707 }
708
709 if (line != nextLine || col != nextCol) {
710 if (previousLine == line) { // not the first entry for the line
711 out.append(',');
712 }
713 writeEntry(m, col);
714 previousLine = line;
715 previousColumn = col;
716 }
717
718 for (int i = line; i <= nextLine; i++) {
719 if (i == nextLine) {
720 break;
721 }
722
723 closeLine(false);
724 openLine(false);
725 }
726 }
727
728 /**
729 * Writes an entry for the given column (of the generated text) and
730 * associated mapping.
731 * The values are stored as relative to the last seen values for each
732 * field and encoded as Base64VLQs.
733 */
734 void writeEntry(Mapping m, int column) throws IOException {
735 // The relative generated column number
736 Base64VLQ.encode(out, column - previousColumn);
737 previousColumn = column;
738 if (m != null) {
739 // The relative source file id
740 int sourceId = getSourceId(m.sourceFile);
741 Base64VLQ.encode(out, sourceId - previousSourceFileId);
742 previousSourceFileId = sourceId;
743
744 // The relative source file line and column
745 int srcline = m.originalPosition.getLine();
746 int srcColumn = m.originalPosition.getColumn();
747 Base64VLQ.encode(out, srcline - previousSourceLine);
748 previousSourceLine = srcline;
749
750 Base64VLQ.encode(out, srcColumn - previousSourceColumn);
751 previousSourceColumn = srcColumn;
752
753 if (m.originalName != null) {
754 // The relative id for the associated symbol name
755 int nameId = getNameId(m.originalName);
756 Base64VLQ.encode(out, (nameId - previousNameId));
757 previousNameId = nameId;
758 }
759 }
760 }
761
762 // Append the line mapping entries.
763 void appendLineMappings() throws IOException {
764 // Start the first line.
765 openLine(true);
766
767 (new MappingTraversal()).traverse(this);
768
769 // And close the final line.
770 closeLine(true);
771 }
772
773 /**
774 * Begin the entry for a new line.
775 */
776 private void openLine(boolean firstEntry) throws IOException {
777 if (firstEntry) {
778 out.append('\"');
779 }
780 }
781
782 /**
783 * End the entry for a line.
784 */
785 private void closeLine(boolean finalEntry) throws IOException {
786 out.append(';');
787 if (finalEntry) {
788 out.append('\"');
789 }
790 }
791 }
792
793 }