Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2008 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.javascript.rhino.Node;
20
21 /**
22 * For use with CodeGenerator to determine the cost of generated code.
23 *
24 * @see CodeGenerator
25 * @see CodePrinter
26 */
27 class InlineCostEstimator {
28 // For now simply assume identifiers are 2 characters.
29 private static final String ESTIMATED_IDENTIFIER = "ab";
30 static final int ESTIMATED_IDENTIFIER_COST = ESTIMATED_IDENTIFIER.length();
31
32 private InlineCostEstimator() {
33 }
34
35 /**
36 * Determines the size of the JS code.
37 */
38 static int getCost(Node root) {
39 return getCost(root, Integer.MAX_VALUE);
40 }
41
42 /**
43 * Determines the estimated size of the JS snippet represented by the node.
44 */
45 static int getCost(Node root, int costThreshhold) {
46 CompiledSizeEstimator estimator = new CompiledSizeEstimator(costThreshhold);
47 estimator.add(root);
48 return estimator.getCost();
49 }
50
51 /**
52 * Code consumer that estimates compiled size by assuming names are
53 * shortened and all whitespace is stripped.
54 */
55 private static class CompiledSizeEstimator extends CodeConsumer {
56 private int maxCost;
57 private int cost = 0;
58 private char last = '\0';
59 private boolean continueProcessing = true;
60
61 CompiledSizeEstimator(int costThreshhold) {
62 this.maxCost = costThreshhold;
63 }
64
65 void add(Node root) {
66 CodeGenerator cg = CodeGenerator.forCostEstimation(this);
67 cg.add(root);
68 }
69
70 int getCost() {
71 return cost;
72 }
73
74 @Override
75 boolean continueProcessing() {
76 return continueProcessing;
77 }
78
79 @Override
80 char getLastChar() {
81 return last;
82 }
83
84 @Override
85 void append(String str){
86 last = str.charAt(str.length() - 1);
87 cost += str.length();
88 if (maxCost <= cost) {
89 continueProcessing = false;
90 }
91 }
92
93 @Override
94 void addIdentifier(String identifier) {
95 add(ESTIMATED_IDENTIFIER);
96 }
97
98 /**
99 * Constants (true, false, null) are considered basically free,
100 * because it's likely that they will get folded when we're done.
101 */
102 @Override
103 void addConstant(String newcode) {
104 add("0");
105 }
106 }
107 }