Mon, 14 Nov 2011 15:11:10 -0800
7106166: (javac) re-factor EndPos parser
Reviewed-by: jjg
1 /*
2 * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.util;
28 import java.io.ByteArrayOutputStream;
29 import java.io.Closeable;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStreamWriter;
33 import java.lang.ref.SoftReference;
34 import java.lang.reflect.Constructor;
35 import java.net.URL;
36 import java.net.URLClassLoader;
37 import java.nio.ByteBuffer;
38 import java.nio.CharBuffer;
39 import java.nio.charset.Charset;
40 import java.nio.charset.CharsetDecoder;
41 import java.nio.charset.CoderResult;
42 import java.nio.charset.CodingErrorAction;
43 import java.nio.charset.IllegalCharsetNameException;
44 import java.nio.charset.UnsupportedCharsetException;
45 import java.util.Collection;
46 import java.util.HashMap;
47 import java.util.Iterator;
48 import java.util.Map;
49 import javax.tools.JavaFileObject;
50 import javax.tools.JavaFileObject.Kind;
52 import com.sun.tools.javac.code.Lint;
53 import com.sun.tools.javac.code.Source;
54 import com.sun.tools.javac.file.FSInfo;
55 import com.sun.tools.javac.file.Locations;
56 import com.sun.tools.javac.main.JavacOption;
57 import com.sun.tools.javac.main.OptionName;
58 import com.sun.tools.javac.main.RecognizedOptions;
59 import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
61 /**
62 * Utility methods for building a filemanager.
63 * There are no references here to file-system specific objects such as
64 * java.io.File or java.nio.file.Path.
65 */
66 public abstract class BaseFileManager {
67 protected BaseFileManager(Charset charset) {
68 this.charset = charset;
69 byteBufferCache = new ByteBufferCache();
70 locations = createLocations();
71 }
73 /**
74 * Set the context for JavacPathFileManager.
75 */
76 public void setContext(Context context) {
77 log = Log.instance(context);
78 options = Options.instance(context);
79 classLoaderClass = options.get("procloader");
80 locations.update(log, options, Lint.instance(context), FSInfo.instance(context));
81 }
83 protected Locations createLocations() {
84 return new Locations();
85 }
87 /**
88 * The log to be used for error reporting.
89 */
90 public Log log;
92 /**
93 * User provided charset (through javax.tools).
94 */
95 protected Charset charset;
97 protected Options options;
99 protected String classLoaderClass;
101 protected Locations locations;
103 protected Source getSource() {
104 String sourceName = options.get(OptionName.SOURCE);
105 Source source = null;
106 if (sourceName != null)
107 source = Source.lookup(sourceName);
108 return (source != null ? source : Source.DEFAULT);
109 }
111 protected ClassLoader getClassLoader(URL[] urls) {
112 ClassLoader thisClassLoader = getClass().getClassLoader();
114 // Bug: 6558476
115 // Ideally, ClassLoader should be Closeable, but before JDK7 it is not.
116 // On older versions, try the following, to get a closeable classloader.
118 // 1: Allow client to specify the class to use via hidden option
119 if (classLoaderClass != null) {
120 try {
121 Class<? extends ClassLoader> loader =
122 Class.forName(classLoaderClass).asSubclass(ClassLoader.class);
123 Class<?>[] constrArgTypes = { URL[].class, ClassLoader.class };
124 Constructor<? extends ClassLoader> constr = loader.getConstructor(constrArgTypes);
125 return constr.newInstance(new Object[] { urls, thisClassLoader });
126 } catch (Throwable t) {
127 // ignore errors loading user-provided class loader, fall through
128 }
129 }
131 // 2: If URLClassLoader implements Closeable, use that.
132 if (Closeable.class.isAssignableFrom(URLClassLoader.class))
133 return new URLClassLoader(urls, thisClassLoader);
135 // 3: Try using private reflection-based CloseableURLClassLoader
136 try {
137 return new CloseableURLClassLoader(urls, thisClassLoader);
138 } catch (Throwable t) {
139 // ignore errors loading workaround class loader, fall through
140 }
142 // 4: If all else fails, use plain old standard URLClassLoader
143 return new URLClassLoader(urls, thisClassLoader);
144 }
146 // <editor-fold defaultstate="collapsed" desc="Option handling">
147 public boolean handleOption(String current, Iterator<String> remaining) {
148 for (JavacOption o: javacFileManagerOptions) {
149 if (o.matches(current)) {
150 if (o.hasArg()) {
151 if (remaining.hasNext()) {
152 if (!o.process(options, current, remaining.next()))
153 return true;
154 }
155 } else {
156 if (!o.process(options, current))
157 return true;
158 }
159 // operand missing, or process returned false
160 throw new IllegalArgumentException(current);
161 }
162 }
164 return false;
165 }
166 // where
167 private static JavacOption[] javacFileManagerOptions =
168 RecognizedOptions.getJavacFileManagerOptions(
169 new RecognizedOptions.GrumpyHelper(Log.instance(new Context())));
171 public int isSupportedOption(String option) {
172 for (JavacOption o : javacFileManagerOptions) {
173 if (o.matches(option))
174 return o.hasArg() ? 1 : 0;
175 }
176 return -1;
177 }
179 public abstract boolean isDefaultBootClassPath();
181 // </editor-fold>
183 // <editor-fold defaultstate="collapsed" desc="Encoding">
184 private String defaultEncodingName;
185 private String getDefaultEncodingName() {
186 if (defaultEncodingName == null) {
187 defaultEncodingName =
188 new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding();
189 }
190 return defaultEncodingName;
191 }
193 public String getEncodingName() {
194 String encName = options.get(OptionName.ENCODING);
195 if (encName == null)
196 return getDefaultEncodingName();
197 else
198 return encName;
199 }
201 public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
202 String encodingName = getEncodingName();
203 CharsetDecoder decoder;
204 try {
205 decoder = getDecoder(encodingName, ignoreEncodingErrors);
206 } catch (IllegalCharsetNameException e) {
207 log.error("unsupported.encoding", encodingName);
208 return (CharBuffer)CharBuffer.allocate(1).flip();
209 } catch (UnsupportedCharsetException e) {
210 log.error("unsupported.encoding", encodingName);
211 return (CharBuffer)CharBuffer.allocate(1).flip();
212 }
214 // slightly overestimate the buffer size to avoid reallocation.
215 float factor =
216 decoder.averageCharsPerByte() * 0.8f +
217 decoder.maxCharsPerByte() * 0.2f;
218 CharBuffer dest = CharBuffer.
219 allocate(10 + (int)(inbuf.remaining()*factor));
221 while (true) {
222 CoderResult result = decoder.decode(inbuf, dest, true);
223 dest.flip();
225 if (result.isUnderflow()) { // done reading
226 // make sure there is at least one extra character
227 if (dest.limit() == dest.capacity()) {
228 dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
229 dest.flip();
230 }
231 return dest;
232 } else if (result.isOverflow()) { // buffer too small; expand
233 int newCapacity =
234 10 + dest.capacity() +
235 (int)(inbuf.remaining()*decoder.maxCharsPerByte());
236 dest = CharBuffer.allocate(newCapacity).put(dest);
237 } else if (result.isMalformed() || result.isUnmappable()) {
238 // bad character in input
240 // report coding error (warn only pre 1.5)
241 if (!getSource().allowEncodingErrors()) {
242 log.error(new SimpleDiagnosticPosition(dest.limit()),
243 "illegal.char.for.encoding",
244 charset == null ? encodingName : charset.name());
245 } else {
246 log.warning(new SimpleDiagnosticPosition(dest.limit()),
247 "illegal.char.for.encoding",
248 charset == null ? encodingName : charset.name());
249 }
251 // skip past the coding error
252 inbuf.position(inbuf.position() + result.length());
254 // undo the flip() to prepare the output buffer
255 // for more translation
256 dest.position(dest.limit());
257 dest.limit(dest.capacity());
258 dest.put((char)0xfffd); // backward compatible
259 } else {
260 throw new AssertionError(result);
261 }
262 }
263 // unreached
264 }
266 public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) {
267 Charset cs = (this.charset == null)
268 ? Charset.forName(encodingName)
269 : this.charset;
270 CharsetDecoder decoder = cs.newDecoder();
272 CodingErrorAction action;
273 if (ignoreEncodingErrors)
274 action = CodingErrorAction.REPLACE;
275 else
276 action = CodingErrorAction.REPORT;
278 return decoder
279 .onMalformedInput(action)
280 .onUnmappableCharacter(action);
281 }
282 // </editor-fold>
284 // <editor-fold defaultstate="collapsed" desc="ByteBuffers">
285 /**
286 * Make a byte buffer from an input stream.
287 */
288 public ByteBuffer makeByteBuffer(InputStream in)
289 throws IOException {
290 int limit = in.available();
291 if (limit < 1024) limit = 1024;
292 ByteBuffer result = byteBufferCache.get(limit);
293 int position = 0;
294 while (in.available() != 0) {
295 if (position >= limit)
296 // expand buffer
297 result = ByteBuffer.
298 allocate(limit <<= 1).
299 put((ByteBuffer)result.flip());
300 int count = in.read(result.array(),
301 position,
302 limit - position);
303 if (count < 0) break;
304 result.position(position += count);
305 }
306 return (ByteBuffer)result.flip();
307 }
309 public void recycleByteBuffer(ByteBuffer bb) {
310 byteBufferCache.put(bb);
311 }
313 /**
314 * A single-element cache of direct byte buffers.
315 */
316 private static class ByteBufferCache {
317 private ByteBuffer cached;
318 ByteBuffer get(int capacity) {
319 if (capacity < 20480) capacity = 20480;
320 ByteBuffer result =
321 (cached != null && cached.capacity() >= capacity)
322 ? (ByteBuffer)cached.clear()
323 : ByteBuffer.allocate(capacity + capacity>>1);
324 cached = null;
325 return result;
326 }
327 void put(ByteBuffer x) {
328 cached = x;
329 }
330 }
332 private final ByteBufferCache byteBufferCache;
333 // </editor-fold>
335 // <editor-fold defaultstate="collapsed" desc="Content cache">
336 public CharBuffer getCachedContent(JavaFileObject file) {
337 ContentCacheEntry e = contentCache.get(file);
338 if (e == null)
339 return null;
341 if (!e.isValid(file)) {
342 contentCache.remove(file);
343 return null;
344 }
346 return e.getValue();
347 }
349 public void cache(JavaFileObject file, CharBuffer cb) {
350 contentCache.put(file, new ContentCacheEntry(file, cb));
351 }
353 public void flushCache(JavaFileObject file) {
354 contentCache.remove(file);
355 }
357 protected final Map<JavaFileObject, ContentCacheEntry> contentCache
358 = new HashMap<JavaFileObject, ContentCacheEntry>();
360 protected static class ContentCacheEntry {
361 final long timestamp;
362 final SoftReference<CharBuffer> ref;
364 ContentCacheEntry(JavaFileObject file, CharBuffer cb) {
365 this.timestamp = file.getLastModified();
366 this.ref = new SoftReference<CharBuffer>(cb);
367 }
369 boolean isValid(JavaFileObject file) {
370 return timestamp == file.getLastModified();
371 }
373 CharBuffer getValue() {
374 return ref.get();
375 }
376 }
377 // </editor-fold>
379 public static Kind getKind(String name) {
380 if (name.endsWith(Kind.CLASS.extension))
381 return Kind.CLASS;
382 else if (name.endsWith(Kind.SOURCE.extension))
383 return Kind.SOURCE;
384 else if (name.endsWith(Kind.HTML.extension))
385 return Kind.HTML;
386 else
387 return Kind.OTHER;
388 }
390 protected static <T> T nullCheck(T o) {
391 o.getClass(); // null check
392 return o;
393 }
395 protected static <T> Collection<T> nullCheck(Collection<T> it) {
396 for (T t : it)
397 t.getClass(); // null check
398 return it;
399 }
400 }