Thu, 10 Jun 2010 09:29:23 +0100
6945418: Project Coin: Simplified Varargs Method Invocation
Summary: Add new mandatory warning for unsafe vararg method declaration. Warning can be suppressed as usual (@SuppressWarnings("varargs")/-Xlint:-varargs)
Reviewed-by: jjg, darcy
1 /*
2 * Copyright (c) 2009, 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 com.sun.tools.javac.code.Source;
29 import com.sun.tools.javac.main.JavacOption;
30 import com.sun.tools.javac.main.OptionName;
31 import com.sun.tools.javac.main.RecognizedOptions;
32 import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
33 import java.io.ByteArrayOutputStream;
34 import java.io.Closeable;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.OutputStreamWriter;
38 import java.lang.ref.SoftReference;
39 import java.lang.reflect.Constructor;
40 import java.net.URL;
41 import java.net.URLClassLoader;
42 import java.nio.ByteBuffer;
43 import java.nio.CharBuffer;
44 import java.nio.charset.Charset;
45 import java.nio.charset.CharsetDecoder;
46 import java.nio.charset.CoderResult;
47 import java.nio.charset.CodingErrorAction;
48 import java.nio.charset.IllegalCharsetNameException;
49 import java.nio.charset.UnsupportedCharsetException;
50 import java.util.Collection;
51 import java.util.HashMap;
52 import java.util.Iterator;
53 import java.util.Map;
54 import javax.tools.JavaFileObject;
55 import javax.tools.JavaFileObject.Kind;
57 /**
58 * Utility methods for building a filemanager.
59 * There are no references here to file-system specific objects such as
60 * java.io.File or java.nio.file.Path.
61 */
62 public class BaseFileManager {
63 protected BaseFileManager(Charset charset) {
64 this.charset = charset;
65 byteBufferCache = new ByteBufferCache();
66 }
68 /**
69 * Set the context for JavacPathFileManager.
70 */
71 protected void setContext(Context context) {
72 log = Log.instance(context);
73 options = Options.instance(context);
74 classLoaderClass = options.get("procloader");
75 }
77 /**
78 * The log to be used for error reporting.
79 */
80 public Log log;
82 /**
83 * User provided charset (through javax.tools).
84 */
85 protected Charset charset;
87 protected Options options;
89 protected String classLoaderClass;
91 protected Source getSource() {
92 String sourceName = options.get(OptionName.SOURCE);
93 Source source = null;
94 if (sourceName != null)
95 source = Source.lookup(sourceName);
96 return (source != null ? source : Source.DEFAULT);
97 }
99 protected ClassLoader getClassLoader(URL[] urls) {
100 ClassLoader thisClassLoader = getClass().getClassLoader();
102 // Bug: 6558476
103 // Ideally, ClassLoader should be Closeable, but before JDK7 it is not.
104 // On older versions, try the following, to get a closeable classloader.
106 // 1: Allow client to specify the class to use via hidden option
107 if (classLoaderClass != null) {
108 try {
109 Class<? extends ClassLoader> loader =
110 Class.forName(classLoaderClass).asSubclass(ClassLoader.class);
111 Class<?>[] constrArgTypes = { URL[].class, ClassLoader.class };
112 Constructor<? extends ClassLoader> constr = loader.getConstructor(constrArgTypes);
113 return constr.newInstance(new Object[] { urls, thisClassLoader });
114 } catch (Throwable t) {
115 // ignore errors loading user-provided class loader, fall through
116 }
117 }
119 // 2: If URLClassLoader implements Closeable, use that.
120 if (Closeable.class.isAssignableFrom(URLClassLoader.class))
121 return new URLClassLoader(urls, thisClassLoader);
123 // 3: Try using private reflection-based CloseableURLClassLoader
124 try {
125 return new CloseableURLClassLoader(urls, thisClassLoader);
126 } catch (Throwable t) {
127 // ignore errors loading workaround class loader, fall through
128 }
130 // 4: If all else fails, use plain old standard URLClassLoader
131 return new URLClassLoader(urls, thisClassLoader);
132 }
134 // <editor-fold defaultstate="collapsed" desc="Option handling">
135 public boolean handleOption(String current, Iterator<String> remaining) {
136 for (JavacOption o: javacFileManagerOptions) {
137 if (o.matches(current)) {
138 if (o.hasArg()) {
139 if (remaining.hasNext()) {
140 if (!o.process(options, current, remaining.next()))
141 return true;
142 }
143 } else {
144 if (!o.process(options, current))
145 return true;
146 }
147 // operand missing, or process returned false
148 throw new IllegalArgumentException(current);
149 }
150 }
152 return false;
153 }
154 // where
155 private static JavacOption[] javacFileManagerOptions =
156 RecognizedOptions.getJavacFileManagerOptions(
157 new RecognizedOptions.GrumpyHelper());
159 public int isSupportedOption(String option) {
160 for (JavacOption o : javacFileManagerOptions) {
161 if (o.matches(option))
162 return o.hasArg() ? 1 : 0;
163 }
164 return -1;
165 }
166 // </editor-fold>
168 // <editor-fold defaultstate="collapsed" desc="Encoding">
169 private String defaultEncodingName;
170 private String getDefaultEncodingName() {
171 if (defaultEncodingName == null) {
172 defaultEncodingName =
173 new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding();
174 }
175 return defaultEncodingName;
176 }
178 public String getEncodingName() {
179 String encName = options.get(OptionName.ENCODING);
180 if (encName == null)
181 return getDefaultEncodingName();
182 else
183 return encName;
184 }
186 public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
187 String encodingName = getEncodingName();
188 CharsetDecoder decoder;
189 try {
190 decoder = getDecoder(encodingName, ignoreEncodingErrors);
191 } catch (IllegalCharsetNameException e) {
192 log.error("unsupported.encoding", encodingName);
193 return (CharBuffer)CharBuffer.allocate(1).flip();
194 } catch (UnsupportedCharsetException e) {
195 log.error("unsupported.encoding", encodingName);
196 return (CharBuffer)CharBuffer.allocate(1).flip();
197 }
199 // slightly overestimate the buffer size to avoid reallocation.
200 float factor =
201 decoder.averageCharsPerByte() * 0.8f +
202 decoder.maxCharsPerByte() * 0.2f;
203 CharBuffer dest = CharBuffer.
204 allocate(10 + (int)(inbuf.remaining()*factor));
206 while (true) {
207 CoderResult result = decoder.decode(inbuf, dest, true);
208 dest.flip();
210 if (result.isUnderflow()) { // done reading
211 // make sure there is at least one extra character
212 if (dest.limit() == dest.capacity()) {
213 dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
214 dest.flip();
215 }
216 return dest;
217 } else if (result.isOverflow()) { // buffer too small; expand
218 int newCapacity =
219 10 + dest.capacity() +
220 (int)(inbuf.remaining()*decoder.maxCharsPerByte());
221 dest = CharBuffer.allocate(newCapacity).put(dest);
222 } else if (result.isMalformed() || result.isUnmappable()) {
223 // bad character in input
225 // report coding error (warn only pre 1.5)
226 if (!getSource().allowEncodingErrors()) {
227 log.error(new SimpleDiagnosticPosition(dest.limit()),
228 "illegal.char.for.encoding",
229 charset == null ? encodingName : charset.name());
230 } else {
231 log.warning(new SimpleDiagnosticPosition(dest.limit()),
232 "illegal.char.for.encoding",
233 charset == null ? encodingName : charset.name());
234 }
236 // skip past the coding error
237 inbuf.position(inbuf.position() + result.length());
239 // undo the flip() to prepare the output buffer
240 // for more translation
241 dest.position(dest.limit());
242 dest.limit(dest.capacity());
243 dest.put((char)0xfffd); // backward compatible
244 } else {
245 throw new AssertionError(result);
246 }
247 }
248 // unreached
249 }
251 public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) {
252 Charset cs = (this.charset == null)
253 ? Charset.forName(encodingName)
254 : this.charset;
255 CharsetDecoder decoder = cs.newDecoder();
257 CodingErrorAction action;
258 if (ignoreEncodingErrors)
259 action = CodingErrorAction.REPLACE;
260 else
261 action = CodingErrorAction.REPORT;
263 return decoder
264 .onMalformedInput(action)
265 .onUnmappableCharacter(action);
266 }
267 // </editor-fold>
269 // <editor-fold defaultstate="collapsed" desc="ByteBuffers">
270 /**
271 * Make a byte buffer from an input stream.
272 */
273 public ByteBuffer makeByteBuffer(InputStream in)
274 throws IOException {
275 int limit = in.available();
276 if (limit < 1024) limit = 1024;
277 ByteBuffer result = byteBufferCache.get(limit);
278 int position = 0;
279 while (in.available() != 0) {
280 if (position >= limit)
281 // expand buffer
282 result = ByteBuffer.
283 allocate(limit <<= 1).
284 put((ByteBuffer)result.flip());
285 int count = in.read(result.array(),
286 position,
287 limit - position);
288 if (count < 0) break;
289 result.position(position += count);
290 }
291 return (ByteBuffer)result.flip();
292 }
294 public void recycleByteBuffer(ByteBuffer bb) {
295 byteBufferCache.put(bb);
296 }
298 /**
299 * A single-element cache of direct byte buffers.
300 */
301 private static class ByteBufferCache {
302 private ByteBuffer cached;
303 ByteBuffer get(int capacity) {
304 if (capacity < 20480) capacity = 20480;
305 ByteBuffer result =
306 (cached != null && cached.capacity() >= capacity)
307 ? (ByteBuffer)cached.clear()
308 : ByteBuffer.allocate(capacity + capacity>>1);
309 cached = null;
310 return result;
311 }
312 void put(ByteBuffer x) {
313 cached = x;
314 }
315 }
317 private final ByteBufferCache byteBufferCache;
318 // </editor-fold>
320 // <editor-fold defaultstate="collapsed" desc="Content cache">
321 public CharBuffer getCachedContent(JavaFileObject file) {
322 SoftReference<CharBuffer> r = contentCache.get(file);
323 return (r == null ? null : r.get());
324 }
326 public void cache(JavaFileObject file, CharBuffer cb) {
327 contentCache.put(file, new SoftReference<CharBuffer>(cb));
328 }
330 protected final Map<JavaFileObject, SoftReference<CharBuffer>> contentCache
331 = new HashMap<JavaFileObject, SoftReference<CharBuffer>>();
332 // </editor-fold>
334 public static Kind getKind(String name) {
335 if (name.endsWith(Kind.CLASS.extension))
336 return Kind.CLASS;
337 else if (name.endsWith(Kind.SOURCE.extension))
338 return Kind.SOURCE;
339 else if (name.endsWith(Kind.HTML.extension))
340 return Kind.HTML;
341 else
342 return Kind.OTHER;
343 }
345 protected static <T> T nullCheck(T o) {
346 o.getClass(); // null check
347 return o;
348 }
350 protected static <T> Collection<T> nullCheck(Collection<T> it) {
351 for (T t : it)
352 t.getClass(); // null check
353 return it;
354 }
355 }