Java Code Examples for org.eclipse.jdt.core.JavaCore#setComplianceOptions()

The following examples show how to use org.eclipse.jdt.core.JavaCore#setComplianceOptions() . 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: JavaFile.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
public static CompilationUnit genASTFromSource(String icu, String[] classPath, String[] sourcePath){
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setResolveBindings(true);
		parser.setBindingsRecovery(true);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		Map<?, ?> options = JavaCore.getOptions();
		JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
		parser.setCompilerOptions(options);
 
//		String[] sources = { "C:\\Users\\pc\\workspace\\asttester\\src" }; 
//		String[] classpath = {"C:\\Program Files\\Java\\jre1.8.0_25\\lib\\rt.jar"};
 
		parser.setEnvironment(classPath, sourcePath, new String[] { "UTF-8"}, true);
		parser.setSource(icu.toCharArray());
		return (CompilationUnit) parser.createAST(null);
	}
 
Example 2
Source File: Java7BaseTest.java    From compiler with Apache License 2.0 6 votes vote down vote up
protected static void dumpJava(final String content) {
	final ASTParser parser = ASTParser.newParser(astLevel);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(content.toCharArray());

	final Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(javaVersion, options);
	parser.setCompilerOptions(options);

	final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

	try {
		final UglyMathCommentsExtractor cex = new UglyMathCommentsExtractor(cu, content);
		final ASTDumper dumper = new ASTDumper(cex);
		dumper.dump(cu);
		cex.close();
	} catch (final Exception e) {}
}
 
Example 3
Source File: ASTParserFactory.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected final ASTParser createDefaultJavaParser(final String javaVersion) {
  ASTParser parser = null;
  final Hashtable<String, String> options = JavaCore.getOptions();
  try {
    parser = ASTParser.newParser(ASTParserFactory.asJLS(javaVersion));
    JavaCore.setComplianceOptions(javaVersion, options);
  } catch (final Throwable _t) {
    if (_t instanceof IllegalArgumentException) {
      parser = ASTParser.newParser(ASTParserFactory.asJLS(this.minParserApiLevel));
      JavaCore.setComplianceOptions(this.minParserApiLevel, options);
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
  options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
  parser.setCompilerOptions(options);
  parser.setStatementsRecovery(true);
  parser.setResolveBindings(true);
  parser.setBindingsRecovery(true);
  return parser;
}
 
Example 4
Source File: TestOptions.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static Hashtable<String, String> getDefaultOptions() {
	Hashtable<String, String> result = JavaCore.getDefaultOptions();
	result.put(JavaCore.COMPILER_PB_LOCAL_VARIABLE_HIDING, JavaCore.IGNORE);
	result.put(JavaCore.COMPILER_PB_FIELD_HIDING, JavaCore.IGNORE);
	result.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.IGNORE);
	result.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.IGNORE);
	result.put(JavaCore.COMPILER_PB_RAW_TYPE_REFERENCE, JavaCore.IGNORE);
	result.put(JavaCore.COMPILER_PB_UNUSED_WARNING_TOKEN, JavaCore.IGNORE);
	result.put(JavaCore.COMPILER_PB_DEAD_CODE, JavaCore.IGNORE);
	result.put(JavaCore.COMPILER_PB_UNUSED_IMPORT, JavaCore.ERROR);

	result.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);
	result.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4");

	JavaCore.setComplianceOptions("1.8", result);

	return result;
}
 
Example 5
Source File: JVMConfigurator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void configureJVMSettings(IJavaProject javaProject, IVMInstall vmInstall) {
	if (javaProject == null) {
		return;
	}
	String version = "";
	if (vmInstall instanceof AbstractVMInstall) {
		AbstractVMInstall jvm = (AbstractVMInstall) vmInstall;
		version = jvm.getJavaVersion();
		long jdkLevel = CompilerOptions.versionToJdkLevel(jvm.getJavaVersion());
		String compliance = CompilerOptions.versionFromJdkLevel(jdkLevel);
		Map<String, String> options = javaProject.getOptions(false);
		JavaCore.setComplianceOptions(compliance, options);
	}
	;
	if (JavaCore.compareJavaVersions(version, JavaCore.latestSupportedJavaVersion()) >= 0) {
		//Enable Java preview features for the latest JDK release by default and stfu about it
		javaProject.setOption(JavaCore.COMPILER_PB_ENABLE_PREVIEW_FEATURES, JavaCore.ENABLED);
		javaProject.setOption(JavaCore.COMPILER_PB_REPORT_PREVIEW_FEATURES, JavaCore.IGNORE);
	} else {
		javaProject.setOption(JavaCore.COMPILER_PB_ENABLE_PREVIEW_FEATURES, JavaCore.DISABLED);
	}

}
 
Example 6
Source File: ASTGenerator.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
public static ASTNode genAST(String source, int type){
	ASTParser astParser = ASTParser.newParser(AST.JLS8);
	Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
	astParser.setCompilerOptions(options);
	astParser.setSource(source.toCharArray());
	astParser.setKind(type);
	astParser.setResolveBindings(true);
	return astParser.createAST(null);
}
 
Example 7
Source File: BaseBuilderGeneratorIT.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
protected CompilationUnit parseAst(char[] source) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source);
    Map options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_5, options);
    parser.setCompilerOptions(options);
    CompilationUnit result = (CompilationUnit) parser.createAST(null);
    return result;
}
 
Example 8
Source File: JVMConfigurator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void defaultVMInstallChanged(IVMInstall previous, IVMInstall current) {
	if (Objects.equals(previous, current)) {
		return;
	}
	String prev = (previous == null) ? null : previous.getId() + "-" + previous.getInstallLocation();
	String curr = (current == null) ? null : current.getId() + "-" + current.getInstallLocation();

	JavaLanguageServerPlugin.logInfo("Default VM Install changed from  " + prev + " to " + curr);

	//Reset global compliance settings
	AbstractVMInstall jvm = (AbstractVMInstall) current;
	long jdkLevel = CompilerOptions.versionToJdkLevel(jvm.getJavaVersion());
	String compliance = CompilerOptions.versionFromJdkLevel(jdkLevel);
	Hashtable<String, String> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(compliance, options);
	JavaCore.setOptions(options);

	IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
	for (IProject project : projects) {
		if (!ProjectUtils.isVisibleProject(project) && ProjectUtils.isJavaProject(project)) {
			IJavaProject javaProject = JavaCore.create(project);
			configureJVMSettings(javaProject, current);
		}
		ProjectsManager projectsManager = JavaLanguageServerPlugin.getProjectsManager();
		if (projectsManager != null) {
			//TODO Only trigger update if the project uses the default JVM
			JavaLanguageServerPlugin.logInfo("defaultVMInstallChanged -> force update of " + project.getName());
			projectsManager.updateProject(project, true);
		}
	}
}
 
Example 9
Source File: Utils.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
public static ASTNode genASTFromSource(String icu, int type) {
	ASTParser astParser = ASTParser.newParser(AST.JLS8);
	Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
	astParser.setCompilerOptions(options);
	astParser.setSource(icu.toCharArray());
	astParser.setKind(type);
	astParser.setResolveBindings(true);
	astParser.setBindingsRecovery(true);
	return astParser.createAST(null);
}
 
Example 10
Source File: TestVMType.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static void setTestJREAsDefault(String vmId) throws CoreException {
	IVMInstallType vmInstallType = JavaRuntime.getVMInstallType(VMTYPE_ID);
	IVMInstall testVMInstall = vmInstallType.findVMInstall(vmId);
	if (!testVMInstall.equals(JavaRuntime.getDefaultVMInstall())) {
		// set the 1.8 test JRE as the new default JRE
		JavaRuntime.setDefaultVMInstall(testVMInstall, new NullProgressMonitor());
		Hashtable<String, String> options = JavaCore.getOptions();
		JavaCore.setComplianceOptions(vmId, options);
		JavaCore.setOptions(options);
	}
	JDTUtils.setCompatibleVMs(VMTYPE_ID);
}
 
Example 11
Source File: JavaFile.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * generate {@code CompilationUnit} from source code based on the specific
 * type (e.g., {@code ASTParser.K_COMPILATION_UNIT})
 * 
 * @param icu
 * @param type
 * @return
 */
public static ASTNode genASTFromSource(String icu, int type) {
	ASTParser astParser = ASTParser.newParser(AST.JLS8);
	Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
	astParser.setCompilerOptions(options);
	astParser.setSource(icu.toCharArray());
	astParser.setKind(type);
	astParser.setResolveBindings(true);
	astParser.setBindingsRecovery(true);
	return astParser.createAST(null);
}
 
Example 12
Source File: JavaFile.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * generate {@code CompilationUnit} from {@code ICompilationUnit}
 * 
 * @param icu
 * @return
 */
public static CompilationUnit genASTFromICU(ICompilationUnit icu) {
	ASTParser astParser = ASTParser.newParser(AST.JLS8);
	Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
	astParser.setCompilerOptions(options);
	astParser.setSource(icu);
	astParser.setKind(ASTParser.K_COMPILATION_UNIT);
	astParser.setResolveBindings(true);
	return (CompilationUnit) astParser.createAST(null);
}
 
Example 13
Source File: UMLModelASTReader.java    From RefactoringMiner with MIT License 5 votes vote down vote up
private static ASTParser buildAstParser(File srcFolder) {
	ASTParser parser = ASTParser.newParser(AST.JLS11);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	Map<String, String> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
	parser.setCompilerOptions(options);
	parser.setResolveBindings(false);
	parser.setEnvironment(new String[0], new String[]{srcFolder.getPath()}, null, false);
	return parser;
}
 
Example 14
Source File: JavaASTUtil.java    From compiler with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static ASTParser buildParser(FileKind fileKind) {
	int astLevel = -1;
	String compliance = null;
	switch (fileKind) {
	case SOURCE_JAVA_JLS2:
		astLevel = AST.JLS2;
		compliance = JavaCore.VERSION_1_4;
		break;
	case SOURCE_JAVA_JLS3:
		astLevel = AST.JLS3;
		compliance = JavaCore.VERSION_1_5;
		break;
	case SOURCE_JAVA_JLS4:
		astLevel = AST.JLS4;
		compliance = JavaCore.VERSION_1_7;
		break;
	case SOURCE_JAVA_JLS8:
		astLevel = AST.JLS8;
		compliance = JavaCore.VERSION_1_8;
		break;
	default:
		break;
	}
	if (compliance != null) {
		ASTParser parser = ASTParser.newParser(astLevel);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);

		final Map<?, ?> options = JavaCore.getOptions();
		JavaCore.setComplianceOptions(compliance, options);
		parser.setCompilerOptions(options);
		return parser;
	}
	return null;
}
 
Example 15
Source File: BoaAstIntrinsics.java    From compiler with Apache License 2.0 5 votes vote down vote up
@FunctionSpec(name = "parse", returnType = "ASTRoot", formalParameters = { "string" })
public static ASTRoot parse(final String s) {
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(s.toCharArray());

	@SuppressWarnings("rawtypes")
	final Map options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
	parser.setCompilerOptions(options);

	final ASTRoot.Builder ast = ASTRoot.newBuilder();
	try {
		final org.eclipse.jdt.core.dom.CompilationUnit cu = (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(null);
		final JavaErrorCheckVisitor errorCheck = new JavaErrorCheckVisitor();
		cu.accept(errorCheck);

		if (!errorCheck.hasError) {
			final JavaVisitor visitor = new JavaVisitor(s);
			ast.addNamespaces(visitor.getNamespaces(cu));
		}
	} catch (final Exception e) {
		// do nothing
	}

	return ast.build();
}
 
Example 16
Source File: ReferencedClassesParser.java    From BUILD_file_generator with Apache License 2.0 5 votes vote down vote up
private static ASTParser createCompilationUnitParser() {
  ASTParser parser = ASTParser.newParser(AST.JLS8);
  Map options = JavaCore.getOptions();
  JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
  parser.setCompilerOptions(options);
  parser.setKind(ASTParser.K_COMPILATION_UNIT);
  return parser;
}
 
Example 17
Source File: JavaFileParser.java    From buck with Apache License 2.0 5 votes vote down vote up
private CompilationUnit makeCompilationUnitFromSource(String code) {
  ASTParser parser = ASTParser.newParser(jlsLevel);
  parser.setSource(code.toCharArray());
  parser.setKind(ASTParser.K_COMPILATION_UNIT);

  Map<String, String> options = JavaCore.getOptions();
  JavaCore.setComplianceOptions(javaVersion, options);
  parser.setCompilerOptions(options);

  return (CompilationUnit) parser.createAST(/* monitor */ null);
}
 
Example 18
Source File: TranslateNodeTest.java    From juniversal with MIT License 5 votes vote down vote up
public CompilationUnit parseCompilationUnit(String java) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    parser.setSource(java.toCharArray()); // set source
    parser.setResolveBindings(true); // we need bindings later on
    parser.setEnvironment(new String[0], new String[0], null, true);
    parser.setUnitName("TestClass.java");

    // In order to parse 1.8 code, some compiler options need to be set to 1.8
    Map options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
    parser.setCompilerOptions(options);

    CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null /* IProgressMonitor */);

    IProblem[] problems = compilationUnit.getProblems();
    if (problems.length > 0) {
        StringBuilder problemsText = new StringBuilder();

        for (IProblem problem : problems) {
            if (problem.isError()) {
                problemsText.append(problem.getMessage() + "\n");
            }
        }

        if (problemsText.length() > 0)
            throw new RuntimeException(problemsText.toString());
    }

    return compilationUnit;
}
 
Example 19
Source File: JavadocQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testInvalidQualification1() throws Exception {
	Map<String, String> original = fJProject1.getOptions(false);
	HashMap<String, String> newOptions = new HashMap<>(original);
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_4, newOptions);
	fJProject1.setOptions(newOptions);

	IPackageFragment pack1 = fSourceFolder.createPackageFragment("pack", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package pack;\n");
	buf.append("\n");
	buf.append("public class A {\n");
	buf.append("    public static class B {\n");
	buf.append("        public static class C {\n");
	buf.append("            \n");
	buf.append("        }\n");
	buf.append("    }\n");
	buf.append("}\n");
	pack1.createCompilationUnit("A.java", buf.toString(), false, null);

	IPackageFragment pack2 = fSourceFolder.createPackageFragment("pack2", false, null);
	buf = new StringBuilder();
	buf.append("package pack2;\n");
	buf.append("\n");
	buf.append("import pack.A.B.C;\n");
	buf.append("\n");
	buf.append("/**\n");
	buf.append(" * {@link C} \n");
	buf.append(" */\n");
	buf.append("public class E {\n");
	buf.append("}\n");
	ICompilationUnit cu = pack2.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package pack2;\n");
	buf.append("\n");
	buf.append("import pack.A.B.C;\n");
	buf.append("\n");
	buf.append("/**\n");
	buf.append(" * {@link pack.A.B.C} \n");
	buf.append(" */\n");
	buf.append("public class E {\n");
	buf.append("}\n");
	Expected e1 = new Expected("Qualify inner type name", buf.toString());
	assertCodeActions(cu, e1);
}
 
Example 20
Source File: Translator.java    From juniversal with MIT License 4 votes vote down vote up
/**
   * Translate all source files configured for the translator.   If a user errors occurs during translation for a file
   * (e.g. a SourceNotSupported exception is thrown), an error message is output for that file, the translation
   * continues on with remaining files, and false is eventually returned from this method as the translate failed.  If
   * an internal occurs during translation (e.g. the translator has a bug), an exception is thrown.
   *
   * @return true if all files were translated without error, false if some failed
   */
  public boolean translate() {
      ASTParser parser = ASTParser.newParser(AST.JLS8);
      parser.setKind(ASTParser.K_COMPILATION_UNIT);
      //parser.setEnvironment(new String[0], new String[0], null, false);
      //TODO: Set classpath & sourcepath differently probably; this just uses the current VM (I think), but I can
      //see that it doesn't resolve everything for some reason
      parser.setEnvironment(classpath, sourcepath, null, true);
      parser.setResolveBindings(true);

      Map options = JavaCore.getOptions();
      JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
      parser.setCompilerOptions(options);

      Var<Boolean> failed = new Var<>(false);

      FileASTRequestor astRequestor = new FileASTRequestor() {
          public void acceptAST(String sourceFilePath, CompilationUnit compilationUnit) {
              SourceFile sourceFile = new SourceFile(compilationUnit, new File(sourceFilePath), sourceTabStop);

              //boolean outputErrorForFile = false;
              for (IProblem problem : compilationUnit.getProblems()) {
                  if (problem.isError()) {
                      System.err.println("Error: " + problem.getMessage());
                      System.err.println(sourceFile.getPositionDescription(problem.getSourceStart()));
                  }
              }

              // Translate each file as it's returned; if a user error occurs while translating (e.g. a
              // SourceNotSupported exception is thrown), print the message for that, note the failure, and continue
              // on
              System.out.println("Translating " + sourceFilePath);
              try {
                  translateFile(sourceFile);
              } catch (UserViewableException e) {
                  System.err.println("Error: " + e.getMessage());
                  failed.set(true);
              }
          }
      };

      parser.createASTs(getJavaFiles(), null, new String[0], astRequestor, null);

      return !failed.value();

/*
       * String source = readFile(jUniversal.getJavaProjectDirectories().get(0).getPath());
 * parser.setSource(source.toCharArray());
 *
 * CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
 *
 *
 * TypeDeclaration typeDeclaration = ASTUtil.getFirstTypeDeclaration(compilationUnit);
 *
 * FileWriter writer; try { writer = new FileWriter(jUniversal.getOutputDirectory()); }
 * catch (IOException e) { throw new RuntimeException(e);   }
 *
 * CPPProfile profile = new CPPProfile(); // profile.setTabStop(4);
 *
 * CPPWriter cppWriter = new CPPWriter(writer, profile);
 *
 * Context context = new Context((CompilationUnit) compilationUnit.getRoot(), source, 8,
 * profile, cppWriter, OutputType.SOURCE);
 *
 * context.setPosition(typeDeclaration.getStartPosition());
 *
 * ASTWriters astWriters = new ASTWriters();
 *
 * try { context.setPosition(typeDeclaration.getStartPosition());
 * skipSpaceAndComments();
 *
 * astWriters.writeNode(typeDeclaration, context); } catch (UserViewableException e) {
 * System.err.println(e.getMessage()); System.exit(1); } catch (RuntimeException e) { if (e
 * instanceof ContextPositionMismatchException) throw e; else throw new
 * JUniversalException(e.getMessage() + "\nError occurred with context at position\n" +
 * context.getPositionDescription(context.getPosition()), e); }
 *
 * try { writer.close(); } catch (IOException e) { throw new RuntimeException(e); }
 */
  }