test/tools/javac/diags/ArgTypeCompilerFactory.java

Wed, 06 Apr 2011 20:33:44 -0700

author
ohair
date
Wed, 06 Apr 2011 20:33:44 -0700
changeset 962
0ff2bbd38f10
parent 893
8f0dcb9499db
child 1097
497571d34112
permissions
-rw-r--r--

7033660: Update copyright year to 2011 on any files changed in 2011
Reviewed-by: dholmes

     1 /*
     2  * Copyright (c) 2010, 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.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  */
    24 import java.io.*;
    25 import java.util.*;
    26 import java.util.List;
    27 import javax.tools.*;
    29 import com.sun.tools.javac.api.*;
    30 import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.DiagnosticPart;
    31 import com.sun.tools.javac.api.Formattable.LocalizedString;
    32 import com.sun.tools.javac.code.Flags.Flag;
    33 import com.sun.tools.javac.code.Kinds.KindName;
    34 import com.sun.tools.javac.code.*;
    35 import com.sun.tools.javac.file.*;
    36 import com.sun.tools.javac.main.Main;
    37 import com.sun.tools.javac.main.JavaCompiler;
    38 import com.sun.tools.javac.parser.Token;
    39 import com.sun.tools.javac.util.*;
    40 import com.sun.tools.javac.util.AbstractDiagnosticFormatter.SimpleConfiguration;
    41 import javax.lang.model.SourceVersion;
    43 /**
    44  * Compiler factory for instances of Example.Compiler that use custom
    45  * DiagnosticFormatter and Messages objects to track the types of args
    46  * when when localizing diagnostics.
    47  * The compiler objects only support "output" mode, not "check" mode.
    48  */
    49 class ArgTypeCompilerFactory implements Example.Compiler.Factory {
    50     // Same code as Example.Compiler.DefaultFactory, but the names resolve differently
    51     public Example.Compiler getCompiler(List<String> opts, boolean verbose) {
    52         String first;
    53         String[] rest;
    54         if (opts == null || opts.isEmpty()) {
    55             first = null;
    56             rest = new String[0];
    57         } else {
    58             first = opts.get(0);
    59             rest = opts.subList(1, opts.size()).toArray(new String[opts.size() - 1]);
    60         }
    61         if (first == null || first.equals("jsr199"))
    62             return new Jsr199Compiler(verbose, rest);
    63         else if (first.equals("simple"))
    64             return new SimpleCompiler(verbose);
    65         else if (first.equals("backdoor"))
    66             return new BackdoorCompiler(verbose);
    67         else
    68             throw new IllegalArgumentException(first);
    69     }
    71     /**
    72      * Compile using the JSR 199 API.  The diagnostics generated are
    73      * scanned for resource keys.   Not all diagnostic keys are generated
    74      * via the JSR 199 API -- for example, rich diagnostics are not directly
    75      * accessible, and some diagnostics generated by the file manager may
    76      * not be generated (for example, the JSR 199 file manager does not see
    77      * -Xlint:path).
    78      */
    79     static class Jsr199Compiler extends Example.Compiler {
    80         List<String> fmOpts;
    82         Jsr199Compiler(boolean verbose, String... args) {
    83             super(verbose);
    84             for (int i = 0; i < args.length; i++) {
    85                 String arg = args[i];
    86                 if (arg.equals("-filemanager") && (i + 1 < args.length)) {
    87                     fmOpts = Arrays.asList(args[++i].split(","));
    88                 } else
    89                     throw new IllegalArgumentException(arg);
    90             }
    91         }
    93         @Override
    94         boolean run(PrintWriter out, Set<String> keys, boolean raw, List<String> opts, List<File> files) {
    95             assert out != null && keys == null;
    97             if (verbose)
    98                 System.err.println("run_jsr199: " + opts + " " + files);
   100             JavacTool tool = JavacTool.create();
   102             StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
   103             if (fmOpts != null)
   104                 fm = new FileManager(fm, fmOpts);
   106             Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);
   108             JavacTaskImpl t = (JavacTaskImpl) tool.getTask(out, fm, null, opts, null, fos);
   109             Context c = t.getContext();
   110             ArgTypeMessages.preRegister(c);
   111             ArgTypeJavaCompiler.preRegister(c);
   112             Boolean ok = t.call();
   114             return ok;
   115         }
   116     }
   118     /**
   119      * Run the test using the standard simple entry point.
   120      */
   121     static class SimpleCompiler extends Example.Compiler {
   122         SimpleCompiler(boolean verbose) {
   123             super(verbose);
   124         }
   126         @Override
   127         boolean run(PrintWriter out, Set<String> keys, boolean raw, List<String> opts, List<File> files) {
   128             assert out != null && keys == null;
   130             if (verbose)
   131                 System.err.println("run_simple: " + opts + " " + files);
   133             List<String> args = new ArrayList<String>();
   135             args.addAll(opts);
   136             for (File f: files)
   137                 args.add(f.getPath());
   139             Main main = new Main("javac", out);
   140             Context c = new Context() {
   141                 @Override public void clear() {
   142                     ((JavacFileManager) get(JavaFileManager.class)).close();
   143                     super.clear();
   144                 }
   145             };
   146             JavacFileManager.preRegister(c); // can't create it until Log has been set up
   147             ArgTypeJavaCompiler.preRegister(c);
   148             ArgTypeMessages.preRegister(c);
   149             int result = main.compile(args.toArray(new String[args.size()]), c);
   151             return (result == 0);
   152         }
   153     }
   155     static class BackdoorCompiler extends Example.Compiler {
   156         BackdoorCompiler(boolean verbose) {
   157             super(verbose);
   158         }
   160         @Override
   161         boolean run(PrintWriter out, Set<String> keys, boolean raw, List<String> opts, List<File> files) {
   162             assert out != null && keys == null;
   164             if (verbose)
   165                 System.err.println("run_simple: " + opts + " " + files);
   167             List<String> args = new ArrayList<String>(opts);
   168             for (File f: files)
   169                 args.add(f.getPath());
   171             Context c = new Context();
   172             JavacFileManager.preRegister(c); // can't create it until Log has been set up
   173             ArgTypeJavaCompiler.preRegister(c);
   174             ArgTypeMessages.preRegister(c);
   175             com.sun.tools.javac.main.Main m = new com.sun.tools.javac.main.Main("javac", out);
   176             int rc = m.compile(args.toArray(new String[args.size()]), c);
   178             return (rc == 0);
   179         }
   181     }
   184     // <editor-fold defaultstate="collapsed" desc="Custom Javac components">
   186     /**
   187      * Diagnostic formatter which reports formats a diag as a series of lines
   188      * containing a key, and a possibly empty set of descriptive strings for the
   189      * arg types.
   190      */
   191     static class ArgTypeDiagnosticFormatter extends AbstractDiagnosticFormatter {
   193         ArgTypeDiagnosticFormatter(Options options) {
   194             super(null, new SimpleConfiguration(options,
   195                     EnumSet.of(DiagnosticPart.SUMMARY,
   196                     DiagnosticPart.DETAILS,
   197                     DiagnosticPart.SUBDIAGNOSTICS)));
   198         }
   200         @Override
   201         protected String formatDiagnostic(JCDiagnostic d, Locale locale) {
   202             return formatMessage(d, locale);
   203         }
   205         @Override
   206         public String formatMessage(JCDiagnostic d, Locale l) {
   207             StringBuilder buf = new StringBuilder();
   208             formatMessage(d, buf);
   209             return buf.toString();
   210         }
   212         private void formatMessage(JCDiagnostic d, StringBuilder buf) {
   213             String key = d.getCode();
   214             Object[] args = d.getArgs();
   215             // report the primary arg types, without recursing into diag fragments
   216             buf.append(getKeyArgsString(key, args));
   217             // report details for any diagnostic fragments
   218             for (Object arg: args) {
   219                 if (arg instanceof JCDiagnostic) {
   220                     buf.append("\n");
   221                     formatMessage((JCDiagnostic) arg, buf);
   222                 }
   223             }
   224             // report details for any subdiagnostics
   225             for (String s: formatSubdiagnostics(d, null)) {
   226                 buf.append("\n");
   227                 buf.append(s);
   228             }
   229         }
   231         @Override
   232         public boolean isRaw() {
   233             return true;
   234         }
   235     }
   237     /**
   238      * Trivial subtype of JavaCompiler to get access to the protected compilerKey field.
   239      * The factory is used to ensure that the log is initialized with an instance of
   240      * ArgTypeDiagnosticFormatter before we create the required JavaCompiler.
   241      */
   242     static class ArgTypeJavaCompiler extends JavaCompiler {
   243         static void preRegister(Context context) {
   244             context.put(compilerKey, new Context.Factory<JavaCompiler>() {
   245                 public JavaCompiler make(Context c) {
   246                     Log log = Log.instance(c);
   247                     Options options = Options.instance(c);
   248                     log.setDiagnosticFormatter(new ArgTypeDiagnosticFormatter(options));
   249                     return new JavaCompiler(c);
   250                 }
   251             });
   252         }
   254         // not used
   255         private ArgTypeJavaCompiler() {
   256             super(null);
   257         }
   258     }
   260     /**
   261      * Diagnostic formatter which "localizes" a message as a line
   262      * containing a key, and a possibly empty set of descriptive strings for the
   263      * arg types.
   264      */
   265     static class ArgTypeMessages extends JavacMessages {
   266         static void preRegister(Context context) {
   267             context.put(JavacMessages.messagesKey, new Context.Factory<JavacMessages>() {
   268                 public JavacMessages make(Context c) {
   269                     return new ArgTypeMessages(c) {
   270                         @Override
   271                         public String getLocalizedString(Locale l, String key, Object... args) {
   272                             return getKeyArgsString(key, args);
   273                         }
   274                     };
   275                 }
   276             });
   277         }
   279         ArgTypeMessages(Context context) {
   280             super(context);
   281         }
   282     }
   284     /**
   285      * Utility method to generate a string for key and args
   286      */
   287     static String getKeyArgsString(String key, Object... args) {
   288         StringBuilder buf = new StringBuilder();
   289         buf.append(key);
   290         String sep = ": ";
   291         for (Object o : args) {
   292             buf.append(sep);
   293             buf.append(getArgTypeOrStringValue(o));
   294             sep = ", ";
   295         }
   296         return buf.toString();
   297     }
   299     static boolean showStringValues = false;
   301     static String getArgTypeOrStringValue(Object o) {
   302         if (showStringValues && o instanceof String)
   303             return "\"" + o + "\"";
   304         return getArgType(o);
   305     }
   307     static String getArgType(Object o) {
   308         if (o == null)
   309             return "null";
   310         if (o instanceof Name)
   311             return "name";
   312         if (o instanceof Boolean)
   313             return "boolean";
   314         if (o instanceof Integer)
   315             return "number";
   316         if (o instanceof String)
   317             return "string";
   318         if (o instanceof Flag)
   319             return "modifier";
   320         if (o instanceof KindName)
   321             return "symbol kind";
   322         if (o instanceof Token)
   323             return "token";
   324         if (o instanceof Symbol)
   325             return "symbol";
   326         if (o instanceof Type)
   327             return "type";
   328         if (o instanceof List) {
   329             List<?> l = (List<?>) o;
   330             if (l.isEmpty())
   331                 return "list";
   332             else
   333                 return "list of " + getArgType(l.get(0));
   334         }
   335         if (o instanceof ListBuffer)
   336             return getArgType(((ListBuffer) o).toList());
   337         if (o instanceof Set) {
   338             Set<?> s = (Set<?>) o;
   339             if (s.isEmpty())
   340                 return "set";
   341             else
   342                 return "set of " + getArgType(s.iterator().next());
   343         }
   344         if (o instanceof SourceVersion)
   345             return "source version";
   346         if (o instanceof FileObject || o instanceof File)
   347             return "file name";
   348         if (o instanceof JCDiagnostic)
   349             return "message segment";
   350         if (o instanceof LocalizedString)
   351             return "message segment";  // only instance is "no arguments"
   352         String s = o.getClass().getSimpleName();
   353         return (s.isEmpty() ? o.getClass().getName() : s);
   354     }
   356     // </editor-fold>
   358 }

mercurial