Debian Codegraph @

src/com/google/javascript/jscomp/CodePrinter.java

raw symbols SCIP
1 /*
2 * Copyright 2004 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.base.Preconditions;
20 import com.google.common.base.Throwables;
21 import com.google.debugging.sourcemap.FilePosition;
22 import com.google.javascript.rhino.Node;
23 import com.google.javascript.rhino.Token;
24 import com.google.javascript.rhino.jstype.JSTypeRegistry;
25
26 import java.util.ArrayDeque;
27 import java.util.ArrayList;
28 import java.util.Deque;
29 import java.util.List;
30
31 /**
32 * CodePrinter prints out JS code in either pretty format or compact format.
33 *
34 * @see CodeGenerator
35 */
36 class CodePrinter {
37 // The number of characters after which we insert a line break in the code
38 static final int DEFAULT_LINE_LENGTH_THRESHOLD = 500;
39
40
41 // There are two separate CodeConsumers, one for pretty-printing and
42 // another for compact printing.
43
44 // There are two implementations because the CompactCodePrinter
45 // potentially has a very different implementation to the pretty
46 // version.
47
48 private abstract static class MappedCodePrinter extends CodeConsumer {
49 final private Deque<Mapping> mappings;
50 final private List<Mapping> allMappings;
51 final private boolean createSrcMap;
52 final private SourceMap.DetailLevel sourceMapDetailLevel;
53 protected final StringBuilder code = new StringBuilder(1024);
54 protected final int lineLengthThreshold;
55 protected int lineLength = 0;
56 protected int lineIndex = 0;
57
58 MappedCodePrinter(
59 int lineLengthThreshold,
60 boolean createSrcMap,
61 SourceMap.DetailLevel sourceMapDetailLevel) {
62 Preconditions.checkState(sourceMapDetailLevel != null);
63 this.lineLengthThreshold = lineLengthThreshold <= 0 ? Integer.MAX_VALUE :
64 lineLengthThreshold;
65 this.createSrcMap = createSrcMap;
66 this.sourceMapDetailLevel = sourceMapDetailLevel;
67 this.mappings = createSrcMap ? new ArrayDeque<Mapping>() : null;
68 this.allMappings = createSrcMap ? new ArrayList<Mapping>() : null;
69 }
70
71 /**
72 * Maintains a mapping from a given node to the position
73 * in the source code at which its generated form was
74 * placed. This position is relative only to the current
75 * run of the CodeConsumer and will be normalized
76 * later on by the SourceMap.
77 *
78 * @see SourceMap
79 */
80 private static class Mapping {
81 Node node;
82 FilePosition start;
83 FilePosition end;
84 }
85
86 /**
87 * Starts the source mapping for the given
88 * node at the current position.
89 */
90 @Override
91 void startSourceMapping(Node node) {
92 Preconditions.checkState(sourceMapDetailLevel != null);
93 Preconditions.checkState(node != null);
94 if (createSrcMap
95 && node.getSourceFileName() != null
96 && node.getLineno() > 0
97 && sourceMapDetailLevel.apply(node)) {
98 int line = getCurrentLineIndex();
99 int index = getCurrentCharIndex();
100 Preconditions.checkState(line >= 0);
101 Mapping mapping = new Mapping();
102 mapping.node = node;
103 mapping.start = new FilePosition(line, index);
104 mappings.push(mapping);
105 allMappings.add(mapping);
106 }
107 }
108
109 /**
110 * Finishes the source mapping for the given
111 * node at the current position.
112 */
113 @Override
114 void endSourceMapping(Node node) {
115 if (createSrcMap && !mappings.isEmpty() && mappings.peek().node == node) {
116 Mapping mapping = mappings.pop();
117 int line = getCurrentLineIndex();
118 int index = getCurrentCharIndex();
119 Preconditions.checkState(line >= 0);
120 mapping.end = new FilePosition(line, index);
121 }
122 }
123
124 /**
125 * Generates the source map from the given code consumer,
126 * appending the information it saved to the SourceMap
127 * object given.
128 */
129 void generateSourceMap(SourceMap map){
130 if (createSrcMap) {
131 for (Mapping mapping : allMappings) {
132 map.addMapping(mapping.node, mapping.start, mapping.end);
133 }
134 }
135 }
136
137 /**
138 * Reports to the code consumer that the given line has been cut at the
139 * given position, i.e. a \n has been inserted there. Or that a cut has
140 * been undone, i.e. a previously inserted \n has been removed.
141 * All mappings in the source maps after that position will be renormalized
142 * as needed.
143 */
144 void reportLineCut(int lineIndex, int charIndex, boolean insertion) {
145 if (createSrcMap) {
146 for (Mapping mapping : allMappings) {
147 mapping.start = convertPosition(mapping.start, lineIndex, charIndex,
148 insertion);
149
150 if (mapping.end != null) {
151 mapping.end = convertPosition(mapping.end, lineIndex, charIndex,
152 insertion);
153 }
154 }
155 }
156 }
157
158 /**
159 * Converts the given position by normalizing it against the insertion
160 * or removal of a newline at the given line and character position.
161 *
162 * @param position The existing position before the newline was inserted.
163 * @param lineIndex The index of the line at which the newline was inserted.
164 * @param characterPosition The position on the line at which the newline
165 * was inserted.
166 * @param insertion True if a newline was inserted, false if a newline was
167 * removed.
168 *
169 * @return The normalized position.
170 * @throws IllegalStateException if an attempt to reverse a line cut is
171 * made on a previous line rather than the current line.
172 */
173 private FilePosition convertPosition(FilePosition position, int lineIndex,
174 int characterPosition, boolean insertion) {
175 int originalLine = position.getLine();
176 int originalChar = position.getColumn();
177 if (insertion) {
178 if (originalLine == lineIndex && originalChar >= characterPosition) {
179 // If the position falls on the line itself, then normalize it
180 // if it falls at or after the place the newline was inserted.
181 return new FilePosition(
182 originalLine + 1, originalChar - characterPosition);
183 } else {
184 return position;
185 }
186 } else {
187 if (originalLine == lineIndex) {
188 return new FilePosition(
189 originalLine - 1, originalChar + characterPosition);
190 } else if (originalLine > lineIndex) {
191 // Not supported, can only undo a cut on the most recent line. To
192 // do this on a previous lines would require reevaluating the cut
193 // positions on all subsequent lines.
194 throw new IllegalStateException(
195 "Cannot undo line cut on a previous line.");
196 } else {
197 return position;
198 }
199 }
200 }
201
202 public String getCode() {
203 return code.toString();
204 }
205
206 @Override
207 char getLastChar() {
208 return (code.length() > 0) ? code.charAt(code.length() - 1) : '\0';
209 }
210
211 protected final int getCurrentCharIndex() {
212 return lineLength;
213 }
214
215 protected final int getCurrentLineIndex() {
216 return lineIndex;
217 }
218 }
219
220 static class PrettyCodePrinter
221 extends MappedCodePrinter {
222 // The number of characters after which we insert a line break in the code
223 static final String INDENT = " ";
224
225 private int indent = 0;
226
227 /**
228 * @param lineLengthThreshold The length of a line after which we force
229 * a newline when possible.
230 * @param createSourceMap Whether to generate source map data.
231 * @param sourceMapDetailLevel A filter to control which nodes get mapped
232 * into the source map.
233 */
234 private PrettyCodePrinter(
235 int lineLengthThreshold,
236 boolean createSourceMap,
237 SourceMap.DetailLevel sourceMapDetailLevel) {
238 super(lineLengthThreshold, createSourceMap, sourceMapDetailLevel);
239 }
240
241 /**
242 * Appends a string to the code, keeping track of the current line length.
243 */
244 @Override
245 void append(String str) {
246 // For pretty printing: indent at the beginning of the line
247 if (lineLength == 0) {
248 for (int i = 0; i < indent; i++) {
249 code.append(INDENT);
250 lineLength += INDENT.length();
251 }
252 }
253 code.append(str);
254 lineLength += str.length();
255 }
256
257 /**
258 * Adds a newline to the code, resetting the line length and handling
259 * indenting for pretty printing.
260 */
261 @Override
262 void startNewLine() {
263 if (lineLength > 0) {
264 code.append('\n');
265 lineIndex++;
266 lineLength = 0;
267 }
268 }
269
270 @Override
271 void maybeLineBreak() {
272 maybeCutLine();
273 }
274
275 /**
276 * This may start a new line if the current line is longer than the line
277 * length threshold.
278 */
279 @Override
280 void maybeCutLine() {
281 if (lineLength > lineLengthThreshold) {
282 startNewLine();
283 }
284 }
285
286 @Override
287 void endLine() {
288 startNewLine();
289 }
290
291 @Override
292 void appendBlockStart() {
293 append(" {");
294 indent++;
295 }
296
297 @Override
298 void appendBlockEnd() {
299 endLine();
300 indent--;
301 append("}");
302 }
303
304 @Override
305 void listSeparator() {
306 add(", ");
307 maybeLineBreak();
308 }
309
310 @Override
311 void endFunction(boolean statementContext) {
312 super.endFunction(statementContext);
313 if (statementContext) {
314 startNewLine();
315 }
316 }
317
318 @Override
319 void beginCaseBody() {
320 super.beginCaseBody();
321 indent++;
322 endLine();
323 }
324
325 @Override
326 void endCaseBody() {
327 super.endCaseBody();
328 indent--;
329 endStatement();
330 }
331
332 @Override
333 void appendOp(String op, boolean binOp) {
334 if (binOp) {
335 if (getLastChar() != ' ' && op.charAt(0) != ',') {
336 append(" ");
337 }
338 append(op);
339 append(" ");
340 } else {
341 append(op);
342 }
343 }
344
345 /**
346 * If the body of a for loop or the then clause of an if statement has
347 * a single statement, should it be wrapped in a block?
348 * {@inheritDoc}
349 */
350 @Override
351 boolean shouldPreserveExtraBlocks() {
352 // When pretty-printing, always place the statement in its own block
353 // so it is printed on a separate line. This allows breakpoints to be
354 // placed on the statement.
355 return true;
356 }
357
358 /**
359 * @return The TRY node for the specified CATCH node.
360 */
361 private Node getTryForCatch(Node n) {
362 return n.getParent().getParent();
363 }
364
365 /**
366 * @return Whether the a line break should be added after the specified
367 * BLOCK.
368 */
369 @Override
370 boolean breakAfterBlockFor(Node n, boolean isStatementContext) {
371 Preconditions.checkState(n.isBlock());
372 Node parent = n.getParent();
373 if (parent != null) {
374 int type = parent.getType();
375 switch (type) {
376 case Token.DO:
377 // Don't break before 'while' in DO-WHILE statements.
378 return false;
379 case Token.FUNCTION:
380 // FUNCTIONs are handled separately, don't break here.
381 return false;
382 case Token.TRY:
383 // Don't break before catch
384 return n != parent.getFirstChild();
385 case Token.CATCH:
386 // Don't break before finally
387 return !NodeUtil.hasFinally(getTryForCatch(parent));
388 case Token.IF:
389 // Don't break before else
390 return n == parent.getLastChild();
391 }
392 }
393 return true;
394 }
395
396 @Override
397 void endFile() {
398 maybeEndStatement();
399 }
400 }
401
402
403 static class CompactCodePrinter
404 extends MappedCodePrinter {
405
406 // The CompactCodePrinter tries to emit just enough newlines to stop there
407 // being lines longer than the threshold. Since the output is going to be
408 // gzipped, it makes sense to try to make the newlines appear in similar
409 // contexts so that gzip can encode them for 'free'.
410 //
411 // This version tries to break the lines at 'preferred' places, which are
412 // between the top-level forms. This works because top-level forms tend to
413 // be more uniform than arbitrary legal contexts. Better compression would
414 // probably require explicit modeling of the gzip algorithm.
415
416 private final boolean lineBreak;
417 private final boolean preferLineBreakAtEndOfFile;
418 private int lineStartPosition = 0;
419 private int preferredBreakPosition = 0;
420 private int prevCutPosition = 0;
421 private int prevLineStartPosition = 0;
422
423 /**
424 * @param lineBreak break the lines a bit more aggressively
425 * @param lineLengthThreshold The length of a line after which we force
426 * a newline when possible.
427 * @param createSrcMap Whether to gather source position
428 * mapping information when printing.
429 * @param sourceMapDetailLevel A filter to control which nodes get mapped into
430 * the source map.
431 */
432 private CompactCodePrinter(boolean lineBreak,
433 boolean preferLineBreakAtEndOfFile, int lineLengthThreshold,
434 boolean createSrcMap, SourceMap.DetailLevel sourceMapDetailLevel) {
435 super(lineLengthThreshold, createSrcMap, sourceMapDetailLevel);
436 this.lineBreak = lineBreak;
437 this.preferLineBreakAtEndOfFile = preferLineBreakAtEndOfFile;
438 }
439
440 /**
441 * Appends a string to the code, keeping track of the current line length.
442 */
443 @Override
444 void append(String str) {
445 code.append(str);
446 lineLength += str.length();
447 }
448
449 /**
450 * Adds a newline to the code, resetting the line length.
451 */
452 @Override
453 void startNewLine() {
454 if (lineLength > 0) {
455 prevCutPosition = code.length();
456 prevLineStartPosition = lineStartPosition;
457 code.append('\n');
458 lineLength = 0;
459 lineIndex++;
460 lineStartPosition = code.length();
461 }
462 }
463
464 @Override
465 void maybeLineBreak() {
466 if (lineBreak) {
467 if (sawFunction) {
468 startNewLine();
469 sawFunction = false;
470 }
471 }
472
473 // Since we are at a legal line break, can we upgrade the
474 // preferred break position? We prefer to break after a
475 // semicolon rather than before it.
476 int len = code.length();
477 if (preferredBreakPosition == len - 1) {
478 char ch = code.charAt(len - 1);
479 if (ch == ';') {
480 preferredBreakPosition = len;
481 }
482 }
483 maybeCutLine();
484 }
485
486 /**
487 * This may start a new line if the current line is longer than the line
488 * length threshold.
489 */
490 @Override
491 void maybeCutLine() {
492 if (lineLength > lineLengthThreshold) {
493 // Use the preferred position provided it will break the line.
494 if (preferredBreakPosition > lineStartPosition &&
495 preferredBreakPosition < lineStartPosition + lineLength) {
496 int position = preferredBreakPosition;
497 code.insert(position, '\n');
498 prevCutPosition = position;
499 reportLineCut(lineIndex, position - lineStartPosition, true);
500 lineIndex++;
501 lineLength -= (position - lineStartPosition);
502 lineStartPosition = position + 1;
503 } else {
504 startNewLine();
505 }
506 }
507 }
508
509 @Override
510 void notePreferredLineBreak() {
511 preferredBreakPosition = code.length();
512 }
513
514 @Override
515 void endFile() {
516 super.endFile();
517 if (!preferLineBreakAtEndOfFile) {
518 return;
519 }
520 if (lineLength > lineLengthThreshold / 2) {
521 // Add an extra break at end of file.
522 append(";");
523 startNewLine();
524 } else if (prevCutPosition > 0) {
525 // Shift the previous break to end of file by replacing it with a
526 // <space> and adding a new break at end of file. Adding the space
527 // handles cases like instanceof\nfoo. (it would be nice to avoid this)
528 code.setCharAt(prevCutPosition, ' ');
529 lineStartPosition = prevLineStartPosition;
530 lineLength = code.length() - lineStartPosition;
531 reportLineCut(lineIndex, prevCutPosition + 1, false);
532 lineIndex--;
533 prevCutPosition = 0;
534 prevLineStartPosition = 0;
535 append(";");
536 startNewLine();
537 } else {
538 // A small file with no line breaks. We do nothing in this case to
539 // avoid excessive line breaks. It's not ideal if a lot of these pile
540 // up, but that is reasonably unlikely.
541 }
542 }
543
544 }
545
546 static class Builder {
547 private final Node root;
548 private CompilerOptions options = new CompilerOptions();
549 private boolean outputTypes = false;
550 private SourceMap sourceMap = null;
551 private boolean tagAsStrict;
552 private JSTypeRegistry registry;
553
554 /**
555 * Sets the root node from which to generate the source code.
556 * @param node The root node.
557 */
558 Builder(Node node) {
559 root = node;
560 }
561
562 /**
563 * Sets the output options from compiler options.
564 */
565 Builder setCompilerOptions(CompilerOptions options) {
566 try {
567 this.options = (CompilerOptions) options.clone();
568 } catch (CloneNotSupportedException e) {
569 throw Throwables.propagate(e);
570 }
571 return this;
572 }
573
574 Builder setTypeRegistry(JSTypeRegistry registry) {
575 this.registry = registry;
576 return this;
577 }
578
579 /**
580 * Sets whether pretty printing should be used.
581 * @param prettyPrint If true, pretty printing will be used.
582 */
583 Builder setPrettyPrint(boolean prettyPrint) {
584 options.prettyPrint = prettyPrint;
585 return this;
586 }
587
588 /**
589 * Sets whether line breaking should be done automatically.
590 * @param lineBreak If true, line breaking is done automatically.
591 */
592 Builder setLineBreak(boolean lineBreak) {
593 options.lineBreak = lineBreak;
594 return this;
595 }
596
597 /**
598 * Sets whether to output closure-style type annotations.
599 * @param outputTypes If true, outputs closure-style type annotations.
600 */
601 Builder setOutputTypes(boolean outputTypes) {
602 this.outputTypes = outputTypes;
603 return this;
604 }
605
606 /**
607 * Sets the source map to which to write the metadata about
608 * the generated source code.
609 *
610 * @param sourceMap The source map.
611 */
612 Builder setSourceMap(SourceMap sourceMap) {
613 this.sourceMap = sourceMap;
614 return this;
615 }
616
617 /**
618 * Set whether the output should be tags as ECMASCRIPT 5 Strict.
619 */
620 Builder setTagAsStrict(boolean tagAsStrict) {
621 this.tagAsStrict = tagAsStrict;
622 return this;
623 }
624
625 /**
626 * Generates the source code and returns it.
627 */
628 String build() {
629 if (root == null) {
630 throw new IllegalStateException(
631 "Cannot build without root node being specified");
632 }
633
634 Format outputFormat = outputTypes
635 ? Format.TYPED
636 : options.prettyPrint
637 ? Format.PRETTY
638 : Format.COMPACT;
639
640 return toSource(root, outputFormat, options, registry,
641 sourceMap, tagAsStrict);
642 }
643 }
644
645 enum Format {
646 COMPACT,
647 PRETTY,
648 TYPED
649 }
650
651 /**
652 * Converts a tree to JS code
653 */
654 private static String toSource(Node root, Format outputFormat,
655 CompilerOptions options, JSTypeRegistry registry,
656 SourceMap sourceMap, boolean tagAsStrict) {
657 Preconditions.checkState(options.sourceMapDetailLevel != null);
658
659 boolean createSourceMap = (sourceMap != null);
660 MappedCodePrinter mcp =
661 outputFormat == Format.COMPACT
662 ? new CompactCodePrinter(
663 options.lineBreak,
664 options.preferLineBreakAtEndOfFile,
665 options.lineLengthThreshold,
666 createSourceMap,
667 options.sourceMapDetailLevel)
668 : new PrettyCodePrinter(
669 options.lineLengthThreshold,
670 createSourceMap,
671 options.sourceMapDetailLevel);
672 CodeGenerator cg =
673 outputFormat == Format.TYPED
674 ? new TypedCodeGenerator(mcp, options, registry)
675 : new CodeGenerator(mcp, options);
676
677 if (tagAsStrict) {
678 cg.tagAsStrict();
679 }
680
681 cg.add(root);
682 mcp.endFile();
683
684 String code = mcp.getCode();
685
686 if (createSourceMap) {
687 mcp.generateSourceMap(sourceMap);
688 }
689
690 return code;
691 }
692 }