下面列出了javax.annotation.processing.AbstractProcessor#javax.lang.model.SourceVersion 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private String assert_java_identifier(ParseTree node, boolean isDefining) {
String name = node.getText();
if ("for".equals(name)) {
if (isDefining) {
throw reportError("Syntax error on token \"" + name + "\" is not a valid identifier.", node);
}
return name;
}
if (Code.CONTEXT_NAME.equals(name)) {
if (isDefining) {
throw reportError("Duplicate local variable \"" + name + "\" is a reserved identifier.", node);
}
return name;
}
if (SourceVersion.isKeyword(name)) {
throw reportError("Syntax error on token \"" + name + "\", It is not a valid identifier in Java.", node);
}
if (name.startsWith("$")) {
throw reportError("Local variable \"" + name + "\" can't start with '$', it is a reserved identifier.", node);
}
return name;
}
public static void main(String... args) {
Tool compiler = ToolProvider.getSystemJavaCompiler();
Set<SourceVersion> expected = EnumSet.noneOf(SourceVersion.class);
for (String arg : args)
expected.add(SourceVersion.valueOf(arg));
Set<SourceVersion> found = compiler.getSourceVersions();
Set<SourceVersion> notExpected = EnumSet.copyOf(found);
for (SourceVersion version : expected) {
if (!found.contains(version))
throw new AssertionError("Expected source version not found: " + version);
else
notExpected.remove(version);
}
if (!notExpected.isEmpty())
throw new AssertionError("Unexpected source versions: " + notExpected);
}
@Parameters(name = "{0}")
public static Collection<Object[]> data() {
ImmutableList.Builder<Object[]> params = ImmutableList.builder();
if (SourceVersion.latestSupported().compareTo(SourceVersion.RELEASE_8) > 0) {
// use default options when running on JDK > 8
// TODO(b/72513371): use --release 8 once compile-testing supports that
params.add(
new Object[] {
ImmutableList.of(), "javax.annotation.processing.Generated",
});
}
params.add(
new Object[] {
ImmutableList.of("-source", "8", "-target", "8"), "javax.annotation.Generated",
});
return params.build();
}
/** Gets the class file version corresponding to the given source version constant. */
public static int sourceVersionToClassFileVersion(SourceVersion version) {
switch (version) {
case RELEASE_0:
return Opcodes.V1_1; // JVMS8 4.1: 1.0 and 1.1 both support version 45.3 (Opcodes.V1_1)
case RELEASE_1:
return Opcodes.V1_1;
case RELEASE_2:
return Opcodes.V1_2;
case RELEASE_3:
return Opcodes.V1_3;
case RELEASE_4:
return Opcodes.V1_4;
case RELEASE_5:
return Opcodes.V1_5;
case RELEASE_6:
return Opcodes.V1_6;
case RELEASE_7:
return Opcodes.V1_7;
case RELEASE_8:
return Opcodes.V1_8;
default:
throw new IllegalArgumentException(String.format("Unexpected source version: %s", version));
}
}
private void fillIn(PackageSymbol p,
Location location,
Iterable<JavaFileObject> files)
{
currentLoc = location;
for (JavaFileObject fo : files) {
switch (fo.getKind()) {
case CLASS:
case SOURCE: {
// TODO pass binaryName to includeClassFile
String binaryName = fileManager.inferBinaryName(currentLoc, fo);
String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
if (SourceVersion.isIdentifier(simpleName) ||
simpleName.equals("package-info"))
includeClassFile(p, fo);
break;
}
default:
extraFileActions(p, fo);
}
}
}
public static void main(String... args) {
Tool compiler = ToolProvider.getSystemJavaCompiler();
Set<SourceVersion> expected = EnumSet.noneOf(SourceVersion.class);
for (String arg : args)
expected.add(SourceVersion.valueOf(arg));
Set<SourceVersion> found = compiler.getSourceVersions();
Set<SourceVersion> notExpected = EnumSet.copyOf(found);
for (SourceVersion version : expected) {
if (!found.contains(version))
throw new AssertionError("Expected source version not found: " + version);
else
notExpected.remove(version);
}
if (!notExpected.isEmpty())
throw new AssertionError("Unexpected source versions: " + notExpected);
}
public static void main(String... args) {
Tool compiler = ToolProvider.getSystemJavaCompiler();
Set<SourceVersion> expected = EnumSet.noneOf(SourceVersion.class);
for (String arg : args)
expected.add(SourceVersion.valueOf(arg));
Set<SourceVersion> found = compiler.getSourceVersions();
Set<SourceVersion> notExpected = EnumSet.copyOf(found);
for (SourceVersion version : expected) {
if (!found.contains(version))
throw new AssertionError("Expected source version not found: " + version);
else
notExpected.remove(version);
}
if (!notExpected.isEmpty())
throw new AssertionError("Unexpected source versions: " + notExpected);
}
public static void main(String... args) {
Tool compiler = ToolProvider.getSystemJavaCompiler();
Set<SourceVersion> expected = EnumSet.noneOf(SourceVersion.class);
for (String arg : args)
expected.add(SourceVersion.valueOf(arg));
Set<SourceVersion> found = compiler.getSourceVersions();
Set<SourceVersion> notExpected = EnumSet.copyOf(found);
for (SourceVersion version : expected) {
if (!found.contains(version))
throw new AssertionError("Expected source version not found: " + version);
else
notExpected.remove(version);
}
if (!notExpected.isEmpty())
throw new AssertionError("Unexpected source versions: " + notExpected);
}
/** Resolve an identifier.
* @param name The identifier to resolve
*/
public Symbol resolveIdent(String name) {
if (name.equals(""))
return syms.errSymbol;
JavaFileObject prev = log.useSource(null);
try {
JCExpression tree = null;
for (String s : name.split("\\.", -1)) {
if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
return syms.errSymbol;
tree = (tree == null) ? make.Ident(names.fromString(s))
: make.Select(tree, names.fromString(s));
}
JCCompilationUnit toplevel =
make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
toplevel.packge = syms.unnamedPackage;
return attr.attribIdent(tree, toplevel);
} finally {
log.useSource(prev);
}
}
private void validateLimitModules(SourceVersion sv) {
String limitModules = options.get(Option.LIMIT_MODULES);
if (limitModules != null) {
// Each entry must be of the form target-list where target-list is a
// comma separated list of module names, or ALL-DEFAULT, ALL-SYSTEM,
// or ALL-MODULE_PATH.
// Empty items in the target list are ignored.
// There must be at least one item in the list; this is handled in Option.LIMIT_EXPORTS.
for (String moduleName : limitModules.split(",")) {
switch (moduleName) {
case "":
break;
default:
if (!SourceVersion.isName(moduleName, sv)) {
// syntactically invalid module name: e.g. --limit-modules m1,m!
log.error(Errors.BadNameForOption(Option.LIMIT_MODULES, moduleName));
}
break;
}
}
}
}
/**
* @param targetVersion the class file version to target, expressed as the corresponding Java
* source version
* @param messager
* @param types
* @param includeParameterMetadata
*/
ClassVisitorDriverFromElement(
SourceVersion targetVersion,
ElementsExtended elements,
Messager messager,
Types types,
boolean includeParameterMetadata) {
this.targetVersion = targetVersion;
this.elements = elements;
descriptorFactory = new DescriptorFactory(elements);
this.messager = messager;
this.types = types;
this.includeParameterMetadata = includeParameterMetadata;
signatureFactory = new SignatureFactory(descriptorFactory);
accessFlagsUtils = new AccessFlags(elements);
}
/**
* Checks whether or not a processor's source version is
* compatible with the compilation source version. The
* processor's source version needs to be greater than or
* equal to the source version of the compile.
*/
private void checkSourceVersionCompatibility(Source source, Log log) {
SourceVersion procSourceVersion = processor.getSupportedSourceVersion();
if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0 ) {
log.warning("proc.processor.incompatible.source.version",
procSourceVersion,
processor.getClass().getName(),
source.name);
}
}
public static boolean isPackageNameValid(String packageName) {
if (!SourceVersion.isName(packageName)) {
return false;
}
if (packageName.startsWith("java")) {
return false;
}
return true;
}
public void testTrailingEmptyCase() throws Exception {
if(!ConvertSwitchToRuleSwitchTest.isJDK14())
return;
HintTest.create()
.input("package test;" +
"public class Test {\n" +
" private void test(int p) {\n" +
" String result;\n" +
" switch (p) {\n" +
" case 0:\n" +
" int i = 0;\n" +
" int j = 0;\n" +
" break;\n" +
" default:\n" +
" }\n" +
" }\n" +
"}\n")
.sourceLevel(SourceVersion.latest().name())
.run(ConvertSwitchToRuleSwitch.class)
.findWarning("3:9-3:15:verifier:" + Bundle.ERR_ConvertSwitchToRuleSwitch())
.applyFix()
.assertCompilable()
.assertOutput("package test;" +
"public class Test {\n" +
" private void test(int p) {\n" +
" String result;\n" +
" switch (p) {\n" +
" case 0 -> {\n" +
" int i = 0;\n" +
" int j = 0;\n" +
" }\n" +
" default -> { }\n" +
" }\n" +
" }\n" +
"}\n");
}
public void testSpanIndentationTextBlock1() throws Exception {
try {
SourceVersion.valueOf("RELEASE_13");
} catch (IllegalArgumentException ex) {
//OK, skip test:
return ;
}
performSpanIndentationTest("package t;\npublic class T {\n|private final String s = \"\"\"\n\"\"\";|\n}\n",
"package t;\npublic class T {\n private final String s = \"\"\"\n \"\"\";\n}\n");
}
public void testSpanIndentationTextBlock2() throws Exception {
try {
SourceVersion.valueOf("RELEASE_13");
} catch (IllegalArgumentException ex) {
//OK, skip test:
return ;
}
performSpanIndentationTest("package t;\npublic class T {\n|private final String s = \"\"\"\n1\n 2\n 3\n\"\"\";|\n}\n",
"package t;\npublic class T {\n private final String s = \"\"\"\n 1\n 2\n 3\n \"\"\";\n}\n");
}
public static JavacOptions parse(OptionChecker primary, OptionChecker secondary, String... arguments) {
List<String> recognizedOptions = new ArrayList<String>();
List<String> unrecognizedOptions = new ArrayList<String>();
List<String> classNames = new ArrayList<String>();
List<File> files = new ArrayList<File>();
for (int i = 0; i < arguments.length; i++) {
String argument = arguments[i];
int optionCount = primary.isSupportedOption(argument);
if (optionCount < 0) {
optionCount = secondary.isSupportedOption(argument);
}
if (optionCount < 0) {
File file = new File(argument);
if (file.exists())
files.add(file);
else if (SourceVersion.isName(argument))
classNames.add(argument);
else
unrecognizedOptions.add(argument);
} else {
for (int j = 0; j < optionCount + 1; j++) {
int index = i + j;
if (index == arguments.length) throw new IllegalArgumentException(argument);
recognizedOptions.add(arguments[index]);
}
i += optionCount;
}
}
return new JavacOptions(recognizedOptions, classNames, files, unrecognizedOptions);
}
public void testRecord2() throws Exception {
try {
SourceVersion.valueOf("RELEASE_14"); //NOI18N
} catch (IllegalArgumentException ex) {
//OK, no RELEASE_14, skip tests
return;
}
setSourceLevel("14");
performTest("Records",
"public class Records {\n" +
" public interface Super {}\n" +
" public record Foo1(String i, String j) implements Super { }\n" +
" public record Foo2(String i, String j) implements Super { }\n" +
" public record Foo3(String i, String j) implements Super { }\n" +
"}\n",
"[PUBLIC, CLASS, DECLARATION], 0:13-0:20",
"[STATIC, PUBLIC, INTERFACE, DECLARATION], 1:21-1:26",
"[KEYWORD], 2:11-2:17",
"[STATIC, PUBLIC, RECORD, DECLARATION], 2:18-2:22",
"[PUBLIC, CLASS], 2:23-2:29",
"[PUBLIC, RECORD_COMPONENT, DECLARATION], 2:30-2:31",
"[PUBLIC, CLASS], 2:33-2:39",
"[PUBLIC, RECORD_COMPONENT, DECLARATION], 2:40-2:41",
"[STATIC, PUBLIC, INTERFACE], 2:54-2:59",
"[KEYWORD], 3:11-3:17",
"[STATIC, PUBLIC, RECORD, DECLARATION], 3:18-3:22",
"[PUBLIC, CLASS], 3:23-3:29",
"[PUBLIC, RECORD_COMPONENT, DECLARATION], 3:30-3:31",
"[PUBLIC, CLASS], 3:33-3:39",
"[PUBLIC, RECORD_COMPONENT, DECLARATION], 3:40-3:41",
"[STATIC, PUBLIC, INTERFACE], 3:54-3:59",
"[KEYWORD], 4:11-4:17",
"[STATIC, PUBLIC, RECORD, DECLARATION], 4:18-4:22",
"[PUBLIC, CLASS], 4:23-4:29",
"[PUBLIC, RECORD_COMPONENT, DECLARATION], 4:30-4:31",
"[PUBLIC, CLASS], 4:33-4:39",
"[PUBLIC, RECORD_COMPONENT, DECLARATION], 4:40-4:41",
"[STATIC, PUBLIC, INTERFACE], 4:54-4:59");
}
/**
* If the processor class is annotated with {@link
* SupportedSourceVersion}, return the source version in the
* annotation. If the class is not so annotated, {@link
* SourceVersion#RELEASE_6} is returned.
*
* @return the latest source version supported by this processor
*/
public SourceVersion getSupportedSourceVersion() {
SupportedSourceVersion ssv = this.getClass().getAnnotation(SupportedSourceVersion.class);
SourceVersion sv = null;
if (ssv == null) {
sv = SourceVersion.RELEASE_6;
if (isInitialized())
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
"No SupportedSourceVersion annotation " +
"found on " + this.getClass().getName() +
", returning " + sv + ".");
} else
sv = ssv.value();
return sv;
}
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnvironment) {
SourceVersion expectedVersion =
SourceVersion.valueOf(processingEnv.getOptions().get("ExpectedVersion"));
SourceVersion actualVersion = processingEnv.getSourceVersion();
System.out.println("Expected SourceVersion " + expectedVersion +
" actual SourceVersion " + actualVersion);
if (expectedVersion != actualVersion)
throw new RuntimeException();
return true;
}
private static String extractMemberName(String part) {
checkArgument(Character.isJavaIdentifierStart(part.charAt(0)), "not an identifier: %s", part);
for (int i = 1; i <= part.length(); i++) {
if (!SourceVersion.isIdentifier(part.substring(0, i))) {
return part.substring(0, i - 1);
}
}
return part;
}
@Override
public SourceVersion getSupportedSourceVersion() {
if (SourceVersion.latest().compareTo(SourceVersion.RELEASE_6) > 0)
return SourceVersion.valueOf("RELEASE_7");
else
return SourceVersion.RELEASE_6;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.RELEASE_8;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public SourceVersion getSupportedSourceVersion() {
// support the latest release
return SourceVersion.latest();
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}