javax.lang.model.SourceVersion Java Examples

The following examples show how to use javax.lang.model.SourceVersion. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: T6395981.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example #2
Source File: T6395981.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example #3
Source File: T6395981.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example #4
Source File: JavaCompiler.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/** 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);
    }
}
 
Example #5
Source File: JetTemplateCodeVisitor.java    From jetbrick-template-1x with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: Arguments.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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;
            }
        }
    }
}
 
Example #7
Source File: ClassVisitorDriverFromElement.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * @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);
}
 
Example #8
Source File: GeneratedDoesNotExistTest.java    From auto with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #9
Source File: SourceVersionUtils.java    From buck with Apache License 2.0 6 votes vote down vote up
/** 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));
  }
}
 
Example #10
Source File: ClassReader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #11
Source File: T6395981.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example #12
Source File: CodeWriter.java    From JReFrameworker with MIT License 5 votes vote down vote up
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;
}
 
Example #13
Source File: SchemaGenerator.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #14
Source File: AbstractProcessor.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #15
Source File: ReindenterTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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");
}
 
Example #16
Source File: DetectorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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");
}
 
Example #17
Source File: PackageUtil.java    From celerio with Apache License 2.0 5 votes vote down vote up
public static boolean isPackageNameValid(String packageName) {
    if (!SourceVersion.isName(packageName)) {
        return false;
    }

    if (packageName.startsWith("java")) {
        return false;
    }

    return true;
}
 
Example #18
Source File: TestSourceVersion.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #19
Source File: AnnotationParser.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    if (SourceVersion.latest().compareTo(SourceVersion.RELEASE_6) > 0)
        return SourceVersion.valueOf("RELEASE_7");
    else
        return SourceVersion.RELEASE_6;
}
 
Example #20
Source File: ReindenterTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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");
}
 
Example #21
Source File: JavacProcessingEnvironment.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #22
Source File: ConvertSwitchToRuleSwitchTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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");
}
 
Example #23
Source File: TestGetElement.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latest();
}
 
Example #24
Source File: FitProcessor.java    From fit with Apache License 2.0 4 votes vote down vote up
@Override public SourceVersion getSupportedSourceVersion() {
  return SourceVersion.latestSupported();
}
 
Example #25
Source File: ProcessorImpl.java    From takari-lifecycle with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
  return SourceVersion.RELEASE_7;
}
 
Example #26
Source File: VerifierAnnotationProcessor.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latest();
}
 
Example #27
Source File: JavaValidator.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
/**
 * Return error string or null if function name is valid.
 * @param typeName tested function name
 */
public static String validateTypeName(String typeName)
{
	// don't conflict with @Test annotation
	if("Test".equals(typeName)) {
		return "Test is already defined";
	}
	
	if ("".equals(typeName)) {
		return "Invalid empty Type name";
	}

	if (typeName.contains(" ")) {
		return "Type '"+typeName+"' contain white space";
	}

	if (typeName.contains("\t")) {
		return "Type '"+typeName+"' contain tab character";
	}

       if(SourceVersion.isKeyword(typeName)) {
		return "Type '"+typeName+"' is reserved java word";
	}

	byte[] bytes = typeName.getBytes();
	for (int i=0; i<bytes.length; i++)
	{
		byte b = bytes[i];
           boolean valid = (b == '_')
				|| (b >= '0' && b <= '9')
				|| (b >= 'a' && b <= 'z')
                   || (b >= 'A' && b <= 'Z');
           if(!valid) {
			return "Type '"+typeName+"' contain invalid character";
		}
	}
	Character.isJavaIdentifierStart(bytes[0]);

	if (bytes[0] == '_') {
		return "Type '"+typeName+"' start with invalid character '_'";
	}

	if (bytes[0] >= '0' && bytes[0] <= '9') {
		return "Type '"+typeName+"' start with a digit";
	}

	return null;
}
 
Example #28
Source File: ReferenceTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latest();
}
 
Example #29
Source File: ManagedAttributeValueTypeValidator.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion()
{
    return SourceVersion.latest();
}
 
Example #30
Source File: JackdawProcessor.java    From jackdaw with Apache License 2.0 4 votes vote down vote up
@Override
public final SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latestSupported();
}