Java Code Examples for javax.lang.model.SourceVersion

The following examples show how to use javax.lang.model.SourceVersion. These examples are extracted from open source projects. 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 Project: jetbrick-template-1x   Author: subchen   File: JetTemplateCodeVisitor.java    License: 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 #2
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: T6395981.java    License: 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 Project: auto   Author: google   File: GeneratedDoesNotExistTest.java    License: 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 #4
Source Project: buck   Author: facebook   File: SourceVersionUtils.java    License: 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 #5
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: ClassReader.java    License: 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 #6
Source Project: hottub   Author: dsrg-uoft   File: T6395981.java    License: 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 #7
Source Project: TencentKona-8   Author: Tencent   File: T6395981.java    License: 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 #8
Source Project: jdk8u60   Author: chenghanpeng   File: T6395981.java    License: 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 #9
Source Project: openjdk-8-source   Author: keerath   File: JavaCompiler.java    License: 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 #10
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: Arguments.java    License: 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 #11
Source Project: buck   Author: facebook   File: ClassVisitorDriverFromElement.java    License: 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 #12
Source Project: openjdk-8   Author: bpupadhyaya   File: JavacProcessingEnvironment.java    License: 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 #13
Source Project: celerio   Author: jaxio   File: PackageUtil.java    License: 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 #14
Source Project: netbeans   Author: apache   File: ConvertSwitchToRuleSwitchTest.java    License: 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 #15
Source Project: netbeans   Author: apache   File: ReindenterTest.java    License: 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 #16
Source Project: netbeans   Author: apache   File: ReindenterTest.java    License: 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 #17
Source Project: openjdk-8   Author: bpupadhyaya   File: SchemaGenerator.java    License: 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 #18
Source Project: netbeans   Author: apache   File: DetectorTest.java    License: 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 #19
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: AbstractProcessor.java    License: 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 #20
Source Project: jdk8u60   Author: chenghanpeng   File: TestSourceVersion.java    License: 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 #21
Source Project: JReFrameworker   Author: JReFrameworker   File: CodeWriter.java    License: 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 #22
Source Project: hottub   Author: dsrg-uoft   File: AnnotationParser.java    License: 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 #23
Source Project: Prism4j   Author: noties   File: PrismBundler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.RELEASE_8;
}
 
Example #24
Source Project: bazel   Author: bazelbuild   File: JavacTurbineTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
  return SourceVersion.latest();
}
 
Example #25
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: TestTrees.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latest();
}
 
Example #26
Source Project: openjdk-8   Author: bpupadhyaya   File: TypeProcOnly.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latest();
}
 
Example #27
Source Project: ig-json-parser   Author: Instagram   File: JsonAnnotationProcessor.java    License: MIT License 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
  return SourceVersion.latestSupported();
}
 
Example #28
Source Project: SimpleWeibo   Author: 8tory   File: CompilationTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
  return SourceVersion.latestSupported();
}
 
Example #29
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: Example.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    // support the latest release
    return SourceVersion.latest();
}
 
Example #30
Source Project: openjdk-8   Author: bpupadhyaya   File: TestGetElement.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latest();
}