Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2005 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.annotations.VisibleForTesting;
20 import com.google.common.base.Charsets;
21 import com.google.common.collect.ImmutableMap;
22 import com.google.common.io.ByteStreams;
23 import com.google.common.io.CharStreams;
24 import com.google.common.io.Files;
25
26 import java.io.*;
27 import java.text.*;
28 import java.util.*;
29
30 /**
31 * Stores the mapping from original variable name to new variable names.
32 * @see RenameVars
33 */
34 public class VariableMap {
35
36 /** Maps original source name to new name */
37 private final ImmutableMap<String, String> map;
38
39 /** Maps new name to source name, lazily initialized */
40 private ImmutableMap<String, String> reverseMap = null;
41
42 private static final char SEPARATOR = ':';
43
44 VariableMap(Map<String, String> map) {
45 this.map = ImmutableMap.copyOf(map);
46 }
47
48 /**
49 * Given an original variable name, look up new name, may return null
50 * if it's not found.
51 */
52 public String lookupNewName(String sourceName) {
53 return map.get(sourceName);
54 }
55
56 /**
57 * Given a new variable name, lookup the source name, may return null
58 * if it's not found.
59 */
60 public String lookupSourceName(String newName) {
61 initReverseMap();
62 return reverseMap.get(newName);
63 }
64
65 /**
66 * Initializes the reverse map.
67 */
68 private synchronized void initReverseMap() {
69 if (reverseMap == null) {
70 ImmutableMap.Builder<String, String> rm = ImmutableMap.builder();
71 for (Map.Entry<String, String> entry : map.entrySet()) {
72 rm.put(entry.getValue(), entry.getKey());
73 }
74 reverseMap = rm.build();
75 }
76 }
77
78 /**
79 * Returns an unmodifiable mapping from original names to new names.
80 */
81 public Map<String, String> getOriginalNameToNewNameMap() {
82 return map;
83 }
84
85 /**
86 * Returns an unmodifiable mapping from new names to original names.
87 */
88 public Map<String, String> getNewNameToOriginalNameMap() {
89 initReverseMap();
90 return reverseMap;
91 }
92
93 /**
94 * Saves the variable map to a file.
95 */
96 public void save(String filename) throws IOException {
97 Files.write(toBytes(), new File(filename));
98 }
99
100 /**
101 * Reads the variable map from a file written via {@link #save(String)}.
102 */
103 public static VariableMap load(String filename) throws IOException {
104 try {
105 return fromBytes(Files.toByteArray(new File(filename)));
106 } catch (ParseException e) {
107 // Wrap parse exception for backwards compatibility.
108 throw new IOException(e);
109 }
110 }
111
112 /**
113 * Serializes the variable map to a byte array.
114 */
115 public byte[] toBytes() {
116 ByteArrayOutputStream baos = new ByteArrayOutputStream();
117 Writer writer = new OutputStreamWriter(baos, Charsets.UTF_8);
118 try {
119 for (Map.Entry<String, String> entry : map.entrySet()) {
120 writer.write(escape(entry.getKey()));
121 writer.write(SEPARATOR);
122 writer.write(escape(entry.getValue()));
123 writer.write('\n');
124 }
125 writer.close();
126 } catch (IOException e) {
127 // Note: A ByteArrayOutputStream never throws IOException. This try/catch
128 // is just here to appease the Java compiler.
129 throw new RuntimeException(e);
130 }
131 return baos.toByteArray();
132 }
133
134 /**
135 * Deserializes the variable map from a byte array returned by
136 * {@link #toBytes()}.
137 */
138 public static VariableMap fromBytes(byte[] bytes) throws ParseException {
139 Iterable<String> lines;
140 try {
141 lines = CharStreams.readLines(CharStreams.newReaderSupplier(
142 ByteStreams.newInputStreamSupplier(bytes), Charsets.UTF_8));
143 } catch (IOException e) {
144 // Note: An IOException is never thrown while reading from a byte array.
145 // This try/catch is just here to appease the Java compiler.
146 throw new RuntimeException(e);
147 }
148
149 ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
150
151 for (String line : lines) {
152 int pos = findIndexOfChar(line, SEPARATOR);
153 if (pos <= 0 || pos == line.length() - 1) {
154 throw new ParseException("Bad line: " + line, 0);
155 }
156 map.put(
157 unescape(line.substring(0, pos)),
158 unescape(line.substring(pos + 1)));
159 }
160 return new VariableMap(map.build());
161 }
162
163 private static String escape(String value) {
164 return value.replace("\\", "\\\\")
165 .replace(":", "\\:")
166 .replace("\n", "\\n");
167 }
168
169 private static int findIndexOfChar(String value, char stopChar) {
170 int len = value.length();
171 for (int i=0; i<len; i++) {
172 char c = value.charAt(i);
173 if (c == '\\' && ++i < len) {
174 c = value.charAt(i);
175 } else if (c == stopChar){
176 return i;
177 }
178 }
179 return -1;
180 }
181
182 private static String unescape(CharSequence value) {
183 StringBuilder sb = new StringBuilder();
184 int len = value.length();
185 for (int i=0; i<len; i++) {
186 char c = value.charAt(i);
187 if (c == '\\' && ++i < len) {
188 c = value.charAt(i);
189 }
190 sb.append(c);
191 }
192 return sb.toString();
193 }
194
195 /**
196 * Initializes the variable map from an existing map.
197 * @param map The map to use from original names to generated names. It is
198 * copied and changes to the specified map will not affect the returned
199 * object.
200 */
201 public static VariableMap fromMap(Map<String, String> map) {
202 return new VariableMap(map);
203 }
204
205 @VisibleForTesting
206 Map<String, String> toMap() {
207 return map;
208 }
209 }