Search in sources :

Example 56 with IProblem

use of org.eclipse.jdt.core.compiler.IProblem in project evosuite by EvoSuite.

the class TestExtensionJob method parseJavaFile.

protected CompilationUnit parseJavaFile(String unitName, String fileName) throws IOException {
    String fileContents = readFile(fileName, Charset.defaultCharset());
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setStatementsRecovery(true);
    Map<String, String> COMPILER_OPTIONS = new HashMap<String, String>(JavaCore.getOptions());
    COMPILER_OPTIONS.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7);
    COMPILER_OPTIONS.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7);
    COMPILER_OPTIONS.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);
    // parser.setResolveBindings(true);
    // parser.setBindingsRecovery(true);
    parser.setUnitName(unitName);
    String[] encodings = { ENCODING };
    String[] classpaths = { classPath };
    String[] sources = { new File(suiteClass).getParent() };
    parser.setEnvironment(classpaths, sources, encodings, true);
    parser.setSource(fileContents.toCharArray());
    CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
    Set<String> problems = new HashSet<String>();
    for (IProblem problem : compilationUnit.getProblems()) {
        problems.add(problem.getSourceLineNumber() + ": " + problem.toString());
    }
    if (!problems.isEmpty()) {
        System.out.println("Got " + problems.size() + " problems compiling the source file: ");
        for (String problem : problems) {
            System.out.println(problem);
        }
    }
    return compilationUnit;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) HashMap(java.util.HashMap) ASTParser(org.eclipse.jdt.core.dom.ASTParser) IFile(org.eclipse.core.resources.IFile) File(java.io.File) IProblem(org.eclipse.jdt.core.compiler.IProblem) HashSet(java.util.HashSet)

Example 57 with IProblem

use of org.eclipse.jdt.core.compiler.IProblem in project evosuite by EvoSuite.

the class JUnitTestReader method parseJavaFile.

/**
 * <p>
 * parseJavaFile
 * </p>
 *
 * @param unitName
 *            a {@link java.lang.String} object.
 * @param fileContents
 *            a {@link java.lang.String} object.
 * @return a {@link org.eclipse.jdt.core.dom.CompilationUnit} object.
 */
protected CompilationUnit parseJavaFile(String unitName, String fileContents) {
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setUnitName(unitName);
    @SuppressWarnings("unchecked") Hashtable<String, String> options = JavaCore.getDefaultOptions();
    options.put(JavaCore.COMPILER_SOURCE, SOURCE_JAVA_VERSION);
    parser.setCompilerOptions(options);
    String[] encodings = createEncodings(ENCODING, sources.length);
    parser.setEnvironment(classpath, sources, encodings, true);
    parser.setSource(fileContents.toCharArray());
    CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
    Set<String> problems = new HashSet<String>();
    for (IProblem problem : compilationUnit.getProblems()) {
        problems.add(problem.toString());
    }
    if (!problems.isEmpty()) {
        logger.warn("Got {} problems compiling the source file: ", problems.size());
        for (String problem : problems) {
            logger.warn("{}", problem);
        }
    }
    return compilationUnit;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ASTParser(org.eclipse.jdt.core.dom.ASTParser) IProblem(org.eclipse.jdt.core.compiler.IProblem) HashSet(java.util.HashSet)

Example 58 with IProblem

use of org.eclipse.jdt.core.compiler.IProblem in project jetbrick-template-1x by subchen.

the class JdtCompiler method generateJavaClass.

@Override
protected void generateJavaClass(JavaSource source) throws IOException {
    INameEnvironment env = new NameEnvironment(source);
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    CompilerOptions options = getCompilerOptions();
    CompilerRequestor requestor = new CompilerRequestor();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);
    compiler.compile(new ICompilationUnit[] { new CompilationUnit(source) });
    if (requestor.hasErrors()) {
        String sourceCode = source.getSourceCode();
        String[] sourceCodeLines = sourceCode.split("(\r\n|\r|\n)", -1);
        StringBuilder sb = new StringBuilder();
        sb.append("Compilation failed.");
        sb.append('\n');
        for (IProblem p : requestor.getErrors()) {
            sb.append(p.getMessage()).append('\n');
            int start = p.getSourceStart();
            // default
            int column = start;
            for (int i = start; i >= 0; i--) {
                char c = sourceCode.charAt(i);
                if (c == '\n' || c == '\r') {
                    column = start - i;
                    break;
                }
            }
            sb.append(StringUtils.getPrettyError(sourceCodeLines, p.getSourceLineNumber(), column, p.getSourceStart(), p.getSourceEnd(), 3));
        }
        sb.append(requestor.getErrors().length);
        sb.append(" error(s)\n");
        throw new CompileErrorException(sb.toString());
    }
    requestor.save(source.getOutputdir());
}
Also used : Compiler(org.eclipse.jdt.internal.compiler.Compiler) IProblem(org.eclipse.jdt.core.compiler.IProblem) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory)

Example 59 with IProblem

use of org.eclipse.jdt.core.compiler.IProblem in project bndtools by bndtools.

the class NewTypeWizardPage method typeNameChanged.

/**
 * Hook method that gets called when the type name has changed. The method validates the type name and returns the
 * status of the validation.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus typeNameChanged() {
    StatusInfo status = new StatusInfo();
    fCurrType = null;
    String typeNameWithParameters = getTypeName();
    // must not be empty
    if (typeNameWithParameters.length() == 0) {
        status.setError(NewWizardMessages.NewTypeWizardPage_error_EnterTypeName);
        return status;
    }
    String typeName = getTypeNameWithoutParameters();
    if (typeName.indexOf('.') != -1) {
        status.setError(NewWizardMessages.NewTypeWizardPage_error_QualifiedName);
        return status;
    }
    IJavaProject project = getJavaProject();
    IStatus val = validateJavaTypeName(typeName, project);
    if (val.getSeverity() == IStatus.ERROR) {
        status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, val.getMessage()));
        return status;
    } else if (val.getSeverity() == IStatus.WARNING) {
        status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_TypeNameDiscouraged, val.getMessage()));
    // continue checking
    }
    // must not exist
    if (!isEnclosingTypeSelected()) {
        IPackageFragment pack = getPackageFragment();
        if (pack != null) {
            ICompilationUnit cu = pack.getCompilationUnit(getCompilationUnitName(typeName));
            fCurrType = cu.getType(typeName);
            IResource resource = cu.getResource();
            if (resource.exists()) {
                status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
                return status;
            }
            if (!ResourcesPlugin.getWorkspace().validateFiltered(resource).isOK()) {
                status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameFiltered);
                return status;
            }
            URI location = resource.getLocationURI();
            if (location != null) {
                try {
                    IFileStore store = EFS.getStore(location);
                    if (store.fetchInfo().exists()) {
                        status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExistsDifferentCase);
                        return status;
                    }
                } catch (CoreException e) {
                    status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_uri_location_unkown, BasicElementLabels.getURLPart(Resources.getLocationString(resource))));
                }
            }
        }
    } else {
        IType type = getEnclosingType();
        if (type != null) {
            fCurrType = type.getType(typeName);
            if (fCurrType.exists()) {
                status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
                return status;
            }
        }
    }
    if (!typeNameWithParameters.equals(typeName) && project != null) {
        if (!JavaModelUtil.is50OrHigher(project)) {
            status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeParameters);
            return status;
        }
        // $NON-NLS-1$//$NON-NLS-2$
        String typeDeclaration = "class " + typeNameWithParameters + " {}";
        ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setSource(typeDeclaration.toCharArray());
        parser.setProject(project);
        CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
        IProblem[] problems = compilationUnit.getProblems();
        if (problems.length > 0) {
            status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, problems[0].getMessage()));
            return status;
        }
    }
    return status;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IStatus(org.eclipse.core.runtime.IStatus) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) URI(java.net.URI) IProblem(org.eclipse.jdt.core.compiler.IProblem) IType(org.eclipse.jdt.core.IType) IJavaProject(org.eclipse.jdt.core.IJavaProject) CoreException(org.eclipse.core.runtime.CoreException) StatusInfo(org.eclipse.jdt.internal.ui.dialogs.StatusInfo) IFileStore(org.eclipse.core.filesystem.IFileStore) ASTParser(org.eclipse.jdt.core.dom.ASTParser) IResource(org.eclipse.core.resources.IResource)

Example 60 with IProblem

use of org.eclipse.jdt.core.compiler.IProblem in project flux by eclipse.

the class LinkedNodeFinder method getNameNodeProblemKind.

private static int getNameNodeProblemKind(IProblem[] problems, SimpleName nameNode) {
    int nameOffset = nameNode.getStartPosition();
    int nameInclEnd = nameOffset + nameNode.getLength() - 1;
    for (int i = 0; i < problems.length; i++) {
        IProblem curr = problems[i];
        if (curr.getSourceStart() == nameOffset && curr.getSourceEnd() == nameInclEnd) {
            int kind = getProblemKind(curr);
            if (kind != 0) {
                return kind;
            }
        }
    }
    return 0;
}
Also used : IProblem(org.eclipse.jdt.core.compiler.IProblem)

Aggregations

IProblem (org.eclipse.jdt.core.compiler.IProblem)61 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)28 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)25 ArrayList (java.util.ArrayList)20 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)10 File (java.io.File)9 ASTParser (org.eclipse.jdt.core.dom.ASTParser)9 IProblemLocation (org.eclipse.jdt.ui.text.java.IProblemLocation)7 ClassFile (org.eclipse.jdt.internal.compiler.ClassFile)6 Test (org.junit.Test)6 HashMap (java.util.HashMap)5 ASTNode (org.eclipse.jdt.core.dom.ASTNode)5 RefactoringStatusEntry (org.eclipse.ltk.core.refactoring.RefactoringStatusEntry)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 IOException (java.io.IOException)4 InputStream (java.io.InputStream)4 URI (java.net.URI)4 HashSet (java.util.HashSet)4 IJavaProject (org.eclipse.jdt.core.IJavaProject)4 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)4