Search in sources :

Example 46 with IProblem

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

the class PreprocessingService method preprocessSketch.

/// --------------------------------------------------------------------------
private PreprocessedSketch preprocessSketch(PreprocessedSketch prevResult) {
    boolean firstCheck = prevResult == null;
    PreprocessedSketch.Builder result = new PreprocessedSketch.Builder();
    List<ImportStatement> codeFolderImports = result.codeFolderImports;
    List<ImportStatement> programImports = result.programImports;
    JavaMode javaMode = (JavaMode) editor.getMode();
    Sketch sketch = result.sketch = editor.getSketch();
    String className = sketch.getName();
    StringBuilder workBuffer = new StringBuilder();
    // Combine code into one buffer
    IntList tabStartsList = new IntList();
    for (SketchCode sc : sketch.getCode()) {
        if (sc.isExtension("pde")) {
            tabStartsList.append(workBuffer.length());
            try {
                workBuffer.append(sc.getDocumentText());
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
            workBuffer.append('\n');
        }
    }
    result.tabStartOffsets = tabStartsList.array();
    String pdeStage = result.pdeCode = workBuffer.toString();
    boolean reloadCodeFolder = firstCheck || codeFolderChanged.getAndSet(false);
    boolean reloadLibraries = firstCheck || librariesChanged.getAndSet(false);
    // Core and default imports
    if (coreAndDefaultImports == null) {
        PdePreprocessor p = editor.createPreprocessor(null);
        coreAndDefaultImports = buildCoreAndDefaultImports(p);
    }
    result.coreAndDefaultImports.addAll(coreAndDefaultImports);
    // Prepare code folder imports
    if (reloadCodeFolder) {
        codeFolderImports.addAll(buildCodeFolderImports(sketch));
    } else {
        codeFolderImports.addAll(prevResult.codeFolderImports);
    }
    // TODO: convert unicode escapes to chars
    SourceUtils.scrubCommentsAndStrings(workBuffer);
    Mode sketchMode = PdePreprocessor.parseMode(workBuffer);
    // Prepare transforms to convert pde code into parsable code
    TextTransform toParsable = new TextTransform(pdeStage);
    toParsable.addAll(SourceUtils.insertImports(coreAndDefaultImports));
    toParsable.addAll(SourceUtils.insertImports(codeFolderImports));
    toParsable.addAll(SourceUtils.parseProgramImports(workBuffer, programImports));
    toParsable.addAll(SourceUtils.replaceTypeConstructors(workBuffer));
    toParsable.addAll(SourceUtils.replaceHexLiterals(workBuffer));
    toParsable.addAll(SourceUtils.wrapSketch(sketchMode, className, workBuffer.length()));
    {
        // Refresh sketch classloader and classpath if imports changed
        if (javaRuntimeClassPath == null) {
            javaRuntimeClassPath = buildJavaRuntimeClassPath();
            sketchModeClassPath = buildModeClassPath(javaMode, false);
            searchModeClassPath = buildModeClassPath(javaMode, true);
        }
        if (reloadLibraries) {
            coreLibraryClassPath = buildCoreLibraryClassPath(javaMode);
        }
        boolean rebuildLibraryClassPath = reloadLibraries || checkIfImportsChanged(programImports, prevResult.programImports);
        if (rebuildLibraryClassPath) {
            sketchLibraryClassPath = buildSketchLibraryClassPath(javaMode, programImports);
            searchLibraryClassPath = buildSearchLibraryClassPath(javaMode);
        }
        boolean rebuildClassPath = reloadCodeFolder || rebuildLibraryClassPath || prevResult.classLoader == null || prevResult.classPath == null || prevResult.classPathArray == null || prevResult.searchClassPathArray == null;
        if (reloadCodeFolder) {
            codeFolderClassPath = buildCodeFolderClassPath(sketch);
        }
        if (rebuildClassPath) {
            {
                // Sketch class path
                List<String> sketchClassPath = new ArrayList<>();
                sketchClassPath.addAll(javaRuntimeClassPath);
                sketchClassPath.addAll(sketchModeClassPath);
                sketchClassPath.addAll(sketchLibraryClassPath);
                sketchClassPath.addAll(coreLibraryClassPath);
                sketchClassPath.addAll(codeFolderClassPath);
                String[] classPathArray = sketchClassPath.stream().toArray(String[]::new);
                URL[] urlArray = Arrays.stream(classPathArray).map(path -> {
                    try {
                        return Paths.get(path).toUri().toURL();
                    } catch (MalformedURLException e) {
                        Messages.loge("malformed URL when preparing sketch classloader", e);
                        return null;
                    }
                }).filter(url -> url != null).toArray(URL[]::new);
                result.classLoader = new URLClassLoader(urlArray, null);
                result.classPath = classPathFactory.createFromPaths(classPathArray);
                result.classPathArray = classPathArray;
            }
            {
                // Search class path
                List<String> searchClassPath = new ArrayList<>();
                searchClassPath.addAll(javaRuntimeClassPath);
                searchClassPath.addAll(searchModeClassPath);
                searchClassPath.addAll(searchLibraryClassPath);
                searchClassPath.addAll(coreLibraryClassPath);
                searchClassPath.addAll(codeFolderClassPath);
                result.searchClassPathArray = searchClassPath.stream().toArray(String[]::new);
            }
        } else {
            result.classLoader = prevResult.classLoader;
            result.classPath = prevResult.classPath;
            result.searchClassPathArray = prevResult.searchClassPathArray;
            result.classPathArray = prevResult.classPathArray;
        }
    }
    {
        // Check for missing braces
        List<JavaProblem> missingBraceProblems = SourceUtils.checkForMissingBraces(workBuffer, result.tabStartOffsets);
        if (!missingBraceProblems.isEmpty()) {
            result.missingBraceProblems.addAll(missingBraceProblems);
            result.hasSyntaxErrors = true;
        }
    }
    // Transform code to parsable state
    String parsableStage = toParsable.apply();
    OffsetMapper parsableMapper = toParsable.getMapper();
    // Create intermediate AST for advanced preprocessing
    CompilationUnit parsableCU = makeAST(parser, parsableStage.toCharArray(), COMPILER_OPTIONS);
    // Prepare advanced transforms which operate on AST
    TextTransform toCompilable = new TextTransform(parsableStage);
    toCompilable.addAll(SourceUtils.preprocessAST(parsableCU));
    // Transform code to compilable state
    String compilableStage = toCompilable.apply();
    OffsetMapper compilableMapper = toCompilable.getMapper();
    char[] compilableStageChars = compilableStage.toCharArray();
    // Create compilable AST to get syntax problems
    CompilationUnit compilableCU = makeAST(parser, compilableStageChars, COMPILER_OPTIONS);
    // Get syntax problems from compilable AST
    result.hasSyntaxErrors |= Arrays.stream(compilableCU.getProblems()).anyMatch(IProblem::isError);
    // Generate bindings after getting problems - avoids
    // 'missing type' errors when there are syntax problems
    CompilationUnit bindingsCU = makeASTWithBindings(parser, compilableStageChars, COMPILER_OPTIONS, className, result.classPathArray);
    // Get compilation problems
    List<IProblem> bindingsProblems = Arrays.asList(bindingsCU.getProblems());
    result.hasCompilationErrors = bindingsProblems.stream().anyMatch(IProblem::isError);
    // Update builder
    result.offsetMapper = parsableMapper.thenMapping(compilableMapper);
    result.javaCode = compilableStage;
    result.compilationUnit = bindingsCU;
    // Build it
    return result.build();
}
Also used : JavaMode(processing.mode.java.JavaMode) Arrays(java.util.Arrays) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) URL(java.net.URL) PdePreprocessor(processing.mode.java.preproc.PdePreprocessor) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) URLClassLoader(java.net.URLClassLoader) StringList(processing.data.StringList) Map(java.util.Map) JavaEditor(processing.mode.java.JavaEditor) StreamSupport(java.util.stream.StreamSupport) Mode(processing.mode.java.preproc.PdePreprocessor.Mode) SketchCode(processing.app.SketchCode) SketchException(processing.app.SketchException) Library(processing.app.Library) Messages(processing.app.Messages) Sketch(processing.app.Sketch) ClassPathFactory(com.google.classpath.ClassPathFactory) MalformedURLException(java.net.MalformedURLException) JavaCore(org.eclipse.jdt.core.JavaCore) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) BadLocationException(javax.swing.text.BadLocationException) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) Collectors(java.util.stream.Collectors) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) IntList(processing.data.IntList) List(java.util.List) ASTParser(org.eclipse.jdt.core.dom.ASTParser) Paths(java.nio.file.Paths) OffsetMapper(processing.mode.java.pdex.TextTransform.OffsetMapper) AST(org.eclipse.jdt.core.dom.AST) IProblem(org.eclipse.jdt.core.compiler.IProblem) Collections(java.util.Collections) Util(processing.app.Util) MalformedURLException(java.net.MalformedURLException) SketchCode(processing.app.SketchCode) ArrayList(java.util.ArrayList) URL(java.net.URL) OffsetMapper(processing.mode.java.pdex.TextTransform.OffsetMapper) ArrayList(java.util.ArrayList) StringList(processing.data.StringList) IntList(processing.data.IntList) List(java.util.List) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) JavaMode(processing.mode.java.JavaMode) Mode(processing.mode.java.preproc.PdePreprocessor.Mode) IProblem(org.eclipse.jdt.core.compiler.IProblem) JavaMode(processing.mode.java.JavaMode) IntList(processing.data.IntList) URLClassLoader(java.net.URLClassLoader) Sketch(processing.app.Sketch) PdePreprocessor(processing.mode.java.preproc.PdePreprocessor) BadLocationException(javax.swing.text.BadLocationException)

Example 47 with IProblem

use of org.eclipse.jdt.core.compiler.IProblem in project tdi-studio-se by Talend.

the class Problems method computeCompilationUnit.

@SuppressWarnings("restriction")
private static List<Problem> computeCompilationUnit(IFile file, ProblemType type, Item item) throws CoreException {
    ERepositoryObjectType itemType = ERepositoryObjectType.getItemType(item);
    // FIXME, only for standard job first, also for JobLaunchShortcut.launch
    if (itemType == null || !itemType.equals(ERepositoryObjectType.PROCESS)) {
        return Collections.emptyList();
    }
    List<Problem> compilProblems = new ArrayList<Problem>();
    final ICompilationUnit unit = JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(new FileEditorInput(file), false);
    if (unit != null) {
        CompilationUnit ast = unit.reconcile(ASTProvider.SHARED_AST_LEVEL, ICompilationUnit.FORCE_PROBLEM_DETECTION, null, null);
        IProblem[] problems = ast.getProblems();
        if (problems != null) {
            for (IProblem p : problems) {
                String[] arguments = p.getArguments();
                int id = p.getID();
                String message = p.getMessage();
                int sourceLineNumber = p.getSourceLineNumber();
                int sourceStart = p.getSourceStart();
                int sourceEnd = p.getSourceEnd();
                String uniName = null;
                IPath location = file.getLocation();
                if (location != null) {
                    String path = location.toString();
                    uniName = setErrorMark(path, sourceLineNumber);
                }
                ProblemStatus status = ProblemStatus.WARNING;
                if (p.isError()) {
                    status = ProblemStatus.ERROR;
                }
                TalendProblem tp = new TalendProblem(status, item, null, message, sourceLineNumber, uniName, sourceStart, sourceEnd, type);
                compilProblems.add(tp);
            }
        }
    }
    return compilProblems;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPath(org.eclipse.core.runtime.IPath) TalendProblem(org.talend.core.model.process.TalendProblem) ArrayList(java.util.ArrayList) IProblem(org.eclipse.jdt.core.compiler.IProblem) ProblemStatus(org.talend.core.model.process.Problem.ProblemStatus) FileEditorInput(org.eclipse.ui.part.FileEditorInput) Problem(org.talend.core.model.process.Problem) IProblem(org.eclipse.jdt.core.compiler.IProblem) TalendProblem(org.talend.core.model.process.TalendProblem) ERepositoryObjectType(org.talend.core.model.repository.ERepositoryObjectType)

Example 48 with IProblem

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

the class EclipseJavaCompiler method compile.

public org.drools.compiler.commons.jci.compilers.CompilationResult compile(final String[] pSourceFiles, final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader, final JavaCompilerSettings pSettings) {
    final Collection problems = new ArrayList();
    final ICompilationUnit[] compilationUnits = new ICompilationUnit[pSourceFiles.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        final String sourceFile = pSourceFiles[i];
        if (pReader.isAvailable(sourceFile)) {
            compilationUnits[i] = new CompilationUnit(pReader, sourceFile);
        } else {
            // log.error("source not found " + sourceFile);
            final CompilationProblem problem = new CompilationProblem() {

                public int getEndColumn() {
                    return 0;
                }

                public int getEndLine() {
                    return 0;
                }

                public String getFileName() {
                    return sourceFile;
                }

                public String getMessage() {
                    return "Source " + sourceFile + " could not be found";
                }

                public int getStartColumn() {
                    return 0;
                }

                public int getStartLine() {
                    return 0;
                }

                public boolean isError() {
                    return true;
                }

                public String toString() {
                    return getMessage();
                }
            };
            if (problemHandler != null) {
                problemHandler.handle(problem);
            }
            problems.add(problem);
        }
    }
    if (problems.size() > 0) {
        final CompilationProblem[] result = new CompilationProblem[problems.size()];
        problems.toArray(result);
        return new org.drools.compiler.commons.jci.compilers.CompilationResult(result);
    }
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final INameEnvironment nameEnvironment = new INameEnvironment() {

        public NameEnvironmentAnswer findType(final char[][] pCompoundTypeName) {
            final StringBuilder result = new StringBuilder();
            for (int i = 0; i < pCompoundTypeName.length; i++) {
                if (i != 0) {
                    result.append('.');
                }
                result.append(pCompoundTypeName[i]);
            }
            return findType(result.toString());
        }

        public NameEnvironmentAnswer findType(final char[] pTypeName, final char[][] pPackageName) {
            final StringBuilder result = new StringBuilder();
            for (int i = 0; i < pPackageName.length; i++) {
                result.append(pPackageName[i]);
                result.append('.');
            }
            // log.debug("finding typeName=" + new String(typeName) + " packageName=" + result.toString());
            result.append(pTypeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(final String pClazzName) {
            final String resourceName = ClassUtils.convertClassToResourcePath(pClazzName);
            final byte[] clazzBytes = pStore.read(resourceName);
            if (clazzBytes != null) {
                try {
                    return createNameEnvironmentAnswer(pClazzName, clazzBytes);
                } catch (final ClassFormatException e) {
                    throw new RuntimeException("ClassFormatException in loading class '" + pClazzName + "' with JCI.");
                }
            }
            InputStream is = null;
            ByteArrayOutputStream baos = null;
            try {
                is = pClassLoader.getResourceAsStream(resourceName);
                if (is == null) {
                    return null;
                }
                if (ClassUtils.isWindows() || ClassUtils.isOSX()) {
                    // check it really is a class, this issue is due to windows case sensitivity issues for the class org.kie.Process and path org/droosl/process
                    try {
                        pClassLoader.loadClass(pClazzName);
                    } catch (ClassNotFoundException e) {
                        return null;
                    } catch (NoClassDefFoundError e) {
                        return null;
                    }
                }
                final byte[] buffer = new byte[8192];
                baos = new ByteArrayOutputStream(buffer.length);
                int count;
                while ((count = is.read(buffer, 0, buffer.length)) > 0) {
                    baos.write(buffer, 0, count);
                }
                baos.flush();
                return createNameEnvironmentAnswer(pClazzName, baos.toByteArray());
            } catch (final IOException e) {
                throw new RuntimeException("could not read class", e);
            } catch (final ClassFormatException e) {
                throw new RuntimeException("wrong class format", e);
            } finally {
                try {
                    if (baos != null) {
                        baos.close();
                    }
                } catch (final IOException oe) {
                    throw new RuntimeException("could not close output stream", oe);
                }
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (final IOException ie) {
                    throw new RuntimeException("could not close input stream", ie);
                }
            }
        }

        private NameEnvironmentAnswer createNameEnvironmentAnswer(final String pClazzName, final byte[] clazzBytes) throws ClassFormatException {
            final char[] fileName = pClazzName.toCharArray();
            final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
            return new NameEnvironmentAnswer(classFileReader, null);
        }

        private boolean isSourceAvailable(final String pClazzName, final ResourceReader pReader) {
            // FIXME: this should not be tied to the extension
            final String javaSource = pClazzName.replace('.', '/') + ".java";
            final String classSource = pClazzName.replace('.', '/') + ".class";
            return pReader.isAvailable(prefix + javaSource) || pReader.isAvailable(prefix + classSource);
        }

        private boolean isPackage(final String pClazzName) {
            InputStream is = null;
            try {
                is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName));
                if (is != null) {
                    if (ClassUtils.isWindows() || ClassUtils.isOSX()) {
                        try {
                            Class cls = pClassLoader.loadClass(pClazzName);
                            if (cls != null) {
                                return false;
                            }
                        } catch (ClassNotFoundException e) {
                            return true;
                        } catch (NoClassDefFoundError e) {
                            return true;
                        }
                    }
                }
                boolean result = is == null && !isSourceAvailable(pClazzName, pReader);
                return result;
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        throw new RuntimeException("Unable to close stream for resource: " + pClazzName);
                    }
                }
            }
        }

        public boolean isPackage(char[][] parentPackageName, char[] pPackageName) {
            final StringBuilder result = new StringBuilder();
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    if (i != 0) {
                        result.append('.');
                    }
                    result.append(parentPackageName[i]);
                }
            }
            if (parentPackageName != null && parentPackageName.length > 0) {
                result.append('.');
            }
            result.append(pPackageName);
            return isPackage(result.toString());
        }

        public void cleanup() {
        }
    };
    final ICompilerRequestor compilerRequestor = new ICompilerRequestor() {

        public void acceptResult(final CompilationResult pResult) {
            if (pResult.hasProblems()) {
                final IProblem[] iproblems = pResult.getProblems();
                for (int i = 0; i < iproblems.length; i++) {
                    final IProblem iproblem = iproblems[i];
                    final CompilationProblem problem = new EclipseCompilationProblem(iproblem);
                    if (problemHandler != null) {
                        problemHandler.handle(problem);
                    }
                    problems.add(problem);
                }
            }
            if (!pResult.hasErrors()) {
                final ClassFile[] clazzFiles = pResult.getClassFiles();
                for (int i = 0; i < clazzFiles.length; i++) {
                    final ClassFile clazzFile = clazzFiles[i];
                    final char[][] compoundName = clazzFile.getCompoundName();
                    final StringBuilder clazzName = new StringBuilder();
                    for (int j = 0; j < compoundName.length; j++) {
                        if (j != 0) {
                            clazzName.append('.');
                        }
                        clazzName.append(compoundName[j]);
                    }
                    pStore.write(clazzName.toString().replace('.', '/') + ".class", clazzFile.getBytes());
                }
            }
        }
    };
    final Map settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings();
    CompilerOptions compilerOptions = new CompilerOptions(settingsMap);
    compilerOptions.parseLiteralExpressionsAsConstants = false;
    final Compiler compiler = new Compiler(nameEnvironment, policy, compilerOptions, compilerRequestor, problemFactory);
    if (ClassGenerator.DUMP_GENERATED_CLASSES) {
        dumpUnits(compilationUnits, pReader);
    }
    compiler.compile(compilationUnits);
    final CompilationProblem[] result = new CompilationProblem[problems.size()];
    problems.toArray(result);
    return new org.drools.compiler.commons.jci.compilers.CompilationResult(result);
}
Also used : IErrorHandlingPolicy(org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy) ResourceReader(org.drools.compiler.commons.jci.readers.ResourceReader) NameEnvironmentAnswer(org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer) ClassFileReader(org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader) ArrayList(java.util.ArrayList) CompilationProblem(org.drools.compiler.commons.jci.problems.CompilationProblem) ClassFormatException(org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException) INameEnvironment(org.eclipse.jdt.internal.compiler.env.INameEnvironment) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory) IProblemFactory(org.eclipse.jdt.internal.compiler.IProblemFactory) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) Compiler(org.eclipse.jdt.internal.compiler.Compiler) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) ICompilerRequestor(org.eclipse.jdt.internal.compiler.ICompilerRequestor) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) IProblem(org.eclipse.jdt.core.compiler.IProblem) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) Collection(java.util.Collection) CompilationResult(org.eclipse.jdt.internal.compiler.CompilationResult) Map(java.util.Map)

Example 49 with IProblem

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

the class DocumentLifeCycleHandlerTest method testNotExpectedPackage.

@Test
public void testNotExpectedPackage() throws Exception {
    newDefaultProject();
    // @formatter:off
    String content = "package org;\n" + "public class Foo {" + "}";
    // @formatter:on
    temp = createTempFolder();
    File file = createTempFile(temp, "Foo.java", content);
    URI uri = file.toURI();
    ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
    openDocument(cu, cu.getSource(), 1);
    CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
    IProblem[] problems = astRoot.getProblems();
    assertEquals("Unexpected number of errors", 0, problems.length);
    String source = cu.getSource();
    int length = source.length();
    source = source.replace("org", "org.eclipse");
    changeDocument(cu, source, 2, JDTUtils.toRange(cu, 0, source.length()), length);
    FileUtils.writeStringToFile(file, source);
    saveDocument(cu);
    cu = JDTUtils.resolveCompilationUnit(uri);
    astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
    problems = astRoot.getProblems();
    assertEquals("Unexpected number of errors", 0, problems.length);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) File(java.io.File) URI(java.net.URI) IProblem(org.eclipse.jdt.core.compiler.IProblem) AbstractProjectsManagerBasedTest(org.eclipse.jdt.ls.core.internal.managers.AbstractProjectsManagerBasedTest) Test(org.junit.Test)

Example 50 with IProblem

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

the class DocumentLifeCycleHandler method checkPackageDeclaration.

private ICompilationUnit checkPackageDeclaration(String uri, ICompilationUnit unit) {
    if (unit.getResource() != null && unit.getJavaProject() != null && unit.getJavaProject().getProject().getName().equals(ProjectsManager.DEFAULT_PROJECT_NAME)) {
        try {
            CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(unit, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
            IProblem[] problems = astRoot.getProblems();
            for (IProblem problem : problems) {
                if (problem.getID() == IProblem.PackageIsNotExpectedPackage) {
                    IResource file = unit.getResource();
                    boolean toRemove = file.isLinked();
                    if (toRemove) {
                        IPath path = file.getParent().getProjectRelativePath();
                        if (path.segmentCount() > 0 && JDTUtils.SRC.equals(path.segments()[0])) {
                            String packageNameResource = path.removeFirstSegments(1).toString().replace(JDTUtils.PATH_SEPARATOR, JDTUtils.PERIOD);
                            path = file.getLocation();
                            if (path != null && path.segmentCount() > 0) {
                                path = path.removeLastSegments(1);
                                String pathStr = path.toString().replace(JDTUtils.PATH_SEPARATOR, JDTUtils.PERIOD);
                                if (pathStr.endsWith(packageNameResource)) {
                                    toRemove = false;
                                }
                            }
                        }
                    }
                    if (toRemove) {
                        file.delete(true, new NullProgressMonitor());
                        if (unit.equals(sharedASTProvider.getActiveJavaElement())) {
                            sharedASTProvider.disposeAST();
                        }
                        unit.discardWorkingCopy();
                        unit = JDTUtils.resolveCompilationUnit(uri);
                        unit.becomeWorkingCopy(new NullProgressMonitor());
                        triggerValidation(unit);
                    }
                    break;
                }
            }
        } catch (CoreException e) {
            JavaLanguageServerPlugin.logException(e.getMessage(), e);
        }
    }
    return unit;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IPath(org.eclipse.core.runtime.IPath) CoreException(org.eclipse.core.runtime.CoreException) IProblem(org.eclipse.jdt.core.compiler.IProblem) IResource(org.eclipse.core.resources.IResource)

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