org.eclipse.jdt.internal.compiler.batch.CompilationUnit Java Examples

The following examples show how to use org.eclipse.jdt.internal.compiler.batch.CompilationUnit. 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: SourcepathDirectory.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public NameEnvironmentAnswer findType(String packageName, String typeName, AccessRestriction accessRestriction) {
  Path javaFile = getFile(packageName, typeName);

  // Could be looking for a nested class, so try using outer class file name.
  // ASSUMPTION: '$' is ONLY used in a compiler generated class file names.
  if (javaFile == null && typeName.indexOf("$") > 0) {
    javaFile = getFile(packageName, typeName.split("\\$")[0]);
  }

  if (javaFile != null) {
    CompilationUnit cu = new ClasspathCompilationUnit(javaFile, encoding);
    return new NameEnvironmentAnswer(cu, accessRestriction);
  }
  return null;
}
 
Example #2
Source File: ExtractAnnotations.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
private boolean addSources(List<ICompilationUnit> sourceUnits, File file) throws IOException {
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null) {
            for (File sub : files) {
                addSources(sourceUnits, sub);
            }

        }

    } else if (file.getPath().endsWith(DOT_JAVA) && file.isFile()) {
        char[] contents = Util.getFileCharContent(file, encoding);
        ICompilationUnit unit = new CompilationUnit(contents, file.getPath(), encoding);
        return sourceUnits.add(unit);
    }
    return false;
}
 
Example #3
Source File: FilerImpl.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public JavaFileObject createSourceFile(CharSequence name, Element... originatingElements) throws IOException {
  JavaFileObject sourceFile = fileManager.getJavaFileForOutput(StandardLocation.SOURCE_OUTPUT, name.toString(), JavaFileObject.Kind.SOURCE, null);
  if (!createdResources.add(sourceFile.toUri())) {
    throw new FilerException("Attempt to recreate file for type " + name);
  }
  return new JavaFileObjectImpl(sourceFile, new FileObjectDelegate() {

    private boolean closed = false;

    @Override
    protected void onClose(Output<File> generatedSource) {
      if (!closed) {
        closed = true;
        // TODO optimize if the regenerated sources didn't change compared the previous build
        CompilationUnit unit = new CompilationUnit(null, generatedSource.getResource().getAbsolutePath(), null /* encoding */);
        processingEnv.addNewUnit(unit);
        incrementalCompiler.addGeneratedSource(generatedSource);
      }
    }
  });
}
 
Example #4
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 #5
Source File: EclipseCompilerImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public CompilationUnit[] getCompilationUnits() {
	if (this.compilationUnits == null) return EclipseCompilerImpl.NO_UNITS;
	ArrayList<CompilationUnit> units = new ArrayList<CompilationUnit>();
	for (final JavaFileObject javaFileObject : this.compilationUnits) {
		if (javaFileObject.getKind() != JavaFileObject.Kind.SOURCE) {
			throw new IllegalArgumentException();
		}
		String name = javaFileObject.getName();
		name = name.replace('\\', '/');
		CompilationUnit compilationUnit = new CompilationUnit(null,
			name,
			null) {

			@Override
			public char[] getContents() {
				try {
					return javaFileObject.getCharContent(true).toString().toCharArray();
				} catch(IOException e) {
					e.printStackTrace();
					throw new AbortCompilationUnit(null, e, null);
				}
			}
		};
		units.add(compilationUnit);
		this.javaFileObjectMap.put(compilationUnit, javaFileObject);
	}
	CompilationUnit[] result = new CompilationUnit[units.size()];
	units.toArray(result);
	return result;
}
 
Example #6
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 #7
Source File: CodeSnippetParsingUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ASTNode[] parseClassBodyDeclarations(
		char[] source,
		int offset,
		int length,
		Map settings,
		boolean recordParsingInformation,
		boolean enabledStatementRecovery) {
	if (source == null) {
		throw new IllegalArgumentException();
	}
	CompilerOptions compilerOptions = new CompilerOptions(settings);
	compilerOptions.ignoreMethodBodies = this.ignoreMethodBodies;
	final ProblemReporter problemReporter = new ProblemReporter(
				DefaultErrorHandlingPolicies.proceedWithAllProblems(),
				compilerOptions,
				new DefaultProblemFactory(Locale.getDefault()));

	CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false);
	parser.setMethodsFullRecovery(false);
	parser.setStatementsRecovery(enabledStatementRecovery);

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

	CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
	final CompilationUnitDeclaration compilationUnitDeclaration = new CompilationUnitDeclaration(problemReporter, compilationResult, source.length);
	ASTNode[] result = parser.parseClassBodyDeclarations(source, offset, length, compilationUnitDeclaration);

	if (recordParsingInformation) {
		this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments);
	}
	return result;
}
 
Example #8
Source File: JavaResource.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void doLoad(InputStream inputStream, Map<?, ?> options) throws IOException {
	String encoding = getEncoding(getURI(), options);
	InputStreamReader inputStreamReader = new InputStreamReader(inputStream, encoding);
	contentsAsString = CharStreams.toString(inputStreamReader);
	compilationUnit = new CompilationUnit(contentsAsString.toCharArray(), getURI().lastSegment(), encoding, null);
}
 
Example #9
Source File: EcjParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Node parseJava(@NonNull JavaContext context) {
    String code = context.getContents();
    if (code == null) {
        return null;
    }

    CompilationUnitDeclaration unit = getParsedUnit(context, code);
    try {
        EcjTreeConverter converter = new EcjTreeConverter();
        converter.visit(code, unit);
        List<? extends Node> nodes = converter.getAll();

        if (nodes != null) {
            // There could be more than one node when there are errors; pick out the
            // compilation unit node
            for (Node node : nodes) {
                if (node instanceof lombok.ast.CompilationUnit) {
                    return node;
                }
            }
        }

        return null;
    } catch (Throwable t) {
        mClient.log(t, "Failed converting ECJ parse tree to Lombok for file %1$s",
                context.file.getPath());
        return null;
    }
}
 
Example #10
Source File: ExtractAnnotationsDriver.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
private static Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> parseSources(
        @NonNull List<File> sourcePaths,
        @NonNull List<String> classpath,
        @NonNull String encoding,
        long languageLevel)
        throws IOException {
    List<ICompilationUnit> sourceUnits = Lists.newArrayListWithExpectedSize(100);

    for (File source : gatherJavaSources(sourcePaths)) {
        char[] contents = Util.getFileCharContent(source, encoding);
        ICompilationUnit unit = new CompilationUnit(contents, source.getPath(), encoding);
        sourceUnits.add(unit);
    }

    Map<ICompilationUnit, CompilationUnitDeclaration> outputMap = Maps.newHashMapWithExpectedSize(
            sourceUnits.size());

    CompilerOptions options = EcjParser.createCompilerOptions();
    options.docCommentSupport = true; // So I can find @hide

    // Note: We can *not* set options.ignoreMethodBodies=true because it disables
    // type attribution!

    options.sourceLevel = languageLevel;
    options.complianceLevel = options.sourceLevel;
    // We don't generate code, but just in case the parser consults this flag
    // and makes sure that it's not greater than the source level:
    options.targetJDK = options.sourceLevel;
    options.originalComplianceLevel = options.sourceLevel;
    options.originalSourceLevel = options.sourceLevel;
    options.inlineJsrBytecode = true; // >= 1.5

    INameEnvironment environment = EcjParser.parse(options, sourceUnits, classpath,
            outputMap, null);
    Collection<CompilationUnitDeclaration> parsedUnits = outputMap.values();
    return Pair.of(parsedUnits, environment);
}
 
Example #11
Source File: JavaResource.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected CompilationUnit getCompilationUnit() {
	return compilationUnit;
}
 
Example #12
Source File: CompilationUtils.java    From steady with Apache License 2.0 4 votes vote down vote up
private static ICompilationUnit createCompilationunit(String _source_code, String filename) {
	char[] source_code = _source_code.toCharArray();
    ICompilationUnit cu = new CompilationUnit(source_code, filename, null);
    return cu;
}
 
Example #13
Source File: EclipseCompilerImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected void initialize(PrintWriter outWriter, PrintWriter errWriter, boolean systemExit, Map customDefaultOptions, CompilationProgress compilationProgress) {
	super.initialize(outWriter, errWriter, systemExit, customDefaultOptions, compilationProgress);
	this.javaFileObjectMap = new HashMap<CompilationUnit, JavaFileObject>();
}
 
Example #14
Source File: JavaDerivedStateComputer.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
public CompilationUnit getCompilationUnit(Resource resource) {
	return ((JavaResource) resource).getCompilationUnit();
}
 
Example #15
Source File: CodeSnippetParsingUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public CompilationUnitDeclaration parseCompilationUnit(char[] source, Map settings, boolean recordParsingInformation) {
	if (source == null) {
		throw new IllegalArgumentException();
	}
	CompilerOptions compilerOptions = new CompilerOptions(settings);
	compilerOptions.ignoreMethodBodies = this.ignoreMethodBodies;
	CommentRecorderParser parser =
		new CommentRecorderParser(
			new ProblemReporter(
				DefaultErrorHandlingPolicies.proceedWithAllProblems(),
				compilerOptions,
				new DefaultProblemFactory(Locale.getDefault())),
		false);

	ICompilationUnit sourceUnit =
		new CompilationUnit(
			source,
			"", //$NON-NLS-1$
			compilerOptions.defaultEncoding);
	final CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
	CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult);

	if (recordParsingInformation) {
		this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments);
	}

	if (compilationUnitDeclaration.ignoreMethodBodies) {
		compilationUnitDeclaration.ignoreFurtherInvestigation = true;
		// if initial diet parse did not work, no need to dig into method bodies.
		return compilationUnitDeclaration;
	}

	//fill the methods bodies in order for the code to be generated
	//real parse of the method....
	parser.scanner.setSource(compilationResult);
	org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types;
	if (types != null) {
		for (int i = 0, length = types.length; i < length; i++) {
			types[i].parseMethods(parser, compilationUnitDeclaration);
		}
	}

	if (recordParsingInformation) {
		this.recordedParsingInformation.updateRecordedParsingInformation(compilationResult);
	}
	return compilationUnitDeclaration;
}
 
Example #16
Source File: CodeSnippetParsingUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public ConstructorDeclaration parseStatements(
		char[] source,
		int offset,
		int length,
		Map settings,
		boolean recordParsingInformation,
		boolean enabledStatementRecovery) {
	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 statements
	final ProblemReporter problemReporter = new ProblemReporter(
				DefaultErrorHandlingPolicies.proceedWithAllProblems(),
				compilerOptions,
				new DefaultProblemFactory(Locale.getDefault()));
	CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false);
	parser.setMethodsFullRecovery(false);
	parser.setStatementsRecovery(enabledStatementRecovery);

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

	final CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
	CompilationUnitDeclaration compilationUnitDeclaration = new CompilationUnitDeclaration(problemReporter, compilationResult, length);

	ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration(compilationResult);
	constructorDeclaration.sourceEnd  = -1;
	constructorDeclaration.declarationSourceEnd = offset + length - 1;
	constructorDeclaration.bodyStart = offset;
	constructorDeclaration.bodyEnd = offset + length - 1;

	parser.scanner.setSource(compilationResult);
	parser.scanner.resetTo(offset, offset + length);
	parser.parse(constructorDeclaration, compilationUnitDeclaration, true);

	if (recordParsingInformation) {
		this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments);
	}
	return constructorDeclaration;
}
 
Example #17
Source File: CompilerJdt.java    From takari-lifecycle with Eclipse Public License 1.0 4 votes vote down vote up
private CompilationUnit newSourceFile(File source) {
  final String fileName = source.getAbsolutePath();
  final String encoding = getSourceEncoding() != null ? getSourceEncoding().name() : null;
  return new CompilationUnit(null /* contents */, fileName, encoding, getOutputDirectory().getAbsolutePath(), false /* ignoreOptionalProblems */, null /* modName */);
}
 
Example #18
Source File: ExtractAnnotations.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@NonNull
private Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> parseSources() {
    final List<ICompilationUnit> sourceUnits = Lists.newArrayListWithExpectedSize(100);

    getSource().visit(new EmptyFileVisitor() {
        @Override
        public void visitFile(FileVisitDetails fileVisitDetails) {
            File file = fileVisitDetails.getFile();
            String path = file.getPath();
            if (path.endsWith(DOT_JAVA) && file.isFile()) {
                char[] contents = new char[0];
                try {
                    contents = Util.getFileCharContent(file, encoding);
                    ICompilationUnit unit = new CompilationUnit(contents, path, encoding);
                    sourceUnits.add(unit);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    });

    Map<ICompilationUnit, CompilationUnitDeclaration> outputMap = Maps.newHashMapWithExpectedSize(((ArrayList<ICompilationUnit>) sourceUnits).size());
    List<String> jars = Lists.newArrayList();
    if (bootClasspath != null) {
        ((ArrayList<String>) jars).addAll(bootClasspath);
    }

    if (getClasspath() != null) {
        for (File jar : getClasspath()) {
            ((ArrayList<String>) jars).add(jar.getPath());
        }

    }


    CompilerOptions options = EcjParser.createCompilerOptions();
    options.docCommentSupport = true;// So I can find @hide

    // Note: We can *not* set options.ignoreMethodBodies=true because it disables
    // type attribution!

    long level = getLanguageLevel(getSourceCompatibility());
    options.sourceLevel = level;
    options.complianceLevel = options.sourceLevel;
    // We don't generate code, but just in case the parser consults this flag
    // and makes sure that it's not greater than the source level:
    options.targetJDK = options.sourceLevel;
    options.originalComplianceLevel = options.sourceLevel;
    options.originalSourceLevel = options.sourceLevel;
    options.inlineJsrBytecode = true;// >= 1.5

    INameEnvironment environment = EcjParser.parse(options, sourceUnits, jars, outputMap, null);
    Collection<CompilationUnitDeclaration> parsedUnits = ((HashMap<ICompilationUnit, CompilationUnitDeclaration>) outputMap).values();
    return Pair.of(parsedUnits, environment);
}