Debian Codegraph @

src/com/google/debugging/sourcemap/SourceMapGeneratorV1.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.Lists;
21
22 import java.io.IOException;
23 import java.util.ArrayDeque;
24 import java.util.Deque;
25 import java.util.List;
26
27 import javax.annotation.Nullable;
28
29 /**
30 * Collects information mapping the generated (compiled) source back to
31 * its original source for debugging purposes.
32 *
33 */
34 public class SourceMapGeneratorV1 implements SourceMapGenerator {
35
36 private final static int UNMAPPED = -1;
37
38
39 /**
40 * A mapping from a given position in an input source file to a given position
41 * in the generated code.
42 */
43 static class Mapping {
44 /**
45 * A unique ID for this mapping for record keeping purposes.
46 */
47 int id = UNMAPPED;
48
49 /**
50 * The input source file.
51 */
52 String sourceFile;
53
54 /**
55 * The position of the code in the input source file. Both
56 * the line number and the character index are indexed by
57 * 1 for legacy reasons via the Rhino Node class.
58 */
59 FilePosition originalPosition;
60
61 /**
62 * The starting position of the code in the generated source
63 * file which this mapping represents. Indexed by 0.
64 */
65 FilePosition startPosition;
66
67 /**
68 * The ending position of the code in the generated source
69 * file which this mapping represents. Indexed by 0.
70 */
71 FilePosition endPosition;
72
73 /**
74 * The original name of the token found at the position
75 * represented by this mapping (if any).
76 */
77 String originalName;
78
79 /**
80 * Whether the mapping is actually used by the source map.
81 */
82 boolean used = false;
83 }
84
85 private class MappingWriter {
86 /**
87 * Cache of escaped source file name.
88 */
89 private String lastSourceFile = null;
90 private String lastSourceFileEscaped = null;
91 private int lastLine = 0;
92 private String lastLineString = String.valueOf(0);
93
94 /**
95 * Appends the mapping to the given buffer.
96 */
97 private void appendMappingTo(
98 Mapping m, Appendable out) throws IOException {
99 out.append("[");
100
101 String sourceFile = m.sourceFile;
102 // The source file rarely changes, so cache the escaped string.
103 String escapedSourceFile;
104 if (lastSourceFile != sourceFile) { // yes, s1 != s2, not !s1.equals(s2)
105 lastSourceFile = sourceFile;
106 lastSourceFileEscaped = escapeString(sourceFile);
107 }
108 escapedSourceFile = lastSourceFileEscaped;
109
110 out.append(escapedSourceFile);
111 out.append(",");
112
113 int line = m.originalPosition.getLine();
114 if (line != lastLine) {
115 lastLineString = String.valueOf(line);
116 }
117 String lineValue = lastLineString;
118
119 out.append(lineValue);
120
121 out.append(",");
122 out.append(String.valueOf(
123 m.originalPosition.getColumn()));
124
125 if (m.originalName != null) {
126 out.append(",");
127 out.append(escapeString(m.originalName));
128 }
129
130 out.append("]\n");
131 }
132
133 /**
134 * Add used mappings to the supplied Appendable.
135 */
136 void appendMappings(Appendable out) throws IOException {
137 for (Mapping m : mappings) {
138 if (m.used) {
139 appendMappingTo(m, out);
140 }
141 }
142 }
143 }
144
145 /**
146 * A pre-order traversal ordered list of mappings stored in this map.
147 */
148 private List<Mapping> mappings = Lists.newArrayList();
149
150 /**
151 * For validation store the start of the last mapping added.
152 */
153 private Mapping lastMapping;
154
155 /**
156 * The position that the current source map is offset in the
157 * buffer being used to generated the compiled source file.
158 */
159 private FilePosition offsetPosition = new FilePosition(0, 0);
160
161 /**
162 * The position that the current source map is offset in the
163 * generated the compiled source file by the addition of a
164 * an output wrapper prefix.
165 */
166 private FilePosition prefixPosition = new FilePosition(0, 0);
167
168 /**
169 * Escapes the given string for JSON.
170 */
171 private static String escapeString(String value) {
172 return Util.escapeString(value);
173 }
174
175 /**
176 * Adds a mapping for the given node. Mappings must be added in order.
177 * @param startPosition The position on the starting line
178 * @param endPosition The position on the ending line.
179 */
180 @Override
181 public void addMapping(
182 String sourceName, @Nullable String symbolName,
183 FilePosition sourceStartPosition,
184 FilePosition startPosition, FilePosition endPosition) {
185
186 // Don't bother if there is not sufficient information to be useful.
187 if (sourceName == null || sourceStartPosition.getLine() < 0) {
188 return;
189 }
190
191 // Create the new mapping.
192 Mapping mapping = new Mapping();
193 mapping.sourceFile = sourceName;
194 mapping.originalPosition = sourceStartPosition;
195 mapping.originalName = symbolName; // may be null
196
197 // NOTE: When multiple outputs are concatenated together, the positions in
198 // the mapping are relative to offsetPosition.
199 if (offsetPosition.getLine() == 0
200 && offsetPosition.getColumn() == 0) {
201 mapping.startPosition = startPosition;
202 mapping.endPosition = endPosition;
203 } else {
204 // If the mapping is found on the first line, we need to offset
205 // its character position by the number of characters found on
206 // the *last* line of the source file to which the code is
207 // being generated.
208 int offsetLine = offsetPosition.getLine();
209 int startOffsetPosition = offsetPosition.getColumn();
210 int endOffsetPosition = offsetPosition.getColumn();
211
212 if (startPosition.getLine() > 0) {
213 startOffsetPosition = 0;
214 }
215
216 if (endPosition.getLine() > 0) {
217 endOffsetPosition = 0;
218 }
219
220 mapping.startPosition =
221 new FilePosition(startPosition.getLine() + offsetLine,
222 startPosition.getColumn() + startOffsetPosition);
223
224 mapping.endPosition =
225 new FilePosition(endPosition.getLine() + offsetLine,
226 endPosition.getColumn() + endOffsetPosition);
227 }
228
229 // Validate the mappings are in a proper order.
230 if (lastMapping != null) {
231 int lastLine = lastMapping.startPosition.getLine();
232 int lastColumn = lastMapping.startPosition.getColumn();
233 int nextLine = mapping.startPosition.getLine();
234 int nextColumn = mapping.startPosition.getColumn();
235 Preconditions.checkState(nextLine > lastLine
236 || (nextLine == lastLine && nextColumn >= lastColumn),
237 "Incorrect source mappings order, previous : (%s,%s)\n"
238 + "new : (%s,%s)\nnode : %s",
239 lastLine, lastColumn, nextLine, nextColumn);
240 }
241
242 lastMapping = mapping;
243 mappings.add(mapping);
244 }
245
246 /**
247 * Sets the prefix used for wrapping the generated source file before
248 * it is output. This ensures that the source map is adjusted as
249 * needed.
250 *
251 * @param prefix The prefix that is added before the generated source code.
252 */
253 @Override
254 public void setWrapperPrefix(String prefix) {
255 // Determine the current line and character position.
256 int prefixLine = 0;
257 int prefixIndex = 0;
258
259 for (int i = 0; i < prefix.length(); ++i) {
260 if (prefix.charAt(i) == '\n') {
261 prefixLine++;
262 prefixIndex = 0;
263 } else {
264 prefixIndex++;
265 }
266 }
267
268 prefixPosition = new FilePosition(prefixLine, prefixIndex);
269 }
270
271 /**
272 * Sets the source code that exists in the buffer to which the
273 * generated code is being generated. This ensures that the source map
274 * accurately reflects the fact that the source is being appended to
275 * an existing buffer and as such, does not start at line 0, position 0
276 * but rather some other line and position.
277 *
278 * @param offsetLine The index of the current line being printed.
279 * @param offsetIndex The column index of the current character being printed.
280 */
281 @Override
282 public void setStartingPosition(int offsetLine, int offsetIndex) {
283 Preconditions.checkState(offsetLine >= 0);
284 Preconditions.checkState(offsetIndex >= 0);
285 offsetPosition = new FilePosition(offsetLine, offsetIndex);
286 }
287
288 /**
289 * Resets the source map for reuse for the generation of a new source file.
290 */
291 @Override
292 public void reset() {
293 mappings = Lists.newArrayList();
294 lastMapping = null;
295 offsetPosition = new FilePosition(0, 0);
296 prefixPosition = new FilePosition(0, 0);
297 }
298
299 /**
300 * Appends the source map in LavaBug format to the given buffer.
301 *
302 * @param out The stream to which the map will be appended.
303 * @param name The name of the generated source file that this source map
304 * represents.
305 */
306 @Override
307 public void appendTo(Appendable out, String name) throws IOException {
308 // Write the mappings out to the file. The format of the generated
309 // source map is three sections, each delimited by a magic comment.
310 //
311 // The first section contains an array for each line of the generated
312 // code, where each element in the array is the ID of the mapping which
313 // best represents the index-th character found on that line of the
314 // generated source code.
315 //
316 // The second section contains an array per generated line. Unused.
317 //
318 // The third and final section contains an array per line, each of which
319 // represents a mapping with a unique ID. The mappings are added in order.
320 // The array itself contains a tuple representing
321 // ['source file', line, col (, 'original name')]
322 //
323 // Example for 2 lines of generated code (with line numbers added for
324 // readability):
325 //
326 // 1) /** Begin line maps. **/{ "count": 2 }
327 // 2) [0,0,0,0,0,0,1,1,1,1,2]
328 // 3) [2,2,2,2,2,2,3,4,4,4,4,4]
329 // 4) /** Begin file information. **/
330 // 5) []
331 // 6) []
332 // 7) /** Begin mapping definitions. **/
333 // 8) ["a.js", 1, 34]
334 // 9) ["a.js", 5, 2]
335 // 10) ["b.js", 1, 3, "event"]
336 // 11) ["c.js", 1, 4]
337 // 12) ["d.js", 3, 78, "foo"]
338
339 int maxLine = prepMappings();
340
341 // Add the line character maps.
342 out.append("/** Begin line maps. **/{ \"file\" : ");
343 out.append(escapeString(name));
344 out.append(", \"count\": ");
345 out.append(String.valueOf(maxLine + 1));
346 out.append(" }\n");
347 (new LineMapper(out)).appendLineMappings();
348
349 // Add the source file maps.
350 out.append("/** Begin file information. **/\n");
351
352 // This section is unused but we need one entry per line to
353 // prevent changing the format.
354 for (int i = 0; i <= maxLine; ++i) {
355 out.append("[]\n");
356 }
357
358 // Add the mappings themselves.
359 out.append("/** Begin mapping definitions. **/\n");
360
361 (new MappingWriter()).appendMappings(out);
362 }
363
364 /**
365 * Assigns sequential ids to used mappings, and returns the last line mapped.
366 */
367 private int prepMappings() throws IOException {
368 // Mark any unused mappings.
369 (new MappingTraversal()).traverse(new UsedMappingCheck());
370
371 // Renumber used mappings and keep track of the last line.
372 int id = 0;
373 int maxLine = 0;
374 for (Mapping m : mappings) {
375 if (m.used) {
376 m.id = id++;
377 int endPositionLine = m.endPosition.getLine();
378 maxLine = Math.max(maxLine, endPositionLine);
379 }
380 }
381
382 // Adjust for the prefix.
383 return maxLine + prefixPosition.getLine();
384 }
385
386 private class LineMapper implements MappingVisitor {
387 // The destination.
388 private final Appendable out;
389
390 // Whether the current line has had a value written yet.
391 private boolean firstChar = true;
392
393 private final static String UNMAPPED_STRING = "-1";
394
395 private int lastId = UNMAPPED;
396 private String lastIdString = UNMAPPED_STRING;
397
398 LineMapper(Appendable out) {
399 this.out = out;
400 }
401
402 /**
403 * As each segment is visited write out the appropriate line mapping.
404 */
405 @Override
406 public void visit(Mapping m, int line, int col, int nextLine, int nextCol)
407 throws IOException {
408
409 int id = (m != null) ? m.id : UNMAPPED;
410 if (lastId != id) {
411 // Prevent the creation of unnecessary temporary stings for often
412 // repeated values.
413 lastIdString = (id == UNMAPPED) ? UNMAPPED_STRING : String.valueOf(id);
414 lastId = id;
415 }
416 String idString = lastIdString;
417
418 for (int i = line; i <= nextLine; i++) {
419 if (i == nextLine) {
420 for (int j = col; j < nextCol; j++) {
421 addCharEntry(idString);
422 }
423 break;
424 }
425
426 closeLine();
427 openLine();
428
429 // Set the starting location for the next line.
430 col = 0;
431 }
432 }
433
434 // Append the line mapping entries.
435 void appendLineMappings() throws IOException {
436 // Start the first line.
437 openLine();
438
439 (new MappingTraversal()).traverse(this);
440
441 // And close the final line.
442 closeLine();
443 }
444
445 /**
446 * Begin the entry for a new line.
447 */
448 private void openLine() throws IOException {
449 if (out != null) {
450 out.append("[");
451 this.firstChar = true;
452 }
453 }
454
455 /**
456 * End the entry for a line.
457 */
458 private void closeLine() throws IOException {
459 if (out != null) {
460 out.append("]\n");
461 }
462 }
463
464 /**
465 * Add a new char position entry.
466 * @param id The mapping id to record.
467 */
468 private void addCharEntry(String id) throws IOException {
469 if (out != null) {
470 if (firstChar) {
471 firstChar = false;
472 } else {
473 out.append(",");
474 }
475 out.append(id);
476 }
477 }
478 }
479
480 /**
481 * Mark any visited mapping as "used".
482 */
483 private class UsedMappingCheck implements MappingVisitor {
484 /**
485 * @throws IOException
486 */
487 @Override
488 public void visit(Mapping m, int line, int col, int nextLine, int nextCol)
489 throws IOException {
490 if (m != null) {
491 m.used = true;
492 }
493 }
494 }
495
496 private interface MappingVisitor {
497 /**
498 * @param m The mapping for the current code segment. null if the segment
499 * is unmapped.
500 * @param line The starting line for this code segment.
501 * @param col The starting column for this code segment.
502 * @param endLine The ending line
503 * @param endCol The ending column
504 * @throws IOException
505 */
506 void visit(Mapping m, int line, int col, int endLine, int endCol)
507 throws IOException;
508 }
509
510 /**
511 * Walk the mappings and visit each segment of the mappings, unmapped
512 * segments are visited with a null mapping, unused mapping are not visited.
513 */
514 private class MappingTraversal {
515 // The last line and column written
516 private int line;
517 private int col;
518
519 MappingTraversal() {
520 }
521
522 // Append the line mapping entries.
523 void traverse(MappingVisitor v) throws IOException {
524 // The mapping list is ordered as a pre-order traversal. The mapping
525 // positions give us enough information to rebuild the stack and this
526 // allows the building of the source map in O(n) time.
527 Deque<Mapping> stack = new ArrayDeque<Mapping>();
528 for (Mapping m : mappings) {
529 // Find the closest ancestor of the current mapping:
530 // An overlapping mapping is an ancestor of the current mapping, any
531 // non-overlapping mappings are siblings (or cousins) and must be
532 // closed in the reverse order of when they encountered.
533 while (!stack.isEmpty() && !isOverlapped(stack.peek(), m)) {
534 Mapping previous = stack.pop();
535 maybeVisit(v, previous);
536 }
537
538 // Any gaps between the current line position and the start of the
539 // current mapping belong to the parent.
540 Mapping parent = stack.peek();
541 maybeVisitParent(v, parent, m);
542
543 stack.push(m);
544 }
545
546 // There are no more children to be had, simply close the remaining
547 // mappings in the reverse order of when they encountered.
548 while (!stack.isEmpty()) {
549 Mapping m = stack.pop();
550 maybeVisit(v, m);
551 }
552 }
553
554 /**
555 * @return The line adjusted for the prefix position.
556 */
557 private int getAdjustedLine(FilePosition p) {
558 return p.getLine() + prefixPosition.getLine();
559 }
560
561 /**
562 * @return The column adjusted for the prefix position.
563 */
564 private int getAdjustedCol(FilePosition p) {
565 int rawLine = p.getLine();
566 int rawCol = p.getColumn();
567 // Only the first line needs the character position adjusted.
568 return (rawLine != 0)
569 ? rawCol : rawCol + prefixPosition.getColumn();
570 }
571
572 /**
573 * @return Whether m1 ends before m2 starts.
574 */
575 private boolean isOverlapped(Mapping m1, Mapping m2) {
576 // No need to use adjusted values here, relative positions are sufficient.
577 int l1 = m1.endPosition.getLine();
578 int l2 = m2.startPosition.getLine();
579 int c1 = m1.endPosition.getColumn();
580 int c2 = m2.startPosition.getColumn();
581
582 return (l1 == l2 && c1 >= c2) || l1 > l2;
583 }
584
585 /**
586 * Write any needed entries from the current position to the end of the
587 * provided mapping.
588 */
589 private void maybeVisit(MappingVisitor v, Mapping m) throws IOException {
590 int nextLine = getAdjustedLine(m.endPosition);
591 int nextCol = getAdjustedCol(m.endPosition);
592 // If this anything remaining in this mapping beyond the
593 // current line and column position, write it out now.
594 if (line < nextLine || (line == nextLine && col < nextCol)) {
595 visit(v, m, nextLine, nextCol);
596 }
597 }
598
599 /**
600 * Write any needed entries to complete the provided mapping.
601 */
602 private void maybeVisitParent(MappingVisitor v, Mapping parent, Mapping m)
603 throws IOException {
604 int nextLine = getAdjustedLine(m.startPosition);
605 int nextCol = getAdjustedCol(m.startPosition);
606 // If the previous value is null, no mapping exists.
607 Preconditions.checkState(line < nextLine || col <= nextCol);
608 if (line < nextLine || (line == nextLine && col < nextCol)) {
609 visit(v, parent, nextLine, nextCol);
610 }
611 }
612
613 /**
614 * Write any entries needed between the current position the next position
615 * and update the current position.
616 */
617 private void visit(MappingVisitor v, Mapping m,
618 int nextLine, int nextCol)
619 throws IOException {
620 Preconditions.checkState(line <= nextLine);
621 Preconditions.checkState(line < nextLine || col < nextCol);
622
623 if (line == nextLine && col == nextCol) {
624 // Nothing to do.
625 Preconditions.checkState(false);
626 return;
627 }
628
629 v.visit(m, line, col, nextLine, nextCol);
630
631 line = nextLine;
632 col = nextCol;
633 }
634 }
635
636 @Override
637 public void validate(boolean validate) {
638 // No additional validation to do.
639 }
640
641 @Override
642 public void appendIndexMapTo(
643 Appendable out, String name, List<SourceMapSection> appSections) {
644 throw new UnsupportedOperationException();
645 }
646 }