Java Code Examples for org.eclipse.jdt.internal.compiler.impl.CompilerOptions#versionToJdkLevel()

The following examples show how to use org.eclipse.jdt.internal.compiler.impl.CompilerOptions#versionToJdkLevel() . 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: 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 2
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean filterEnum(SearchMatch match) {
	
	// filter org.apache.commons.lang.enum package for projects above 1.5 
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=317264	
	IJavaElement element = (IJavaElement)match.getElement();
	PackageFragment pkg = (PackageFragment)element.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
	if (pkg != null) {
		// enum was found in org.apache.commons.lang.enum at index 5
		if (pkg.names.length == 5 && pkg.names[4].equals("enum")) {  //$NON-NLS-1$
			if (this.options == null) {
				IJavaProject proj = (IJavaProject)pkg.getAncestor(IJavaElement.JAVA_PROJECT);
				String complianceStr = proj.getOption(CompilerOptions.OPTION_Source, true);
				if (CompilerOptions.versionToJdkLevel(complianceStr) >= ClassFileConstants.JDK1_5)
					return true;
			} else if (this.options.sourceLevel >= ClassFileConstants.JDK1_5) {
				return true;
			}
		}
	}
	return false;
}
 
Example 3
Source File: JavaModelManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private int indexForSourceLevel(String sourceLevel) {
	if (sourceLevel == null) return 0;
	int majVersion = (int) (CompilerOptions.versionToJdkLevel(sourceLevel) >>> 16);
	switch (majVersion) {
		case ClassFileConstants.MAJOR_VERSION_1_2:
			return 1;
		case ClassFileConstants.MAJOR_VERSION_1_3:
			return 2;
		case ClassFileConstants.MAJOR_VERSION_1_4:
			return 3;
		case ClassFileConstants.MAJOR_VERSION_1_5:
			return 4;
		case ClassFileConstants.MAJOR_VERSION_1_6:
			return 5;
		case ClassFileConstants.MAJOR_VERSION_1_7:
			return 6;
		case ClassFileConstants.MAJOR_VERSION_1_8:
			return 7;
		default:
			// all other cases including ClassFileConstants.MAJOR_VERSION_1_1
			return 0;
	}
}
 
Example 4
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 5
Source File: CompilationUnitProblemFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add additional source types
 */
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
	// ensure to jump back to toplevel type for first one (could be a member)
	while (sourceTypes[0].getEnclosingType() != null) {
		sourceTypes[0] = sourceTypes[0].getEnclosingType();
	}

	CompilationResult result =
		new CompilationResult(sourceTypes[0].getFileName(), 1, 1, this.options.maxProblemsPerUnit);
	
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=305259, build the compilation unit in its own sand box.
	final long savedComplianceLevel = this.options.complianceLevel;
	final long savedSourceLevel = this.options.sourceLevel;
	
	try {
		IJavaProject project = ((SourceTypeElementInfo) sourceTypes[0]).getHandle().getJavaProject();
		this.options.complianceLevel = CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_COMPLIANCE, true));
		this.options.sourceLevel = CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_SOURCE, true));

		// need to hold onto this
		CompilationUnitDeclaration unit =
			SourceTypeConverter.buildCompilationUnit(
					sourceTypes,//sourceTypes[0] is always toplevel here
					SourceTypeConverter.FIELD_AND_METHOD // need field and methods
					| SourceTypeConverter.MEMBER_TYPE // need member types
					| SourceTypeConverter.FIELD_INITIALIZATION, // need field initialization
					this.lookupEnvironment.problemReporter,
					result);

		if (unit != null) {
			this.lookupEnvironment.buildTypeBindings(unit, accessRestriction);
			this.lookupEnvironment.completeTypeBindings(unit);
		}
	} finally {
		this.options.complianceLevel = savedComplianceLevel;
		this.options.sourceLevel = savedSourceLevel;
	}
}
 
Example 6
Source File: CodeSnippetEvaluator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private CodeSnippetToCuMapper getMapper() {
	if (this.mapper == null) {
		char[] varClassName = null;
		VariablesInfo installedVars = this.context.installedVars;
		if (installedVars != null) {
			char[] superPackageName = installedVars.packageName;
			if (superPackageName != null && superPackageName.length != 0) {
				varClassName = CharOperation.concat(superPackageName, installedVars.className, '.');
			} else {
				varClassName = installedVars.className;
			}

		}
		this.mapper = new CodeSnippetToCuMapper(
			this.codeSnippet,
			this.context.packageName,
			this.context.imports,
			getClassName(),
			varClassName,
			this.context.localVariableNames,
			this.context.localVariableTypeNames,
			this.context.localVariableModifiers,
			this.context.declaringTypeName,
			this.context.lineSeparator,
			CompilerOptions.versionToJdkLevel(this.options.get(JavaCore.COMPILER_COMPLIANCE))
		);

	}
	return this.mapper;
}
 
Example 7
Source File: ToolFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Create a scanner, indicating the level of detail requested for tokenizing. The scanner can then be
 * used to tokenize some source in a Java aware way.
 * Here is a typical scanning loop:
 *
 * <code>
 * <pre>
 *   IScanner scanner = ToolFactory.createScanner(false, false, false, false);
 *   scanner.setSource("int i = 0;".toCharArray());
 *   while (true) {
 *     int token = scanner.getNextToken();
 *     if (token == ITerminalSymbols.TokenNameEOF) break;
 *     System.out.println(token + " : " + new String(scanner.getCurrentTokenSource()));
 *   }
 * </pre>
 * </code>
 *
 * <p>By default the compliance used to create the scanner is the workspace's compliance when running inside the IDE
 * or 1.4 if running from outside of a headless eclipse.
 * </p>
 *
 * @param tokenizeComments if set to <code>false</code>, comments will be silently consumed
 * @param tokenizeWhiteSpace if set to <code>false</code>, white spaces will be silently consumed,
 * @param assertMode if set to <code>false</code>, occurrences of 'assert' will be reported as identifiers
 * ({@link ITerminalSymbols#TokenNameIdentifier}), whereas if set to <code>true</code>, it
 * would report assert keywords ({@link ITerminalSymbols#TokenNameassert}). Java 1.4 has introduced
 * a new 'assert' keyword.
 * @param recordLineSeparator if set to <code>true</code>, the scanner will record positions of encountered line
 * separator ends. In case of multi-character line separators, the last character position is considered. These positions
 * can then be extracted using {@link IScanner#getLineEnds()}. Only non-unicode escape sequences are
 * considered as valid line separators.
 	 * @return a scanner
 * @see org.eclipse.jdt.core.compiler.IScanner
 * @see #createScanner(boolean, boolean, boolean, String, String)
 */
public static IScanner createScanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, boolean assertMode, boolean recordLineSeparator){
	// use default workspace compliance
	long complianceLevelValue = CompilerOptions.versionToJdkLevel(JavaCore.getOption(JavaCore.COMPILER_COMPLIANCE));
	if (complianceLevelValue == 0) complianceLevelValue = ClassFileConstants.JDK1_4; // fault-tolerance
	PublicScanner scanner =
		new PublicScanner(
			tokenizeComments,
			tokenizeWhiteSpace,
			false/*nls*/,
			assertMode ? ClassFileConstants.JDK1_4 : ClassFileConstants.JDK1_3/*sourceLevel*/,
			complianceLevelValue,
			null/*taskTags*/,
			null/*taskPriorities*/,
			true/*taskCaseSensitive*/);
	scanner.recordLineSeparator = recordLineSeparator;
	return scanner;
}
 
Example 8
Source File: ToolFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Create a scanner, indicating the level of detail requested for tokenizing. The scanner can then be
 * used to tokenize some source in a Java aware way.
 * Here is a typical scanning loop:
 *
 * <code>
 * <pre>
 *   IScanner scanner = ToolFactory.createScanner(false, false, false, false);
 *   scanner.setSource("int i = 0;".toCharArray());
 *   while (true) {
 *     int token = scanner.getNextToken();
 *     if (token == ITerminalSymbols.TokenNameEOF) break;
 *     System.out.println(token + " : " + new String(scanner.getCurrentTokenSource()));
 *   }
 * </pre>
 * </code>
 *
 * <p>By default the compliance used to create the scanner is the workspace's compliance when running inside the IDE
 * or 1.4 if running from outside of a headless eclipse.
 * </p>
 *
 * @param tokenizeComments if set to <code>false</code>, comments will be silently consumed
 * @param tokenizeWhiteSpace if set to <code>false</code>, white spaces will be silently consumed,
 * @param recordLineSeparator if set to <code>true</code>, the scanner will record positions of encountered line
 * separator ends. In case of multi-character line separators, the last character position is considered. These positions
 * can then be extracted using {@link IScanner#getLineEnds()}. Only non-unicode escape sequences are
 * considered as valid line separators.
 * @param sourceLevel if set to <code>&quot;1.3&quot;</code> or <code>null</code>, occurrences of 'assert' will be reported as identifiers
 * ({@link ITerminalSymbols#TokenNameIdentifier}), whereas if set to <code>&quot;1.4&quot;</code>, it
 * would report assert keywords ({@link ITerminalSymbols#TokenNameassert}). Java 1.4 has introduced
 * a new 'assert' keyword.
 * @return a scanner
 * @see org.eclipse.jdt.core.compiler.IScanner
 * @see #createScanner(boolean, boolean, boolean, String, String)
 * @since 3.0
 */
public static IScanner createScanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, boolean recordLineSeparator, String sourceLevel) {
	// use default workspace compliance
	long complianceLevelValue = CompilerOptions.versionToJdkLevel(JavaCore.getOption(JavaCore.COMPILER_COMPLIANCE));
	if (complianceLevelValue == 0) complianceLevelValue = ClassFileConstants.JDK1_4; // fault-tolerance
	long sourceLevelValue = CompilerOptions.versionToJdkLevel(sourceLevel);
	if (sourceLevelValue == 0) sourceLevelValue = ClassFileConstants.JDK1_3; // fault-tolerance
	PublicScanner scanner =
		new PublicScanner(
			tokenizeComments,
			tokenizeWhiteSpace,
			false/*nls*/,
			sourceLevelValue /*sourceLevel*/,
			complianceLevelValue,
			null/*taskTags*/,
			null/*taskPriorities*/,
			true/*taskCaseSensitive*/);
	scanner.recordLineSeparator = recordLineSeparator;
	return scanner;
}
 
Example 9
Source File: EvaluationContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Computes the selection at the specified positions of the given code snippet.
 * (Note that this evaluation context's VM doesn't need to be running.)
 *  @param codeSnippet char[]
 * 		The code snipper source
 *
 *  @param selectionSourceStart int
 *
 *  @param selectionSourceEnd int
 *
 *  @param environment org.eclipse.jdt.internal.core.SearchableEnvironment
 *      used to resolve type/package references and search for types/packages
 *      based on partial names.
 *
 *  @param requestor org.eclipse.jdt.internal.codeassist.ISelectionRequestor
 *      since the engine might produce answers of various forms, the engine
 *      is associated with a requestor able to accept all possible selections.
 *
 *  @param options java.util.Map
 *		set of options used to configure the code assist engine.
 */
public void select(
	char[] codeSnippet,
	int selectionSourceStart,
	int selectionSourceEnd,
	SearchableEnvironment environment,
	ISelectionRequestor requestor,
	Map options,
	WorkingCopyOwner owner) {

	final char[] className = "CodeSnippetSelection".toCharArray(); //$NON-NLS-1$
	final long complianceVersion = CompilerOptions.versionToJdkLevel(options.get(JavaCore.COMPILER_COMPLIANCE));
	final CodeSnippetToCuMapper mapper = new CodeSnippetToCuMapper(
		codeSnippet,
		this.packageName,
		this.imports,
		className,
		this.installedVars == null ? null : this.installedVars.className,
		this.localVariableNames,
		this.localVariableTypeNames,
		this.localVariableModifiers,
		this.declaringTypeName,
		this.lineSeparator,
		complianceVersion
	);
	ICompilationUnit sourceUnit = new ICompilationUnit() {
		public char[] getFileName() {
			return CharOperation.concat(className, Util.defaultJavaExtension().toCharArray());
		}
		public char[] getContents() {
			return mapper.getCUSource(EvaluationContext.this.lineSeparator);
		}
		public char[] getMainTypeName() {
			return className;
		}
		public char[][] getPackageName() {
			return null;
		}
		public boolean ignoreOptionalProblems() {
			return false;
		}
	};
	SelectionEngine engine = new SelectionEngine(environment, mapper.getSelectionRequestor(requestor), options, owner);
	engine.select(sourceUnit, mapper.startPosOffset + selectionSourceStart, mapper.startPosOffset + selectionSourceEnd);
}