org.eclipse.jdt.internal.compiler.CompilationResult Java Examples

The following examples show how to use org.eclipse.jdt.internal.compiler.CompilationResult. 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: CompilationUtils.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * <p>compileSource.</p>
 *
 * @param source a {@link java.lang.String} object.
 * @return a {@link ch.uzh.ifi.seal.changedistiller.ast.java.JavaCompilation} object.
 */
public static JavaCompilation compileSource(String source) {

	//Compiler Options
    CompilerOptions options = getDefaultCompilerOptions();

    //CommentRecorder
    Parser parser = createCommentRecorderParser(options);

    //Create Compilation Unit from Source
    ICompilationUnit cu = createCompilationunit(source, "");

    //Compilation Result
    CompilationResult compilationResult = createDefaultCompilationResult(cu, options);

    return new JavaCompilation(parser.parse(cu, compilationResult), parser.scanner);
}
 
Example #2
Source File: Evaluator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the evaluation results that converts the given compilation result that has problems.
 * If the compilation result has more than one problem, then the problems are broken down so that
 * each evaluation result has the same evaluation id.
 */
protected EvaluationResult[] evaluationResultsForCompilationProblems(CompilationResult result, char[] cuSource) {
	// Break down the problems and group them by ids in evaluation results
	CategorizedProblem[] problems = result.getAllProblems();
	HashMap resultsByIDs = new HashMap(5);
	for (int i = 0; i < problems.length; i++) {
		addEvaluationResultForCompilationProblem(resultsByIDs, problems[i], cuSource);
	}

	// Copy results
	int size = resultsByIDs.size();
	EvaluationResult[] evalResults = new EvaluationResult[size];
	Iterator results = resultsByIDs.values().iterator();
	for (int i = 0; i < size; i++) {
		evalResults[i] = (EvaluationResult)results.next();
	}

	return evalResults;
}
 
Example #3
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Add additional source types
 */
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
	// case of SearchableEnvironment of an IJavaProject is used
	ISourceType sourceType = sourceTypes[0];
	while (sourceType.getEnclosingType() != null)
		sourceType = sourceType.getEnclosingType();
	if (sourceType instanceof SourceTypeElementInfo) {
		// get source
		SourceTypeElementInfo elementInfo = (SourceTypeElementInfo) sourceType;
		IType type = elementInfo.getHandle();
		ICompilationUnit sourceUnit = (ICompilationUnit) type.getCompilationUnit();
		accept(sourceUnit, accessRestriction);
	} else {
		CompilationResult result = new CompilationResult(sourceType.getFileName(), 1, 1, 0);
		CompilationUnitDeclaration unit =
			SourceTypeConverter.buildCompilationUnit(
				sourceTypes,
				SourceTypeConverter.FIELD_AND_METHOD // need field and methods
				| SourceTypeConverter.MEMBER_TYPE, // need member types
				// no need for field initialization
				this.lookupEnvironment.problemReporter,
				result);
		this.lookupEnvironment.buildTypeBindings(unit, accessRestriction);
		this.lookupEnvironment.completeTypeBindings(unit, true);
	}
}
 
Example #4
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Add an additional compilation unit into the loop
 *  ->  build compilation unit declarations, their bindings and record their results.
 */
public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {
	// Switch the current policy and compilation result for this unit to the requested one.
	CompilationResult unitResult = new CompilationResult(sourceUnit, 1, 1, this.options.maxProblemsPerUnit);
	try {
		CompilationUnitDeclaration parsedUnit = basicParser().dietParse(sourceUnit, unitResult);
		this.lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);
		this.lookupEnvironment.completeTypeBindings(parsedUnit, true);
	} catch (AbortCompilationUnit e) {
		// at this point, currentCompilationUnitResult may not be sourceUnit, but some other
		// one requested further along to resolve sourceUnit.
		if (unitResult.compilationUnit == sourceUnit) { // only report once
			//requestor.acceptResult(unitResult.tagAsAccepted());
		} else {
			throw e; // want to abort enclosing request to compile
		}
	}
	// Display unit error in debug mode
	if (BasicSearchEngine.VERBOSE) {
		if (unitResult.problemCount > 0) {
			System.out.println(unitResult);
		}
	}
}
 
Example #5
Source File: SuperTypeNamesCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected CompilationUnitDeclaration buildBindings(ICompilationUnit compilationUnit, boolean isTopLevelOrMember) throws JavaModelException {
	// source unit
	org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) compilationUnit;

	CompilationResult compilationResult = new CompilationResult(sourceUnit, 1, 1, 0);
	CompilationUnitDeclaration unit =
		isTopLevelOrMember ?
			this.locator.basicParser().dietParse(sourceUnit, compilationResult) :
			this.locator.basicParser().parse(sourceUnit, compilationResult);
	if (unit != null) {
		this.locator.lookupEnvironment.buildTypeBindings(unit, null /*no access restriction*/);
		this.locator.lookupEnvironment.completeTypeBindings(unit, !isTopLevelOrMember);
		if (!isTopLevelOrMember) {
			if (unit.scope != null)
				unit.scope.faultInTypes(); // fault in fields & methods
			unit.resolve();
		}
	}
	return unit;
}
 
Example #6
Source File: SourceTypeConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static CompilationUnitDeclaration buildCompilationUnit(
		ISourceType[] sourceTypes,
		int flags,
		ProblemReporter problemReporter,
		CompilationResult compilationResult) {

//		long start = System.currentTimeMillis();
		SourceTypeConverter converter = new SourceTypeConverter(flags, problemReporter);
		try {
			return converter.convert(sourceTypes, compilationResult);
		} catch (JavaModelException e) {
			return null;
/*		} finally {
			System.out.println("Spent " + (System.currentTimeMillis() - start) + "ms to convert " + ((JavaElement) converter.cu).toStringWithAncestors());
*/		}
	}
 
Example #7
Source File: Main.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public ICompilerRequestor getBatchRequestor() {
	return new ICompilerRequestor() {
		int lineDelta = 0;
		public void acceptResult(CompilationResult compilationResult) {
			if (compilationResult.lineSeparatorPositions != null) {
				int unitLineCount = compilationResult.lineSeparatorPositions.length;
				this.lineDelta += unitLineCount;
				if (Main.this.showProgress && this.lineDelta > 2000) {
					// in -log mode, dump a dot every 2000 lines compiled
					Main.this.logger.logProgress();
					this.lineDelta = 0;
				}
			}
			Main.this.logger.startLoggingSource(compilationResult);
			if (compilationResult.hasProblems() || compilationResult.hasTasks()) {
				Main.this.logger.logProblems(compilationResult.getAllProblems(), compilationResult.compilationUnit.getContents(), Main.this);
			}
			outputClassFiles(compilationResult);
			Main.this.logger.endLoggingSource();
		}
	};
}
 
Example #8
Source File: FakedTrackingVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public String nameForReporting(ASTNode location, ReferenceContext referenceContext) {
	if (this.name == UNASSIGNED_CLOSEABLE_NAME) {
		if (location != null && referenceContext != null) {
			CompilationResult compResult = referenceContext.compilationResult();
			if (compResult != null) {
				int[] lineEnds = compResult.getLineSeparatorPositions();
				int resourceLine = Util.getLineNumber(this.sourceStart, lineEnds , 0, lineEnds.length-1);
				int reportLine = Util.getLineNumber(location.sourceStart, lineEnds , 0, lineEnds.length-1);
				if (resourceLine != reportLine) {
					char[] replacement = Integer.toString(resourceLine).toCharArray();
					return String.valueOf(CharOperation.replace(UNASSIGNED_CLOSEABLE_NAME_TEMPLATE, TEMPLATE_ARGUMENT, replacement));
				}
			}
		}
	}
	return String.valueOf(this.name);
}
 
Example #9
Source File: EclipseAstProblemView.java    From EasyMPermission with MIT License 6 votes vote down vote up
/**
 * Adds a problem to the provided CompilationResult object so that it will show up
 * in the Problems/Warnings view.
 */
public static void addProblemToCompilationResult(char[] fileNameArray, CompilationResult result,
		boolean isWarning, String message, int sourceStart, int sourceEnd) {
	if (result == null) return;
	if (fileNameArray == null) fileNameArray = "(unknown).java".toCharArray();
	int lineNumber = 0;
	int columnNumber = 1;
	int[] lineEnds = null;
	lineNumber = sourceStart >= 0
			? Util.getLineNumber(sourceStart, lineEnds = result.getLineSeparatorPositions(), 0, lineEnds.length-1)
			: 0;
	columnNumber = sourceStart >= 0
			? Util.searchColumnNumber(result.getLineSeparatorPositions(), lineNumber,sourceStart)
			: 0;
	
	CategorizedProblem ecProblem = new LombokProblem(
			fileNameArray, message, 0, new String[0],
			isWarning ? ProblemSeverities.Warning : ProblemSeverities.Error,
			sourceStart, sourceEnd, lineNumber, columnNumber);
	result.record(ecProblem, null);
}
 
Example #10
Source File: JDTJavaCompiler.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Invoke CompilationResult#getProblems safely so that it works with
 * 3.1.1 and more recent versions of the eclipse java compiler.
 * See https://jsp.dev.java.net/issues/show_bug.cgi?id=13
 * 
 * @param result The compilation result.
 * @return The same object than CompilationResult#getProblems
 */
private static final IProblem[] safeGetProblems(CompilationResult result) {
    if (!USE_INTROSPECTION_TO_INVOKE_GET_PROBLEM) {
        try {
            return result.getProblems();
        } catch (NoSuchMethodError re) {
            USE_INTROSPECTION_TO_INVOKE_GET_PROBLEM = true;
        }
    }
    try {
        if (GET_PROBLEM_METH == null) {
            GET_PROBLEM_METH = result.getClass()
                    .getDeclaredMethod("getProblems", new Class[] {});
        }
        //an array of a particular type can be casted into an array of a super type.
        return (IProblem[]) GET_PROBLEM_METH.invoke(result, null);
    } catch (Throwable e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException)e;
        } else {
            throw new RuntimeException(e);
        }
    }
}
 
Example #11
Source File: ProblemHandler.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Standard problem handling API, the actual severity (warning/error/ignore) is deducted
 * from the problem ID and the current compiler options.
 */
public void handle(
	int problemId,
	String[] problemArguments,
	String[] messageArguments,
	int problemStartPosition,
	int problemEndPosition,
	ReferenceContext referenceContext,
	CompilationResult unitResult) {

	this.handle(
		problemId,
		problemArguments,
		0, // no message elaboration
		messageArguments,
		computeSeverity(problemId), // severity inferred using the ID
		problemStartPosition,
		problemEndPosition,
		referenceContext,
		unitResult);
}
 
Example #12
Source File: JavaDerivedStateComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public void installStubs(Resource resource) {
	if (isInfoFile(resource)) {
		return;
	}
	CompilationUnit compilationUnit = getCompilationUnit(resource);
	ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
			getCompilerOptions(resource), new DefaultProblemFactory());
	Parser parser = new Parser(problemReporter, true);
	CompilationResult compilationResult = new CompilationResult(compilationUnit, 0, 1, -1);
	CompilationUnitDeclaration result = parser.dietParse(compilationUnit, compilationResult);
	if (result.types != null) {
		for (TypeDeclaration type : result.types) {
			ImportReference currentPackage = result.currentPackage;
			String packageName = null;
			if (currentPackage != null) {
				char[][] importName = currentPackage.getImportName();
				if (importName != null) {
					packageName = CharOperation.toString(importName);
				}
			}
			JvmDeclaredType jvmType = createType(type, packageName);
			resource.getContents().add(jvmType);
		}
	}
}
 
Example #13
Source File: SourceIndexer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void resolveDocument() {
	try {
		IPath path = new Path(this.document.getPath());
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0));
		JavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
		JavaProject javaProject = (JavaProject) model.getJavaProject(project);

		this.options = new CompilerOptions(javaProject.getOptions(true));
		ProblemReporter problemReporter =
				new ProblemReporter(
						DefaultErrorHandlingPolicies.proceedWithAllProblems(),
						this.options,
						new DefaultProblemFactory());

		// Re-parse using normal parser, IndexingParser swallows several nodes, see comment above class.
		this.basicParser = new Parser(problemReporter, false);
		this.basicParser.reportOnlyOneSyntaxError = true;
		this.basicParser.scanner.taskTags = null;
		this.cud = this.basicParser.parse(this.compilationUnit, new CompilationResult(this.compilationUnit, 0, 0, this.options.maxProblemsPerUnit));

		// Use a non model name environment to avoid locks, monitors and such.
		INameEnvironment nameEnvironment = new JavaSearchNameEnvironment(javaProject, JavaModelManager.getJavaModelManager().getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, true/*add primary WCs*/));
		this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, nameEnvironment);
		reduceParseTree(this.cud);
		this.lookupEnvironment.buildTypeBindings(this.cud, null);
		this.lookupEnvironment.completeTypeBindings();
		this.cud.scope.faultInTypes();
		this.cud.resolve();
	} catch (Exception e) {
		if (JobManager.VERBOSE) {
			e.printStackTrace();
		}
	}
}
 
Example #14
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected boolean hasAlreadyDefinedType(CompilationUnitDeclaration parsedUnit) {
	CompilationResult result = parsedUnit.compilationResult;
	if (result == null) return false;
	for (int i = 0; i < result.problemCount; i++)
		if (result.problems[i].getID() == IProblem.DuplicateTypes)
			return true;
	return false;
}
 
Example #15
Source File: CodeSnippetParsingUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Expression parseExpression(char[] source, int offset, int length, Map settings, boolean recordParsingInformation) {

		if (source == null) {
			throw new IllegalArgumentException();
		}
		CompilerOptions compilerOptions = new CompilerOptions(settings);
		// in this case we don't want to ignore method bodies since we are parsing only an expression
		final ProblemReporter problemReporter = new ProblemReporter(
					DefaultErrorHandlingPolicies.proceedWithAllProblems(),
					compilerOptions,
					new DefaultProblemFactory(Locale.getDefault()));

		CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false);

		ICompilationUnit sourceUnit =
			new CompilationUnit(
				source,
				"", //$NON-NLS-1$
				compilerOptions.defaultEncoding);

		CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
		CompilationUnitDeclaration unit = new CompilationUnitDeclaration(problemReporter, compilationResult, source.length);
		Expression result = parser.parseExpression(source, offset, length, unit, true /* record line separators */);

		if (recordParsingInformation) {
			this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, unit.comments);
		}
		return result;
	}
 
Example #16
Source File: PublicScanner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public final void setSource(char[] contents, CompilationResult compilationResult) {
	if (contents == null) {
		char[] cuContents = compilationResult.compilationUnit.getContents();
		setSource(cuContents);
	} else {
		setSource(contents);
	}
	int[] lineSeparatorPositions = compilationResult.lineSeparatorPositions;
	if (lineSeparatorPositions != null) {
		this.lineEnds = lineSeparatorPositions;
		this.linePtr = lineSeparatorPositions.length - 1;
	}
}
 
Example #17
Source File: SourceTypeConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Initializer convert(InitializerElementInfo initializerInfo, CompilationResult compilationResult) throws JavaModelException {

		Block block = new Block(0);
		Initializer initializer = new Initializer(block, ClassFileConstants.AccDefault);

		int start = initializerInfo.getDeclarationSourceStart();
		int end = initializerInfo.getDeclarationSourceEnd();

		initializer.sourceStart = initializer.declarationSourceStart = start;
		initializer.sourceEnd = initializer.declarationSourceEnd = end;
		initializer.modifiers = initializerInfo.getModifiers();

		/* convert local and anonymous types */
		IJavaElement[] children = initializerInfo.getChildren();
		int typesLength = children.length;
		if (typesLength > 0) {
			Statement[] statements = new Statement[typesLength];
			for (int i = 0; i < typesLength; i++) {
				SourceType type = (SourceType) children[i];
				TypeDeclaration localType = convert(type, compilationResult);
				if ((localType.bits & ASTNode.IsAnonymousType) != 0) {
					QualifiedAllocationExpression expression = new QualifiedAllocationExpression(localType);
					expression.type = localType.superclass;
					localType.superclass = null;
					localType.superInterfaces = null;
					localType.allocation = expression;
					statements[i] = expression;
				} else {
					statements[i] = localType;
				}
			}
			block.statements = statements;
		}

		return initializer;
	}
 
Example #18
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void getMethodBodies(CompilationUnitDeclaration unit, MatchingNodeSet nodeSet) {
	if (unit.ignoreMethodBodies) {
		unit.ignoreFurtherInvestigation = true;
		return; // if initial diet parse did not work, no need to dig into method bodies.
	}

	// save existing values to restore them at the end of the parsing process
	// see bug 47079 for more details
	int[] oldLineEnds = this.parser.scanner.lineEnds;
	int oldLinePtr = this.parser.scanner.linePtr;

	try {
		CompilationResult compilationResult = unit.compilationResult;
		this.parser.scanner.setSource(compilationResult);

		if (this.parser.javadocParser.checkDocComment) {
			char[] contents = compilationResult.compilationUnit.getContents();
			this.parser.javadocParser.scanner.setSource(contents);
		}
		this.parser.nodeSet = nodeSet;
		this.parser.parseBodies(unit);
	} finally {
		this.parser.nodeSet = null;
		// this is done to prevent any side effects on the compilation unit result
		// line separator positions array.
		this.parser.scanner.lineEnds = oldLineEnds;
		this.parser.scanner.linePtr = oldLinePtr;
	}
}
 
Example #19
Source File: GroovyCompilationOnScriptExpressionConstraint.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private IStatus evaluateExpression(final IValidationContext context, final EObject eObj) {
    final Expression expression = (Expression) eObj;
    final String scriptText = expression.getContent();
    if (scriptText == null || scriptText.isEmpty()) {
        return context.createSuccessStatus();
    }
    final IJavaProject javaProject = RepositoryManager.getInstance().getCurrentRepository().getJavaProject();
    final GroovySnippetCompiler compiler = new GroovySnippetCompiler((JavaProject) javaProject);
    final CompilationResult result = compiler.compileForErrors(scriptText, null);
    final CategorizedProblem[] problems = result.getErrors();
    if (problems != null && problems.length > 0) {
        final StringBuilder sb = new StringBuilder();
        for (final CategorizedProblem problem : problems) {
            sb.append(problem.getMessage());
            sb.append(", ");
        }
        if (sb.length() > 1) {
            sb.delete(sb.length() - 2, sb.length());
            return context.createFailureStatus(new Object[] { Messages.bind(Messages.groovyCompilationProblem, expression.getName(), sb.toString()) });
        }
    }
    final ModuleNode moduleNode = compiler.compile(scriptText, null);
    final BlockStatement statementBlock = moduleNode.getStatementBlock();
    final ValidationCodeVisitorSupport validationCodeVisitorSupport = new ValidationCodeVisitorSupport(context, expression, moduleNode);
    statementBlock.visit(validationCodeVisitorSupport);
    return validationCodeVisitorSupport.getStatus();
}
 
Example #20
Source File: SourceTypeConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private QualifiedAllocationExpression convert(IJavaElement localType, FieldDeclaration enumConstant, CompilationResult compilationResult) throws JavaModelException {
	TypeDeclaration anonymousLocalTypeDeclaration = convert((SourceType) localType, compilationResult);
	QualifiedAllocationExpression expression = new QualifiedAllocationExpression(anonymousLocalTypeDeclaration);
	expression.type = anonymousLocalTypeDeclaration.superclass;
	anonymousLocalTypeDeclaration.superclass = null;
	anonymousLocalTypeDeclaration.superInterfaces = null;
	anonymousLocalTypeDeclaration.allocation = expression;
	if (enumConstant != null) {
		anonymousLocalTypeDeclaration.modifiers &= ~ClassFileConstants.AccEnum;
		expression.enumConstant = enumConstant;
		expression.type = null;
	}
	return expression;
}
 
Example #21
Source File: CompletionOnAnnotationOfType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public CompletionOnAnnotationOfType(char[] typeName, CompilationResult compilationResult, Annotation annotation){
	super(compilationResult);
	this.sourceEnd = annotation.sourceEnd;
	this.sourceStart = annotation.sourceEnd;
	this.name = typeName;
	this.annotations = new Annotation[]{annotation};
}
 
Example #22
Source File: CompilationUnitResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected static ICompilerRequestor getRequestor() {
	return new ICompilerRequestor() {
		public void acceptResult(CompilationResult compilationResult) {
			// do nothing
		}
	};
}
 
Example #23
Source File: CompilationUnitResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void handleInternalException(
		Throwable internalException,
		CompilationUnitDeclaration unit,
		CompilationResult result) {
	super.handleInternalException(internalException, unit, result);
	if (unit != null) {
		removeUnresolvedBindings(unit);
	}
}
 
Example #24
Source File: Main.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void startLoggingSource(CompilationResult compilationResult) {
	if ((this.tagBits & Logger.XML) != 0) {
		ICompilationUnit compilationUnit = compilationResult.compilationUnit;
		if (compilationUnit != null) {
  				char[] fileName = compilationUnit.getFileName();
  				File f = new File(new String(fileName));
  				if (fileName != null) {
  					this.parameters.put(Logger.PATH, f.getAbsolutePath());
  				}
  				char[][] packageName = compilationResult.packageName;
  				if (packageName != null) {
  					this.parameters.put(
  							Logger.PACKAGE,
  							new String(CharOperation.concatWith(packageName, File.separatorChar)));
  				}
  				CompilationUnit unit = (CompilationUnit) compilationUnit;
  				String destinationPath = unit.destinationPath;
			if (destinationPath == null) {
				destinationPath = this.main.destinationPath;
			}
			if (destinationPath != null && destinationPath != NONE) {
				if (File.separatorChar == '/') {
					this.parameters.put(Logger.OUTPUT, destinationPath);
				} else {
					this.parameters.put(Logger.OUTPUT, destinationPath.replace('/', File.separatorChar));
				}
			}
		}
		printTag(Logger.SOURCE, this.parameters, true, false);
	}
}
 
Example #25
Source File: Main.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public String extractDestinationPathFromSourceFile(CompilationResult result) {
	ICompilationUnit compilationUnit = result.compilationUnit;
	if (compilationUnit != null) {
		char[] fileName = compilationUnit.getFileName();
		int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
		if (lastIndex != -1) {
			final String outputPathName = new String(fileName, 0, lastIndex);
			final File output = new File(outputPathName);
			if (output.exists() && output.isDirectory()) {
				return outputPathName;
			}
		}
	}
	return System.getProperty("user.dir"); //$NON-NLS-1$
}
 
Example #26
Source File: Scanner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public final void setSource(char[] contents, CompilationResult compilationResult) {
	if (contents == null) {
		char[] cuContents = compilationResult.compilationUnit.getContents();
		setSource(cuContents);
	} else {
		setSource(contents);
	}
	int[] lineSeparatorPositions = compilationResult.lineSeparatorPositions;
	if (lineSeparatorPositions != null) {
		this.lineEnds = lineSeparatorPositions;
		this.linePtr = lineSeparatorPositions.length - 1;
	}
}
 
Example #27
Source File: ReferenceExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void initialize(CompilationResult result, Expression expression, TypeReference [] optionalTypeArguments, char [] identifierOrNew, int sourceEndPosition) {
	super.setCompilationResult(result);
	this.lhs = expression;
	this.typeArguments = optionalTypeArguments;
	this.selector = identifierOrNew;
	this.sourceStart = expression.sourceStart;
	this.sourceEnd = sourceEndPosition;
}
 
Example #28
Source File: CompilationUnitDeclaration.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public CompilationUnitDeclaration(ProblemReporter problemReporter, CompilationResult compilationResult, int sourceLength) {
	this.problemReporter = problemReporter;
	this.compilationResult = compilationResult;
	//by definition of a compilation unit....
	this.sourceStart = 0;
	this.sourceEnd = sourceLength - 1;
}
 
Example #29
Source File: AbortCompilation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void updateContext(InvocationSite invocationSite, CompilationResult unitResult) {
	if (this.problem == null) return;
	if (this.problem.getSourceStart() != 0 || this.problem.getSourceEnd() != 0) return;
	this.problem.setSourceStart(invocationSite.sourceStart());
	this.problem.setSourceEnd(invocationSite.sourceEnd());
	int[] lineEnds = unitResult.getLineSeparatorPositions();
	this.problem.setSourceLineNumber(Util.getLineNumber(invocationSite.sourceStart(), lineEnds, 0, lineEnds.length-1));
	this.compilationResult = unitResult;
}
 
Example #30
Source File: AbortCompilation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void updateContext(ASTNode astNode, CompilationResult unitResult) {
	if (this.problem == null) return;
	if (this.problem.getSourceStart() != 0 || this.problem.getSourceEnd() != 0) return;
	this.problem.setSourceStart(astNode.sourceStart());
	this.problem.setSourceEnd(astNode.sourceEnd());
	int[] lineEnds = unitResult.getLineSeparatorPositions();
	this.problem.setSourceLineNumber(Util.getLineNumber(astNode.sourceStart(), lineEnds, 0, lineEnds.length-1));
	this.compilationResult = unitResult;
}