1 /*
  2  * Copyright (c) 2018, 2023, 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.code;
 27 
 28 import com.sun.tools.javac.code.Lint.LintCategory;
 29 import com.sun.tools.javac.code.Source.Feature;
 30 import com.sun.tools.javac.jvm.Target;
 31 import com.sun.tools.javac.resources.CompilerProperties.Errors;
 32 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
 33 import com.sun.tools.javac.util.Assert;
 34 import com.sun.tools.javac.util.Context;
 35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
 36 import com.sun.tools.javac.util.JCDiagnostic.Error;
 37 import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
 38 import com.sun.tools.javac.util.JCDiagnostic.Warning;
 39 import com.sun.tools.javac.util.Log;
 40 import com.sun.tools.javac.util.MandatoryWarningHandler;
 41 import com.sun.tools.javac.util.Names;
 42 import com.sun.tools.javac.util.Options;
 43 
 44 import javax.tools.JavaFileObject;
 45 import java.util.HashMap;
 46 import java.util.HashSet;
 47 import java.util.Map;
 48 import java.util.Set;
 49 
 50 import static com.sun.tools.javac.code.Flags.RECORD;
 51 import static com.sun.tools.javac.code.Flags.SEALED;
 52 import static com.sun.tools.javac.code.Flags.NON_SEALED;
 53 import static com.sun.tools.javac.main.Option.PREVIEW;
 54 import com.sun.tools.javac.util.JCDiagnostic;
 55 
 56 /**
 57  * Helper class to handle preview language features. This class maps certain language features
 58  * (see {@link Feature} into 'preview' features; the mapping is completely ad-hoc, so as to allow
 59  * for maximum flexibility, which allows to migrate preview feature into supported features with ease.
 60  *
 61  * This class acts as a centralized point against which usages of preview features are reported by
 62  * clients (e.g. other javac classes). Internally, this class collects all such usages and generates
 63  * diagnostics to inform the user of such usages. Such diagnostics can be enabled using the
 64  * {@link LintCategory#PREVIEW} lint category, and are suppressible by usual means.
 65  */
 66 public class Preview {
 67 
 68     /** flag: are preview features enabled */
 69     private final boolean enabled;
 70 
 71     /** the diag handler to manage preview feature usage diagnostics */
 72     private final MandatoryWarningHandler previewHandler;
 73 
 74     /** test flag: should all features be considered as preview features? */
 75     private final boolean forcePreview;
 76 
 77     /** a mapping from classfile numbers to Java SE versions */
 78     private final Map<Integer, Source> majorVersionToSource;
 79 
 80     private final Set<JavaFileObject> sourcesWithPreviewFeatures = new HashSet<>();
 81 
 82     private final Names names;
 83     private final Lint lint;
 84     private final Log log;
 85     private final Source source;
 86 
 87     private static final Context.Key<Preview> previewKey = new Context.Key<>();
 88 
 89     public static Preview instance(Context context) {
 90         Preview instance = context.get(previewKey);
 91         if (instance == null) {
 92             instance = new Preview(context);
 93         }
 94         return instance;
 95     }
 96 
 97     Preview(Context context) {
 98         context.put(previewKey, this);
 99         Options options = Options.instance(context);
100         names = Names.instance(context);
101         enabled = options.isSet(PREVIEW);
102         log = Log.instance(context);
103         lint = Lint.instance(context);
104         source = Source.instance(context);
105         this.previewHandler =
106                 new MandatoryWarningHandler(log, source, lint.isEnabled(LintCategory.PREVIEW), true, "preview", LintCategory.PREVIEW);
107         forcePreview = options.isSet("forcePreview");
108         majorVersionToSource = initMajorVersionToSourceMap();
109     }
110 
111     private Map<Integer, Source> initMajorVersionToSourceMap() {
112         Map<Integer, Source> majorVersionToSource = new HashMap<>();
113         for (Target t : Target.values()) {
114             int major = t.majorVersion;
115             Source source = Source.lookup(t.name);
116             if (source != null) {
117                 majorVersionToSource.put(major, source);
118             }
119         }
120         return majorVersionToSource;
121     }
122 
123     /**
124      * Returns true if {@code s} is deemed to participate in the preview of {@code previewSymbol}, and
125      * therefore no warnings or errors will be produced.
126      *
127      * @param syms the symbol table
128      * @param s the symbol depending on the preview symbol
129      * @param previewSymbol the preview symbol marked with @Preview
130      * @return true if {@code s} is participating in the preview of {@code previewSymbol}
131      */
132     public boolean participatesInPreview(Symtab syms, Symbol s, Symbol previewSymbol) {
133         // All symbols in the same module as the preview symbol participate in the preview API
134         if (previewSymbol.packge().modle == s.packge().modle) {
135             return true;
136         }
137 
138         // If java.base's jdk.internal.javac package is exported to s's module then
139         // s participates in the preview API
140         return syms.java_base.exports.stream()
141                 .filter(ed -> ed.packge.fullname == names.jdk_internal_javac)
142                 .anyMatch(ed -> ed.modules.contains(s.packge().modle));
143     }
144 
145     /**
146      * Report usage of a preview feature. Usages reported through this method will affect the
147      * set of sourcefiles with dependencies on preview features.
148      * @param pos the position at which the preview feature was used.
149      * @param feature the preview feature used.
150      */
151     public void warnPreview(int pos, Feature feature) {
152         warnPreview(new SimpleDiagnosticPosition(pos), feature);
153     }
154 
155     /**
156      * Report usage of a preview feature. Usages reported through this method will affect the
157      * set of sourcefiles with dependencies on preview features.
158      * @param pos the position at which the preview feature was used.
159      * @param feature the preview feature used.
160      */
161     public void warnPreview(DiagnosticPosition pos, Feature feature) {
162         Assert.check(isEnabled());
163         Assert.check(isPreview(feature));
164         if (!lint.isSuppressed(LintCategory.PREVIEW)) {
165             sourcesWithPreviewFeatures.add(log.currentSourceFile());
166             previewHandler.report(pos, feature.isPlural() ?
167                     Warnings.PreviewFeatureUsePlural(feature.nameFragment()) :
168                     Warnings.PreviewFeatureUse(feature.nameFragment()));
169         }
170     }
171 
172     /**
173      * Report usage of a preview feature in classfile.
174      * @param classfile the name of the classfile with preview features enabled
175      * @param majorVersion the major version found in the classfile.
176      */
177     public void warnPreview(JavaFileObject classfile, int majorVersion) {
178         Assert.check(isEnabled());
179         if (lint.isEnabled(LintCategory.PREVIEW)) {
180             log.mandatoryWarning(LintCategory.PREVIEW, null,
181                     Warnings.PreviewFeatureUseClassfile(classfile, majorVersionToSource.get(majorVersion).name));
182         }
183     }
184 
185     public void markUsesPreview(DiagnosticPosition pos) {
186         sourcesWithPreviewFeatures.add(log.currentSourceFile());
187     }
188 
189     public void reportPreviewWarning(DiagnosticPosition pos, Warning warnKey) {
190         previewHandler.report(pos, warnKey);
191     }
192 
193     public boolean usesPreview(JavaFileObject file) {
194         return sourcesWithPreviewFeatures.contains(file);
195     }
196 
197     /**
198      * Are preview features enabled?
199      * @return true, if preview features are enabled.
200      */
201     public boolean isEnabled() {
202         return enabled;
203     }
204 
205     /**
206      * Is given feature a preview feature?
207      * @param feature the feature to be tested.
208      * @return true, if given feature is a preview feature.
209      */
210     public boolean isPreview(Feature feature) {
211         return switch (feature) {
212             case STRING_TEMPLATES -> true;
213             case UNNAMED_CLASSES -> true;
214             case SUPER_INIT -> true;
215             case VALUE_CLASSES -> true;
216             //Note: this is a backdoor which allows to optionally treat all features as 'preview' (for testing).
217             //When real preview features will be added, this method can be implemented to return 'true'
218             //for those selected features, and 'false' for all the others.
219             default -> forcePreview;
220         };
221     }
222 
223     /**
224      * Generate an error key which captures the fact that a given preview feature could not be used
225      * due to the preview feature support being disabled.
226      * @param feature the feature for which the diagnostic has to be generated.
227      * @return the diagnostic.
228      */
229     public Error disabledError(Feature feature) {
230         Assert.check(!isEnabled());
231         return feature.isPlural() ?
232                 Errors.PreviewFeatureDisabledPlural(feature.nameFragment()) :
233                 Errors.PreviewFeatureDisabled(feature.nameFragment());
234     }
235 
236     /**
237      * Generate an error key which captures the fact that a preview classfile cannot be loaded
238      * due to the preview feature support being disabled.
239      * @param classfile the name of the classfile with preview features enabled
240      * @param majorVersion the major version found in the classfile.
241      */
242     public Error disabledError(JavaFileObject classfile, int majorVersion) {
243         Assert.check(!isEnabled());
244         return Errors.PreviewFeatureDisabledClassfile(classfile, majorVersionToSource.get(majorVersion).name);
245     }
246 
247     /**
248      * Check whether the given symbol has been declared using
249      * a preview language feature.
250      *
251      * @param sym Symbol to check
252      * @return true iff sym has been declared using a preview language feature
253      */
254     public boolean declaredUsingPreviewFeature(Symbol sym) {
255         return false;
256     }
257 
258     /**
259      * Report any deferred diagnostics.
260      */
261     public void reportDeferredDiagnostics() {
262         previewHandler.reportDeferredDiagnostic();
263     }
264 
265     public void clear() {
266         previewHandler.clear();
267     }
268 
269     public void checkSourceLevel(DiagnosticPosition pos, Feature feature) {
270         if (isPreview(feature) && !isEnabled()) {
271             //preview feature without --preview flag, error
272             log.error(JCDiagnostic.DiagnosticFlag.SOURCE_LEVEL, pos, disabledError(feature));
273         } else {
274             if (!feature.allowedInSource(source)) {
275                 log.error(JCDiagnostic.DiagnosticFlag.SOURCE_LEVEL, pos,
276                           feature.error(source.name));
277             }
278             if (isEnabled() && isPreview(feature)) {
279                 warnPreview(pos, feature);
280             }
281         }
282     }
283 
284 }