1 /*
  2  * Copyright (c) 2005, 2021, 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  */
 25 
 26 package com.sun.tools.javac.api;
 27 
 28 import java.io.InputStream;
 29 import java.io.OutputStream;
 30 import java.io.OutputStreamWriter;
 31 import java.io.PrintWriter;
 32 import java.io.Writer;
 33 import java.nio.charset.Charset;
 34 import java.util.Collections;
 35 import java.util.EnumSet;
 36 import java.util.Locale;
 37 import java.util.Objects;
 38 import java.util.Set;
 39 
 40 import javax.lang.model.SourceVersion;
 41 import javax.tools.*;
 42 
 43 import com.sun.source.util.JavacTask;
 44 import com.sun.tools.javac.code.Preview;
 45 import com.sun.tools.javac.file.JavacFileManager;
 46 import com.sun.tools.javac.main.Arguments;
 47 import com.sun.tools.javac.main.Option;
 48 import com.sun.tools.javac.file.BaseFileManager;
 49 import com.sun.tools.javac.file.CacheFSInfo;
 50 import com.sun.tools.javac.jvm.Target;
 51 import com.sun.tools.javac.util.ClientCodeException;
 52 import com.sun.tools.javac.util.Context;
 53 import com.sun.tools.javac.util.DefinedBy;
 54 import com.sun.tools.javac.util.DefinedBy.Api;
 55 import com.sun.tools.javac.util.List;
 56 import com.sun.tools.javac.util.Log;
 57 import com.sun.tools.javac.util.PropagatedException;
 58 
 59 /**
 60  * TODO: describe com.sun.tools.javac.api.Tool
 61  *
 62  * <p><b>This is NOT part of any supported API.
 63  * If you write code that depends on this, you do so at your own
 64  * risk.  This code and its internal interfaces are subject to change
 65  * or deletion without notice.</b></p>
 66  *
 67  * @author Peter von der Ahé
 68  */
 69 public final class JavacTool implements JavaCompiler {
 70     /**
 71      * Constructor used by service provider mechanism.  The recommended way to
 72      * obtain an instance of this class is by using {@link #create} or the
 73      * service provider mechanism.
 74      * @see javax.tools.JavaCompiler
 75      * @see javax.tools.ToolProvider
 76      * @see #create
 77      */
 78     @Deprecated
 79     public JavacTool() {}
 80 
 81     // @Override // can't add @Override until bootstrap JDK provides Tool.name()
 82     @DefinedBy(Api.COMPILER)
 83     public String name() {
 84         return "javac";
 85     }
 86 
 87     /**
 88      * Static factory method for creating new instances of this tool.
 89      * @return new instance of this tool
 90      */
 91     public static JavacTool create() {
 92         return new JavacTool();
 93     }
 94 
 95     @Override @DefinedBy(Api.COMPILER)
 96     public JavacFileManager getStandardFileManager(
 97         DiagnosticListener<? super JavaFileObject> diagnosticListener,
 98         Locale locale,
 99         Charset charset) {
100         Context context = new Context();
101         context.put(Locale.class, locale);
102         if (diagnosticListener != null)
103             context.put(DiagnosticListener.class, diagnosticListener);
104         PrintWriter pw = (charset == null)
105                 ? new PrintWriter(System.err, true)
106                 : new PrintWriter(new OutputStreamWriter(System.err, charset), true);
107         context.put(Log.errKey, pw);
108         CacheFSInfo.preRegister(context);
109         return new JavacFileManager(context, true, charset);
110     }
111 
112     @Override @DefinedBy(Api.COMPILER)
113     public JavacTask getTask(Writer out,
114                              JavaFileManager fileManager,
115                              DiagnosticListener<? super JavaFileObject> diagnosticListener,
116                              Iterable<String> options,
117                              Iterable<String> classes,
118                              Iterable<? extends JavaFileObject> compilationUnits) {
119         Context context = new Context();
120         return getTask(out, fileManager, diagnosticListener,
121                 options, classes, compilationUnits,
122                 context);
123     }
124 
125     /* Internal version of getTask, allowing context to be provided. */
126     public JavacTask getTask(Writer out,
127                              JavaFileManager fileManager,
128                              DiagnosticListener<? super JavaFileObject> diagnosticListener,
129                              Iterable<String> options,
130                              Iterable<String> classes,
131                              Iterable<? extends JavaFileObject> compilationUnits,
132                              Context context)
133     {
134         try {
135             ClientCodeWrapper ccw = ClientCodeWrapper.instance(context);
136 
137             if (options != null) {
138                 for (String option : options)
139                     Objects.requireNonNull(option);
140             }
141 
142             if (classes != null) {
143                 for (String cls : classes) {
144                     int sep = cls.indexOf('/'); // implicit null check
145                     if (sep > 0) {
146                         String mod = cls.substring(0, sep);
147                         if (!SourceVersion.isName(mod))
148                             throw new IllegalArgumentException("Not a valid module name: " + mod);
149                         cls = cls.substring(sep + 1);
150                     }
151                     if (!SourceVersion.isName(cls))
152                         throw new IllegalArgumentException("Not a valid class name: " + cls);
153                 }
154             }
155 
156             if (compilationUnits != null) {
157                 compilationUnits = ccw.wrapJavaFileObjects(compilationUnits); // implicit null check
158                 for (JavaFileObject cu : compilationUnits) {
159                     if (cu.getKind() != JavaFileObject.Kind.SOURCE) {
160                         String kindMsg = "Compilation unit is not of SOURCE kind: "
161                                 + "\"" + cu.getName() + "\"";
162                         throw new IllegalArgumentException(kindMsg);
163                     }
164                 }
165             }
166 
167             if (diagnosticListener != null)
168                 context.put(DiagnosticListener.class, ccw.wrap(diagnosticListener));
169 
170             // If out is null and the value is set in the context, we need to do nothing.
171             if (out == null && context.get(Log.errKey) == null)
172                 // Situation: out is null and the value is not set in the context.
173                 context.put(Log.errKey, new PrintWriter(System.err, true));
174             else if (out instanceof PrintWriter pw)
175                 // Situation: out is not null and out is a PrintWriter.
176                 context.put(Log.errKey, pw);
177             else if (out != null)
178                 // Situation: out is not null and out is not a PrintWriter.
179                 context.put(Log.errKey, new PrintWriter(out, true));
180 
181             if (fileManager == null) {
182                 fileManager = getStandardFileManager(diagnosticListener, null, null);
183                 if (fileManager instanceof BaseFileManager baseFileManager) {
184                     baseFileManager.autoClose = true;
185                 }
186             }
187             fileManager = ccw.wrap(fileManager);
188 
189             context.put(JavaFileManager.class, fileManager);
190 
191             Arguments args = Arguments.instance(context);
192             args.init("javac", options, classes, compilationUnits);
193 
194             // init multi-release jar handling
195             if (fileManager.isSupportedOption(Option.MULTIRELEASE.primaryName) == 1) {
196                 Target target = Target.instance(context);
197                 List<String> list = List.of(target.multiReleaseValue());
198                 fileManager.handleOption(Option.MULTIRELEASE.primaryName, list.iterator());
199             }
200 
201             // pass preview mode to the file manager:
202             if (fileManager.isSupportedOption(Option.PREVIEWMODE.primaryName) == 1) {
203                 Preview preview = Preview.instance(context);
204                 fileManager.handleOption(Option.PREVIEWMODE.primaryName, List.of(String.valueOf(preview.isEnabled())).iterator());
205             }
206 
207             return new JavacTaskImpl(context);
208         } catch (PropagatedException ex) {
209             throw ex.getCause();
210         } catch (ClientCodeException ex) {
211             throw new RuntimeException(ex.getCause());
212         }
213     }
214 
215     @Override @DefinedBy(Api.COMPILER)
216     public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) {
217         if (err == null)
218             err = System.err;
219         for (String argument : arguments)
220             Objects.requireNonNull(argument);
221         return com.sun.tools.javac.Main.compile(arguments, new PrintWriter(err, true));
222     }
223 
224     @Override @DefinedBy(Api.COMPILER)
225     public Set<SourceVersion> getSourceVersions() {
226         return Collections.unmodifiableSet(EnumSet.range(SourceVersion.RELEASE_3,
227                                                          SourceVersion.latest()));
228     }
229 
230     @Override @DefinedBy(Api.COMPILER)
231     public int isSupportedOption(String option) {
232         Set<Option> recognizedOptions = Option.getJavacToolOptions();
233         for (Option o : recognizedOptions) {
234             if (o.matches(option)) {
235                 return o.hasSeparateArg() ? 1 : 0;
236             }
237         }
238         return -1;
239     }
240 
241 }