001    /*
002     * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
003     * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004     *
005     * This code is free software; you can redistribute it and/or modify it
006     * under the terms of the GNU General Public License version 2 only, as
007     * published by the Free Software Foundation.  Sun designates this
008     * particular file as subject to the "Classpath" exception as provided
009     * by Sun in the LICENSE file that accompanied this code.
010     *
011     * This code is distributed in the hope that it will be useful, but WITHOUT
012     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013     * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
014     * version 2 for more details (a copy is included in the LICENSE file that
015     * accompanied this code).
016     *
017     * You should have received a copy of the GNU General Public License version
018     * 2 along with this work; if not, write to the Free Software Foundation,
019     * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020     *
021     * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022     * CA 95054 USA or visit www.sun.com if you need additional information or
023     * have any questions.
024     */
025    
026    package com.sun.tools.javac.api;
027    
028    import java.io.File;
029    import java.io.InputStream;
030    import java.io.OutputStream;
031    import java.io.PrintWriter;
032    import java.io.Writer;
033    import java.util.ArrayList;
034    import java.util.Collections;
035    import java.util.EnumSet;
036    import java.util.Iterator;
037    import java.util.List;
038    import java.util.Locale;
039    import java.util.Set;
040    import javax.lang.model.SourceVersion;
041    import javax.tools.*;
042    
043    import com.sun.source.util.JavacTask;
044    import com.sun.tools.javac.file.JavacFileManager;
045    import com.sun.tools.javac.main.JavacOption.OptionKind;
046    import com.sun.tools.javac.main.JavacOption;
047    import com.sun.tools.javac.main.Main;
048    import com.sun.tools.javac.main.RecognizedOptions.GrumpyHelper;
049    import com.sun.tools.javac.main.RecognizedOptions;
050    import com.sun.tools.javac.util.Context;
051    import com.sun.tools.javac.util.Log;
052    import com.sun.tools.javac.util.JavacMessages;
053    import com.sun.tools.javac.util.Options;
054    import com.sun.tools.javac.util.Pair;
055    import java.nio.charset.Charset;
056    
057    /**
058     * TODO: describe com.sun.tools.javac.api.Tool
059     *
060     * <p><b>This is NOT part of any API supported by Sun Microsystems.
061     * If you write code that depends on this, you do so at your own
062     * risk.  This code and its internal interfaces are subject to change
063     * or deletion without notice.</b></p>
064     *
065     * @author Peter von der Ah\u00e9
066     */
067    public final class JavacTool implements JavaCompiler {
068        private final List<Pair<String,String>> options
069            = new ArrayList<Pair<String,String>>();
070        private final Context dummyContext = new Context();
071    
072        private final PrintWriter silent = new PrintWriter(new OutputStream(){
073            public void write(int b) {}
074        });
075    
076        private final Main sharedCompiler = new Main("javac", silent);
077        {
078            sharedCompiler.setOptions(Options.instance(dummyContext));
079        }
080    
081        /**
082         * Constructor used by service provider mechanism.  The correct way to
083         * obtain an instance of this class is using create or the service provider
084         * mechanism.
085         * @see javax.tools.JavaCompilerTool
086         * @see javax.tools.ToolProvider
087         * @see #create
088         */
089        @Deprecated
090        public JavacTool() {}
091    
092        /**
093         * Static factory method for creating new instances of this tool.
094         * @return new instance of this tool
095         */
096        public static JavacTool create() {
097            return new JavacTool();
098        }
099    
100        private String argsToString(Object... args) {
101            String newArgs = null;
102            if (args.length > 0) {
103                StringBuilder sb = new StringBuilder();
104                String separator = "";
105                for (Object arg : args) {
106                    sb.append(separator).append(arg.toString());
107                    separator = File.pathSeparator;
108                }
109                newArgs = sb.toString();
110            }
111            return newArgs;
112        }
113    
114        private void setOption1(String name, OptionKind kind, Object... args) {
115            String arg = argsToString(args);
116            JavacOption option = sharedCompiler.getOption(name);
117            if (option == null || !match(kind, option.getKind()))
118                throw new IllegalArgumentException(name);
119            if ((args.length != 0) != option.hasArg())
120                throw new IllegalArgumentException(name);
121            if (option.hasArg()) {
122                if (option.process(null, name, arg)) // FIXME
123                    throw new IllegalArgumentException(name);
124            } else {
125                if (option.process(null, name)) // FIXME
126                    throw new IllegalArgumentException(name);
127            }
128            options.add(new Pair<String,String>(name,arg));
129        }
130    
131        public void setOption(String name, Object... args) {
132            setOption1(name, OptionKind.NORMAL, args);
133        }
134    
135        public void setExtendedOption(String name, Object... args)  {
136            setOption1(name, OptionKind.EXTENDED, args);
137        }
138    
139        private static boolean match(OptionKind clientKind, OptionKind optionKind) {
140            return (clientKind == (optionKind == OptionKind.HIDDEN ? optionKind.EXTENDED : optionKind));
141        }
142    
143        public JavacFileManager getStandardFileManager(
144            DiagnosticListener<? super JavaFileObject> diagnosticListener,
145            Locale locale,
146            Charset charset) {
147            Context context = new Context();
148            JavacMessages.instance(context).setCurrentLocale(locale);
149            if (diagnosticListener != null)
150                context.put(DiagnosticListener.class, diagnosticListener);
151            context.put(Log.outKey, new PrintWriter(System.err, true)); // FIXME
152            return new JavacFileManager(context, true, charset);
153        }
154    
155        private boolean compilationInProgress = false;
156    
157        /**
158         * Register that a compilation is about to start.
159         */
160        void beginContext(final Context context) {
161            if (compilationInProgress)
162                throw new IllegalStateException("Compilation in progress");
163            compilationInProgress = true;
164            final JavaFileManager givenFileManager = context.get(JavaFileManager.class);
165            context.put(JavaFileManager.class, (JavaFileManager)null);
166            context.put(JavaFileManager.class, new Context.Factory<JavaFileManager>() {
167                public JavaFileManager make() {
168                    if (givenFileManager != null) {
169                        context.put(JavaFileManager.class, givenFileManager);
170                        return givenFileManager;
171                    } else {
172                        return new JavacFileManager(context, true, null);
173                    }
174                }
175            });
176        }
177    
178        /**
179         * Register that a compilation is completed.
180         */
181        void endContext() {
182            compilationInProgress = false;
183        }
184    
185        public JavacTask getTask(Writer out,
186                                 JavaFileManager fileManager,
187                                 DiagnosticListener<? super JavaFileObject> diagnosticListener,
188                                 Iterable<String> options,
189                                 Iterable<String> classes,
190                                 Iterable<? extends JavaFileObject> compilationUnits)
191        {
192            final String kindMsg = "All compilation units must be of SOURCE kind";
193            if (options != null)
194                for (String option : options)
195                    option.getClass(); // null check
196            if (classes != null) {
197                for (String cls : classes)
198                    if (!SourceVersion.isName(cls)) // implicit null check
199                        throw new IllegalArgumentException("Not a valid class name: " + cls);
200            }
201            if (compilationUnits != null) {
202                for (JavaFileObject cu : compilationUnits) {
203                    if (cu.getKind() != JavaFileObject.Kind.SOURCE) // implicit null check
204                        throw new IllegalArgumentException(kindMsg);
205                }
206            }
207    
208            Context context = new Context();
209    
210            if (diagnosticListener != null)
211                context.put(DiagnosticListener.class, diagnosticListener);
212    
213            if (out == null)
214                context.put(Log.outKey, new PrintWriter(System.err, true));
215            else
216                context.put(Log.outKey, new PrintWriter(out, true));
217    
218            if (fileManager == null)
219                fileManager = getStandardFileManager(diagnosticListener, null, null);
220            context.put(JavaFileManager.class, fileManager);
221            processOptions(context, fileManager, options);
222            Main compiler = new Main("javacTask", context.get(Log.outKey));
223            return new JavacTaskImpl(this, compiler, options, context, classes, compilationUnits);
224        }
225    
226        private static void processOptions(Context context,
227                                           JavaFileManager fileManager,
228                                           Iterable<String> options)
229        {
230            if (options == null)
231                return;
232    
233            Options optionTable = Options.instance(context);
234    
235            JavacOption[] recognizedOptions =
236                RecognizedOptions.getJavacToolOptions(new GrumpyHelper());
237            Iterator<String> flags = options.iterator();
238            while (flags.hasNext()) {
239                String flag = flags.next();
240                int j;
241                for (j=0; j<recognizedOptions.length; j++)
242                    if (recognizedOptions[j].matches(flag))
243                        break;
244    
245                if (j == recognizedOptions.length) {
246                    if (fileManager.handleOption(flag, flags)) {
247                        continue;
248                    } else {
249                        String msg = Main.getLocalizedString("err.invalid.flag", flag);
250                        throw new IllegalArgumentException(msg);
251                    }
252                }
253    
254                JavacOption option = recognizedOptions[j];
255                if (option.hasArg()) {
256                    if (!flags.hasNext()) {
257                        String msg = Main.getLocalizedString("err.req.arg", flag);
258                        throw new IllegalArgumentException(msg);
259                    }
260                    String operand = flags.next();
261                    if (option.process(optionTable, flag, operand))
262                        // should not happen as the GrumpyHelper will throw exceptions
263                        // in case of errors
264                        throw new IllegalArgumentException(flag + " " + operand);
265                } else {
266                    if (option.process(optionTable, flag))
267                        // should not happen as the GrumpyHelper will throw exceptions
268                        // in case of errors
269                        throw new IllegalArgumentException(flag);
270                }
271            }
272        }
273    
274        public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) {
275            if (err == null)
276                err = System.err;
277            for (String argument : arguments)
278                argument.getClass(); // null check
279            return com.sun.tools.javac.Main.compile(arguments, new PrintWriter(err, true));
280        }
281    
282        public Set<SourceVersion> getSourceVersions() {
283            return Collections.unmodifiableSet(EnumSet.range(SourceVersion.RELEASE_3,
284                                                             SourceVersion.latest()));
285        }
286    
287        public int isSupportedOption(String option) {
288            JavacOption[] recognizedOptions =
289                RecognizedOptions.getJavacToolOptions(new GrumpyHelper());
290            for (JavacOption o : recognizedOptions) {
291                if (o.matches(option))
292                    return o.hasArg() ? 1 : 0;
293            }
294            return -1;
295        }
296    
297    }