test/tools/javac/diags/ArgTypeCompilerFactory.java

changeset 0
959103a6100f
child 2525
2eb010b6cb22
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/test/tools/javac/diags/ArgTypeCompilerFactory.java	Wed Apr 27 01:34:52 2016 +0800
     1.3 @@ -0,0 +1,356 @@
     1.4 +/*
     1.5 + * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.
    1.11 + *
    1.12 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.13 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.14 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.15 + * version 2 for more details (a copy is included in the LICENSE file that
    1.16 + * accompanied this code).
    1.17 + *
    1.18 + * You should have received a copy of the GNU General Public License version
    1.19 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.20 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.21 + *
    1.22 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.23 + * or visit www.oracle.com if you need additional information or have any
    1.24 + * questions.
    1.25 + */
    1.26 +
    1.27 +import java.io.*;
    1.28 +import java.util.*;
    1.29 +import java.util.List;
    1.30 +import javax.tools.*;
    1.31 +
    1.32 +import com.sun.tools.javac.api.*;
    1.33 +import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.DiagnosticPart;
    1.34 +import com.sun.tools.javac.api.Formattable.LocalizedString;
    1.35 +import com.sun.tools.javac.code.Flags.Flag;
    1.36 +import com.sun.tools.javac.code.Kinds.KindName;
    1.37 +import com.sun.tools.javac.code.*;
    1.38 +import com.sun.tools.javac.file.*;
    1.39 +import com.sun.tools.javac.main.Main;
    1.40 +import com.sun.tools.javac.main.JavaCompiler;
    1.41 +import com.sun.tools.javac.parser.Tokens.TokenKind;
    1.42 +import com.sun.tools.javac.util.*;
    1.43 +import com.sun.tools.javac.util.AbstractDiagnosticFormatter.SimpleConfiguration;
    1.44 +import javax.lang.model.SourceVersion;
    1.45 +
    1.46 +/**
    1.47 + * Compiler factory for instances of Example.Compiler that use custom
    1.48 + * DiagnosticFormatter and Messages objects to track the types of args
    1.49 + * when when localizing diagnostics.
    1.50 + * The compiler objects only support "output" mode, not "check" mode.
    1.51 + */
    1.52 +class ArgTypeCompilerFactory implements Example.Compiler.Factory {
    1.53 +    // Same code as Example.Compiler.DefaultFactory, but the names resolve differently
    1.54 +    public Example.Compiler getCompiler(List<String> opts, boolean verbose) {
    1.55 +        String first;
    1.56 +        String[] rest;
    1.57 +        if (opts == null || opts.isEmpty()) {
    1.58 +            first = null;
    1.59 +            rest = new String[0];
    1.60 +        } else {
    1.61 +            first = opts.get(0);
    1.62 +            rest = opts.subList(1, opts.size()).toArray(new String[opts.size() - 1]);
    1.63 +        }
    1.64 +        if (first == null || first.equals("jsr199"))
    1.65 +            return new Jsr199Compiler(verbose, rest);
    1.66 +        else if (first.equals("simple"))
    1.67 +            return new SimpleCompiler(verbose);
    1.68 +        else if (first.equals("backdoor"))
    1.69 +            return new BackdoorCompiler(verbose);
    1.70 +        else
    1.71 +            throw new IllegalArgumentException(first);
    1.72 +    }
    1.73 +
    1.74 +    /**
    1.75 +     * Compile using the JSR 199 API.  The diagnostics generated are
    1.76 +     * scanned for resource keys.   Not all diagnostic keys are generated
    1.77 +     * via the JSR 199 API -- for example, rich diagnostics are not directly
    1.78 +     * accessible, and some diagnostics generated by the file manager may
    1.79 +     * not be generated (for example, the JSR 199 file manager does not see
    1.80 +     * -Xlint:path).
    1.81 +     */
    1.82 +    static class Jsr199Compiler extends Example.Compiler {
    1.83 +        List<String> fmOpts;
    1.84 +
    1.85 +        Jsr199Compiler(boolean verbose, String... args) {
    1.86 +            super(verbose);
    1.87 +            for (int i = 0; i < args.length; i++) {
    1.88 +                String arg = args[i];
    1.89 +                if (arg.equals("-filemanager") && (i + 1 < args.length)) {
    1.90 +                    fmOpts = Arrays.asList(args[++i].split(","));
    1.91 +                } else
    1.92 +                    throw new IllegalArgumentException(arg);
    1.93 +            }
    1.94 +        }
    1.95 +
    1.96 +        @Override
    1.97 +        boolean run(PrintWriter out, Set<String> keys, boolean raw, List<String> opts, List<File> files) {
    1.98 +            assert out != null && keys == null;
    1.99 +
   1.100 +            if (verbose)
   1.101 +                System.err.println("run_jsr199: " + opts + " " + files);
   1.102 +
   1.103 +            JavacTool tool = JavacTool.create();
   1.104 +
   1.105 +            StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
   1.106 +            if (fmOpts != null)
   1.107 +                fm = new FileManager(fm, fmOpts);
   1.108 +
   1.109 +            Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);
   1.110 +
   1.111 +            Context c = new Context();
   1.112 +            ArgTypeMessages.preRegister(c);
   1.113 +            ArgTypeJavaCompiler.preRegister(c);
   1.114 +            JavacTaskImpl t = (JavacTaskImpl) tool.getTask(out, fm, null, opts, null, fos, c);
   1.115 +            return t.call();
   1.116 +        }
   1.117 +    }
   1.118 +
   1.119 +    /**
   1.120 +     * Run the test using the standard simple entry point.
   1.121 +     */
   1.122 +    static class SimpleCompiler extends Example.Compiler {
   1.123 +        SimpleCompiler(boolean verbose) {
   1.124 +            super(verbose);
   1.125 +        }
   1.126 +
   1.127 +        @Override
   1.128 +        boolean run(PrintWriter out, Set<String> keys, boolean raw, List<String> opts, List<File> files) {
   1.129 +            assert out != null && keys == null;
   1.130 +
   1.131 +            if (verbose)
   1.132 +                System.err.println("run_simple: " + opts + " " + files);
   1.133 +
   1.134 +            List<String> args = new ArrayList<String>();
   1.135 +
   1.136 +            args.addAll(opts);
   1.137 +            for (File f: files)
   1.138 +                args.add(f.getPath());
   1.139 +
   1.140 +            Main main = new Main("javac", out);
   1.141 +            Context c = new Context() {
   1.142 +                @Override public void clear() {
   1.143 +                    ((JavacFileManager) get(JavaFileManager.class)).close();
   1.144 +                    super.clear();
   1.145 +                }
   1.146 +            };
   1.147 +            JavacFileManager.preRegister(c); // can't create it until Log has been set up
   1.148 +            ArgTypeJavaCompiler.preRegister(c);
   1.149 +            ArgTypeMessages.preRegister(c);
   1.150 +            Main.Result result = main.compile(args.toArray(new String[args.size()]), c);
   1.151 +
   1.152 +            return result.isOK();
   1.153 +        }
   1.154 +    }
   1.155 +
   1.156 +    static class BackdoorCompiler extends Example.Compiler {
   1.157 +        BackdoorCompiler(boolean verbose) {
   1.158 +            super(verbose);
   1.159 +        }
   1.160 +
   1.161 +        @Override
   1.162 +        boolean run(PrintWriter out, Set<String> keys, boolean raw, List<String> opts, List<File> files) {
   1.163 +            assert out != null && keys == null;
   1.164 +
   1.165 +            if (verbose)
   1.166 +                System.err.println("run_simple: " + opts + " " + files);
   1.167 +
   1.168 +            List<String> args = new ArrayList<String>(opts);
   1.169 +            for (File f: files)
   1.170 +                args.add(f.getPath());
   1.171 +
   1.172 +            Context c = new Context();
   1.173 +            JavacFileManager.preRegister(c); // can't create it until Log has been set up
   1.174 +            ArgTypeJavaCompiler.preRegister(c);
   1.175 +            ArgTypeMessages.preRegister(c);
   1.176 +            Main m = new Main("javac", out);
   1.177 +            Main.Result result = m.compile(args.toArray(new String[args.size()]), c);
   1.178 +
   1.179 +            return result.isOK();
   1.180 +        }
   1.181 +
   1.182 +    }
   1.183 +
   1.184 +
   1.185 +    // <editor-fold defaultstate="collapsed" desc="Custom Javac components">
   1.186 +
   1.187 +    /**
   1.188 +     * Diagnostic formatter which reports formats a diag as a series of lines
   1.189 +     * containing a key, and a possibly empty set of descriptive strings for the
   1.190 +     * arg types.
   1.191 +     */
   1.192 +    static class ArgTypeDiagnosticFormatter extends AbstractDiagnosticFormatter {
   1.193 +
   1.194 +        ArgTypeDiagnosticFormatter(Options options) {
   1.195 +            super(null, new SimpleConfiguration(options,
   1.196 +                    EnumSet.of(DiagnosticPart.SUMMARY,
   1.197 +                    DiagnosticPart.DETAILS,
   1.198 +                    DiagnosticPart.SUBDIAGNOSTICS)));
   1.199 +        }
   1.200 +
   1.201 +        @Override
   1.202 +        protected String formatDiagnostic(JCDiagnostic d, Locale locale) {
   1.203 +            return formatMessage(d, locale);
   1.204 +        }
   1.205 +
   1.206 +        @Override
   1.207 +        public String formatMessage(JCDiagnostic d, Locale l) {
   1.208 +            StringBuilder buf = new StringBuilder();
   1.209 +            formatMessage(d, buf);
   1.210 +            return buf.toString();
   1.211 +        }
   1.212 +
   1.213 +        private void formatMessage(JCDiagnostic d, StringBuilder buf) {
   1.214 +            String key = d.getCode();
   1.215 +            Object[] args = d.getArgs();
   1.216 +            // report the primary arg types, without recursing into diag fragments
   1.217 +            buf.append(getKeyArgsString(key, args));
   1.218 +            // report details for any diagnostic fragments
   1.219 +            for (Object arg: args) {
   1.220 +                if (arg instanceof JCDiagnostic) {
   1.221 +                    buf.append("\n");
   1.222 +                    formatMessage((JCDiagnostic) arg, buf);
   1.223 +                }
   1.224 +            }
   1.225 +            // report details for any subdiagnostics
   1.226 +            for (String s: formatSubdiagnostics(d, null)) {
   1.227 +                buf.append("\n");
   1.228 +                buf.append(s);
   1.229 +            }
   1.230 +        }
   1.231 +
   1.232 +        @Override
   1.233 +        public boolean isRaw() {
   1.234 +            return true;
   1.235 +        }
   1.236 +    }
   1.237 +
   1.238 +    /**
   1.239 +     * Trivial subtype of JavaCompiler to get access to the protected compilerKey field.
   1.240 +     * The factory is used to ensure that the log is initialized with an instance of
   1.241 +     * ArgTypeDiagnosticFormatter before we create the required JavaCompiler.
   1.242 +     */
   1.243 +    static class ArgTypeJavaCompiler extends JavaCompiler {
   1.244 +        static void preRegister(Context context) {
   1.245 +            context.put(compilerKey, new Context.Factory<JavaCompiler>() {
   1.246 +                public JavaCompiler make(Context c) {
   1.247 +                    Log log = Log.instance(c);
   1.248 +                    Options options = Options.instance(c);
   1.249 +                    log.setDiagnosticFormatter(new ArgTypeDiagnosticFormatter(options));
   1.250 +                    return new JavaCompiler(c);
   1.251 +                }
   1.252 +            });
   1.253 +        }
   1.254 +
   1.255 +        // not used
   1.256 +        private ArgTypeJavaCompiler() {
   1.257 +            super(null);
   1.258 +        }
   1.259 +    }
   1.260 +
   1.261 +    /**
   1.262 +     * Diagnostic formatter which "localizes" a message as a line
   1.263 +     * containing a key, and a possibly empty set of descriptive strings for the
   1.264 +     * arg types.
   1.265 +     */
   1.266 +    static class ArgTypeMessages extends JavacMessages {
   1.267 +        static void preRegister(Context context) {
   1.268 +            context.put(JavacMessages.messagesKey, new Context.Factory<JavacMessages>() {
   1.269 +                public JavacMessages make(Context c) {
   1.270 +                    return new ArgTypeMessages(c) {
   1.271 +                        @Override
   1.272 +                        public String getLocalizedString(Locale l, String key, Object... args) {
   1.273 +                            return getKeyArgsString(key, args);
   1.274 +                        }
   1.275 +                    };
   1.276 +                }
   1.277 +            });
   1.278 +        }
   1.279 +
   1.280 +        ArgTypeMessages(Context context) {
   1.281 +            super(context);
   1.282 +        }
   1.283 +    }
   1.284 +
   1.285 +    /**
   1.286 +     * Utility method to generate a string for key and args
   1.287 +     */
   1.288 +    static String getKeyArgsString(String key, Object... args) {
   1.289 +        StringBuilder buf = new StringBuilder();
   1.290 +        buf.append(key);
   1.291 +        String sep = ": ";
   1.292 +        for (Object o : args) {
   1.293 +            buf.append(sep);
   1.294 +            buf.append(getArgTypeOrStringValue(o));
   1.295 +            sep = ", ";
   1.296 +        }
   1.297 +        return buf.toString();
   1.298 +    }
   1.299 +
   1.300 +    static boolean showStringValues = false;
   1.301 +
   1.302 +    static String getArgTypeOrStringValue(Object o) {
   1.303 +        if (showStringValues && o instanceof String)
   1.304 +            return "\"" + o + "\"";
   1.305 +        return getArgType(o);
   1.306 +    }
   1.307 +
   1.308 +    static String getArgType(Object o) {
   1.309 +        if (o == null)
   1.310 +            return "null";
   1.311 +        if (o instanceof Name)
   1.312 +            return "name";
   1.313 +        if (o instanceof Boolean)
   1.314 +            return "boolean";
   1.315 +        if (o instanceof Integer)
   1.316 +            return "number";
   1.317 +        if (o instanceof String)
   1.318 +            return "string";
   1.319 +        if (o instanceof Flag)
   1.320 +            return "modifier";
   1.321 +        if (o instanceof KindName)
   1.322 +            return "symbol kind";
   1.323 +        if (o instanceof TokenKind)
   1.324 +            return "token";
   1.325 +        if (o instanceof Symbol)
   1.326 +            return "symbol";
   1.327 +        if (o instanceof Type)
   1.328 +            return "type";
   1.329 +        if (o instanceof List) {
   1.330 +            List<?> l = (List<?>) o;
   1.331 +            if (l.isEmpty())
   1.332 +                return "list";
   1.333 +            else
   1.334 +                return "list of " + getArgType(l.get(0));
   1.335 +        }
   1.336 +        if (o instanceof ListBuffer)
   1.337 +            return getArgType(((ListBuffer) o).toList());
   1.338 +        if (o instanceof Set) {
   1.339 +            Set<?> s = (Set<?>) o;
   1.340 +            if (s.isEmpty())
   1.341 +                return "set";
   1.342 +            else
   1.343 +                return "set of " + getArgType(s.iterator().next());
   1.344 +        }
   1.345 +        if (o instanceof SourceVersion)
   1.346 +            return "source version";
   1.347 +        if (o instanceof FileObject || o instanceof File)
   1.348 +            return "file name";
   1.349 +        if (o instanceof JCDiagnostic)
   1.350 +            return "message segment";
   1.351 +        if (o instanceof LocalizedString)
   1.352 +            return "message segment";  // only instance is "no arguments"
   1.353 +        String s = o.getClass().getSimpleName();
   1.354 +        return (s.isEmpty() ? o.getClass().getName() : s);
   1.355 +    }
   1.356 +
   1.357 +    // </editor-fold>
   1.358 +
   1.359 +}

mercurial