use of org.eclipse.jdt.internal.compiler.CompilationResult in project xtext-eclipse by eclipse.
the class InMemoryJavaCompiler method compile.
public Result compile(JavaSource... sources) {
Result result = new Result(parentClassLoader);
ICompilerRequestor requestor = (CompilationResult it) -> {
for (ClassFile cf : it.getClassFiles()) {
result.classMap.put(CharOperation.toString(cf.getCompoundName()), cf.getBytes());
}
};
org.eclipse.jdt.internal.compiler.Compiler compiler = new org.eclipse.jdt.internal.compiler.Compiler(nameEnv, DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, requestor, new DefaultProblemFactory() {
@Override
public CategorizedProblem createProblem(char[] originatingFileName, int problemId, String[] problemArguments, int elaborationId, String[] messageArguments, int severity, int startPosition, int endPosition, int lineNumber, int columnNumber) {
CategorizedProblem problem = super.createProblem(originatingFileName, problemId, problemArguments, elaborationId, messageArguments, severity, startPosition, endPosition, lineNumber, columnNumber);
result.compilationProblems.add(problem);
return problem;
}
@Override
public CategorizedProblem createProblem(char[] originatingFileName, int problemId, String[] problemArguments, String[] messageArguments, int severity, int startPosition, int endPosition, int lineNumber, int columnNumber) {
CategorizedProblem problem = super.createProblem(originatingFileName, problemId, problemArguments, messageArguments, severity, startPosition, endPosition, lineNumber, columnNumber);
result.compilationProblems.add(problem);
return problem;
}
});
ICompilationUnit[] units = ((ICompilationUnit[]) Conversions.unwrapArray(ListExtensions.map(Arrays.asList(sources), (JavaSource it) -> new CompilationUnit(it.getCode().toCharArray(), it.getFileName(), null)), ICompilationUnit.class));
compiler.compile(units);
return result;
}
use of org.eclipse.jdt.internal.compiler.CompilationResult in project lombok by rzwitserloot.
the class PatchVal method handleValForLocalDeclaration.
public static boolean handleValForLocalDeclaration(LocalDeclaration local, BlockScope scope) {
if (local == null || !LocalDeclaration.class.equals(local.getClass()))
return false;
boolean decomponent = false;
boolean val = isVal(local, scope);
boolean var = isVar(local, scope);
if (!(val || var))
return false;
if (val) {
StackTraceElement[] st = new Throwable().getStackTrace();
for (int i = 0; i < st.length - 2 && i < 10; i++) {
if (st[i].getClassName().equals("lombok.launch.PatchFixesHider$Val")) {
boolean valInForStatement = st[i + 1].getClassName().equals("org.eclipse.jdt.internal.compiler.ast.LocalDeclaration") && st[i + 2].getClassName().equals("org.eclipse.jdt.internal.compiler.ast.ForStatement");
if (valInForStatement)
return false;
break;
}
}
}
Expression init = local.initialization;
if (init == null && Reflection.initCopyField != null) {
try {
init = (Expression) Reflection.initCopyField.get(local);
} catch (Exception e) {
// init remains null.
}
}
if (init == null && Reflection.iterableCopyField != null) {
try {
init = (Expression) Reflection.iterableCopyField.get(local);
decomponent = true;
} catch (Exception e) {
// init remains null.
}
}
TypeReference replacement = null;
// Java 10+: Lombok uses the native 'var' support and transforms 'val' to 'final var'.
if (hasNativeVarSupport(scope) && val) {
replacement = new SingleTypeReference("var".toCharArray(), pos(local.type));
local.initialization = init;
init = null;
}
if (init != null) {
if (init.getClass().getName().equals("org.eclipse.jdt.internal.compiler.ast.LambdaExpression")) {
return false;
}
TypeBinding resolved = null;
try {
resolved = decomponent ? getForEachComponentType(init, scope) : resolveForExpression(init, scope);
} catch (NullPointerException e) {
// This definitely occurs if as part of resolving the initializer expression, a
// lambda expression in it must also be resolved (such as when lambdas are part of
// a ternary expression). This can't result in a viable 'val' matching, so, we
// just go with 'Object' and let the IDE print the appropriate errors.
resolved = null;
}
if (resolved == null) {
if (init instanceof ConditionalExpression) {
ConditionalExpression cexp = (ConditionalExpression) init;
Expression ifTrue = cexp.valueIfTrue;
Expression ifFalse = cexp.valueIfFalse;
TypeBinding ifTrueResolvedType = ifTrue.resolvedType;
CompilationResult compilationResult = scope.referenceCompilationUnit().compilationResult;
CategorizedProblem[] problems = compilationResult.problems;
CategorizedProblem lastProblem = problems[compilationResult.problemCount - 1];
if (ifTrueResolvedType != null && ifFalse.resolvedType == null && lastProblem.getCategoryID() == CAT_TYPE) {
int problemCount = compilationResult.problemCount;
for (int i = 0; i < problemCount; ++i) {
if (problems[i] == lastProblem) {
problems[i] = null;
if (i + 1 < problemCount) {
System.arraycopy(problems, i + 1, problems, i, problemCount - i + 1);
}
break;
}
}
compilationResult.removeProblem(lastProblem);
if (!compilationResult.hasErrors()) {
clearIgnoreFurtherInvestigationField(scope.referenceContext());
setValue(getField(CompilationResult.class, "hasMandatoryErrors"), compilationResult, false);
}
if (ifFalse instanceof FunctionalExpression) {
FunctionalExpression functionalExpression = (FunctionalExpression) ifFalse;
functionalExpression.setExpectedType(ifTrueResolvedType);
}
if (ifFalse.resolvedType == null) {
resolveForExpression(ifFalse, scope);
}
resolved = ifTrueResolvedType;
}
}
}
if (resolved != null) {
try {
replacement = makeType(resolved, local.type, false);
if (!decomponent)
init.resolvedType = replacement.resolveType(scope);
} catch (Exception e) {
// Some type thing failed.
}
}
}
if (val)
local.modifiers |= ClassFileConstants.AccFinal;
local.annotations = addValAnnotation(local.annotations, local.type, scope);
local.type = replacement != null ? replacement : new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(local.type, 3));
return false;
}
use of org.eclipse.jdt.internal.compiler.CompilationResult in project tomcat by apache.
the class JDTCompiler method generateClass.
/**
* Compile the servlet from .java file to .class file
*/
@Override
protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception {
long t1 = 0;
if (log.isDebugEnabled()) {
t1 = System.currentTimeMillis();
}
final String sourceFile = ctxt.getServletJavaFileName();
final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
String packageName = ctxt.getServletPackageName();
final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName();
final ClassLoader classLoader = ctxt.getJspLoader();
String[] fileNames = new String[] { sourceFile };
String[] classNames = new String[] { targetClassName };
final ArrayList<JavacErrorDetail> problemList = new ArrayList<>();
class CompilationUnit implements ICompilationUnit {
private final String className;
private final String sourceFile;
CompilationUnit(String sourceFile, String className) {
this.className = className;
this.sourceFile = sourceFile;
}
@Override
public char[] getFileName() {
return sourceFile.toCharArray();
}
@Override
public char[] getContents() {
char[] result = null;
try (FileInputStream is = new FileInputStream(sourceFile);
InputStreamReader isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding());
Reader reader = new BufferedReader(isr)) {
char[] chars = new char[8192];
StringBuilder buf = new StringBuilder();
int count;
while ((count = reader.read(chars, 0, chars.length)) > 0) {
buf.append(chars, 0, count);
}
result = new char[buf.length()];
buf.getChars(0, result.length, result, 0);
} catch (IOException e) {
log.error("Compilation error", e);
}
return result;
}
@Override
public char[] getMainTypeName() {
int dot = className.lastIndexOf('.');
if (dot > 0) {
return className.substring(dot + 1).toCharArray();
}
return className.toCharArray();
}
@Override
public char[][] getPackageName() {
StringTokenizer izer = new StringTokenizer(className, ".");
char[][] result = new char[izer.countTokens() - 1][];
for (int i = 0; i < result.length; i++) {
String tok = izer.nextToken();
result[i] = tok.toCharArray();
}
return result;
}
@Override
public boolean ignoreOptionalProblems() {
return false;
}
}
final INameEnvironment env = new INameEnvironment() {
@Override
public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < compoundTypeName.length; i++) {
if (i > 0)
result.append('.');
result.append(compoundTypeName[i]);
}
return findType(result.toString());
}
@Override
public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
StringBuilder result = new StringBuilder();
int i = 0;
for (; i < packageName.length; i++) {
if (i > 0)
result.append('.');
result.append(packageName[i]);
}
if (i > 0)
result.append('.');
result.append(typeName);
return findType(result.toString());
}
private NameEnvironmentAnswer findType(String className) {
if (className.equals(targetClassName)) {
ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
return new NameEnvironmentAnswer(compilationUnit, null);
}
String resourceName = className.replace('.', '/') + ".class";
try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
if (is != null) {
byte[] classBytes;
byte[] buf = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
int count;
while ((count = is.read(buf, 0, buf.length)) > 0) {
baos.write(buf, 0, count);
}
baos.flush();
classBytes = baos.toByteArray();
char[] fileName = className.toCharArray();
ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
return new NameEnvironmentAnswer(classFileReader, null);
}
} catch (IOException exc) {
log.error("Compilation error", exc);
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
log.error("Compilation error", exc);
}
return null;
}
private boolean isPackage(String result) {
if (result.equals(targetClassName)) {
return false;
}
String resourceName = result.replace('.', '/') + ".class";
try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
return is == null;
} catch (IOException e) {
// we are here, since close on is failed. That means it was not null
return false;
}
}
@Override
public boolean isPackage(char[][] parentPackageName, char[] packageName) {
StringBuilder result = new StringBuilder();
int i = 0;
if (parentPackageName != null) {
for (; i < parentPackageName.length; i++) {
if (i > 0)
result.append('.');
result.append(parentPackageName[i]);
}
}
if (Character.isUpperCase(packageName[0])) {
if (!isPackage(result.toString())) {
return false;
}
}
if (i > 0)
result.append('.');
result.append(packageName);
return isPackage(result.toString());
}
@Override
public void cleanup() {
}
};
final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
final Map<String, String> settings = new HashMap<>();
settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
if (ctxt.getOptions().getJavaEncoding() != null) {
settings.put(CompilerOptions.OPTION_Encoding, ctxt.getOptions().getJavaEncoding());
}
if (ctxt.getOptions().getClassDebugInfo()) {
settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
}
// Source JVM
if (ctxt.getOptions().getCompilerSourceVM() != null) {
String opt = ctxt.getOptions().getCompilerSourceVM();
if (opt.equals("1.1")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
} else if (opt.equals("1.2")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
} else if (opt.equals("1.3")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
} else if (opt.equals("1.4")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
} else if (opt.equals("1.5")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
} else if (opt.equals("1.6")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
} else if (opt.equals("1.7")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
} else if (opt.equals("1.8")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
} else if (opt.equals("1.9")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_9);
} else {
log.warn("Unknown source VM " + opt + " ignored.");
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
}
} else {
// Default to 1.8
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
}
// Target JVM
if (ctxt.getOptions().getCompilerTargetVM() != null) {
String opt = ctxt.getOptions().getCompilerTargetVM();
if (opt.equals("1.1")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
} else if (opt.equals("1.2")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
} else if (opt.equals("1.3")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
} else if (opt.equals("1.4")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
} else if (opt.equals("1.5")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
} else if (opt.equals("1.6")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
} else if (opt.equals("1.7")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
} else if (opt.equals("1.8")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
} else if (opt.equals("1.9")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_9);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_9);
} else {
log.warn("Unknown target VM " + opt + " ignored.");
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
}
} else {
// Default to 1.8
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
}
final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
final ICompilerRequestor requestor = new ICompilerRequestor() {
@Override
public void acceptResult(CompilationResult result) {
try {
if (result.hasProblems()) {
IProblem[] problems = result.getProblems();
for (int i = 0; i < problems.length; i++) {
IProblem problem = problems[i];
if (problem.isError()) {
String name = new String(problems[i].getOriginatingFileName());
try {
problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuilder(problem.getMessage()), problem.getSourceLineNumber(), ctxt));
} catch (JasperException e) {
log.error("Error visiting node", e);
}
}
}
}
if (problemList.isEmpty()) {
ClassFile[] classFiles = result.getClassFiles();
for (int i = 0; i < classFiles.length; i++) {
ClassFile classFile = classFiles[i];
char[][] compoundName = classFile.getCompoundName();
StringBuilder classFileName = new StringBuilder(outputDir).append('/');
for (int j = 0; j < compoundName.length; j++) {
if (j > 0)
classFileName.append('/');
classFileName.append(compoundName[j]);
}
byte[] bytes = classFile.getBytes();
classFileName.append(".class");
try (FileOutputStream fout = new FileOutputStream(classFileName.toString());
BufferedOutputStream bos = new BufferedOutputStream(fout)) {
bos.write(bytes);
}
}
}
} catch (IOException exc) {
log.error("Compilation error", exc);
}
}
};
ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length];
for (int i = 0; i < compilationUnits.length; i++) {
String className = classNames[i];
compilationUnits[i] = new CompilationUnit(fileNames[i], className);
}
CompilerOptions cOptions = new CompilerOptions(settings);
cOptions.parseLiteralExpressionsAsConstants = true;
Compiler compiler = new Compiler(env, policy, cOptions, requestor, problemFactory);
compiler.compile(compilationUnits);
if (!ctxt.keepGenerated()) {
File javaFile = new File(ctxt.getServletJavaFileName());
javaFile.delete();
}
if (!problemList.isEmpty()) {
JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
errDispatcher.javacError(jeds);
}
if (log.isDebugEnabled()) {
long t2 = System.currentTimeMillis();
log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
}
if (ctxt.isPrototypeMode()) {
return;
}
// JSR45 Support
if (!options.isSmapSuppressed()) {
SmapUtil.installSmap(smap);
}
}
use of org.eclipse.jdt.internal.compiler.CompilationResult 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);
}
use of org.eclipse.jdt.internal.compiler.CompilationResult in project spoon by INRIA.
the class PositionBuilder method buildPositionCtElement.
SourcePosition buildPositionCtElement(CtElement e, ASTNode node) {
CoreFactory cf = this.jdtTreeBuilder.getFactory().Core();
CompilationUnit cu = this.jdtTreeBuilder.getFactory().CompilationUnit().getOrCreate(new String(this.jdtTreeBuilder.getContextBuilder().compilationunitdeclaration.getFileName()));
CompilationResult cr = this.jdtTreeBuilder.getContextBuilder().compilationunitdeclaration.compilationResult;
int[] lineSeparatorPositions = cr.lineSeparatorPositions;
char[] contents = cr.compilationUnit.getContents();
int sourceStart = node.sourceStart;
int sourceEnd = node.sourceEnd;
if ((node instanceof Annotation)) {
Annotation ann = (Annotation) node;
int declEnd = ann.declarationSourceEnd;
if (declEnd > 0) {
sourceEnd = declEnd;
}
} else if ((node instanceof Expression)) {
Expression expression = (Expression) node;
int statementEnd = expression.statementEnd;
if (statementEnd > 0) {
sourceEnd = statementEnd;
}
}
if (node instanceof AbstractVariableDeclaration) {
AbstractVariableDeclaration variableDeclaration = (AbstractVariableDeclaration) node;
int modifiersSourceStart = variableDeclaration.modifiersSourceStart;
int declarationSourceStart = variableDeclaration.declarationSourceStart;
int declarationSourceEnd = variableDeclaration.declarationSourceEnd;
int declarationEnd = variableDeclaration.declarationEnd;
Annotation[] annotations = variableDeclaration.annotations;
if (annotations != null && annotations.length > 0) {
if (annotations[0].sourceStart() == sourceStart) {
modifiersSourceStart = annotations[annotations.length - 1].sourceEnd() + 2;
}
}
if (modifiersSourceStart == 0) {
modifiersSourceStart = declarationSourceStart;
}
int modifiersSourceEnd;
if (variableDeclaration.type != null) {
modifiersSourceEnd = variableDeclaration.type.sourceStart() - 2;
} else {
// variable that has no type such as TypeParameter
modifiersSourceEnd = declarationSourceStart - 1;
}
// when no modifier
if (modifiersSourceStart > modifiersSourceEnd) {
modifiersSourceEnd = modifiersSourceStart - 1;
}
return cf.createDeclarationSourcePosition(cu, sourceStart, sourceEnd, modifiersSourceStart, modifiersSourceEnd, declarationSourceStart, declarationSourceEnd, lineSeparatorPositions);
} else if (node instanceof TypeDeclaration) {
TypeDeclaration typeDeclaration = (TypeDeclaration) node;
int declarationSourceStart = typeDeclaration.declarationSourceStart;
int declarationSourceEnd = typeDeclaration.declarationSourceEnd;
int modifiersSourceStart = typeDeclaration.modifiersSourceStart;
int bodyStart = typeDeclaration.bodyStart;
int bodyEnd = typeDeclaration.bodyEnd;
Annotation[] annotations = typeDeclaration.annotations;
if (annotations != null && annotations.length > 0) {
if (annotations[0].sourceStart() == declarationSourceStart) {
modifiersSourceStart = findNextNonWhitespace(contents, annotations[annotations.length - 1].declarationSourceEnd + 1);
}
}
if (modifiersSourceStart == 0) {
modifiersSourceStart = declarationSourceStart;
}
// look for start of first keyword before the type keyword e.g. "class". `sourceStart` points at first char of type name
int modifiersSourceEnd = findPrevNonWhitespace(contents, findPrevWhitespace(contents, findPrevNonWhitespace(contents, sourceStart - 1)));
if (modifiersSourceEnd < modifiersSourceStart) {
// there is no modifier
modifiersSourceEnd = modifiersSourceStart - 1;
}
return cf.createBodyHolderSourcePosition(cu, sourceStart, sourceEnd, modifiersSourceStart, modifiersSourceEnd, declarationSourceStart, declarationSourceEnd, bodyStart - 1, bodyEnd, lineSeparatorPositions);
} else if (node instanceof AbstractMethodDeclaration) {
AbstractMethodDeclaration methodDeclaration = (AbstractMethodDeclaration) node;
int bodyStart = methodDeclaration.bodyStart;
int bodyEnd = methodDeclaration.bodyEnd;
int declarationSourceStart = methodDeclaration.declarationSourceStart;
int declarationSourceEnd = methodDeclaration.declarationSourceEnd;
int modifiersSourceStart = methodDeclaration.modifiersSourceStart;
if (modifiersSourceStart == 0) {
modifiersSourceStart = declarationSourceStart;
}
if (node instanceof AnnotationMethodDeclaration && bodyStart == bodyEnd) {
// The ";" at the end of annotation method declaration is not part of body
// let it behave same like in abstract MethodDeclaration
bodyEnd--;
}
Javadoc javadoc = methodDeclaration.javadoc;
if (javadoc != null && javadoc.sourceEnd() > declarationSourceStart) {
modifiersSourceStart = javadoc.sourceEnd() + 1;
}
Annotation[] annotations = methodDeclaration.annotations;
if (annotations != null && annotations.length > 0) {
if (annotations[0].sourceStart() == declarationSourceStart) {
modifiersSourceStart = annotations[annotations.length - 1].sourceEnd() + 2;
}
}
int modifiersSourceEnd = sourceStart - 1;
if (methodDeclaration instanceof MethodDeclaration && ((MethodDeclaration) methodDeclaration).returnType != null) {
modifiersSourceEnd = ((MethodDeclaration) methodDeclaration).returnType.sourceStart() - 2;
}
TypeParameter[] typeParameters = methodDeclaration.typeParameters();
if (typeParameters != null && typeParameters.length > 0) {
modifiersSourceEnd = typeParameters[0].declarationSourceStart - 3;
}
if (getModifiers(methodDeclaration.modifiers, false, true).isEmpty()) {
modifiersSourceStart = modifiersSourceEnd + 1;
}
sourceEnd = sourceStart + methodDeclaration.selector.length - 1;
if (e instanceof CtStatementList) {
return cf.createSourcePosition(cu, bodyStart - 1, bodyEnd + 1, lineSeparatorPositions);
} else {
if (bodyStart == 0) {
return SourcePosition.NOPOSITION;
} else {
if (bodyStart < bodyEnd) {
// include brackets if they are there
if (contents[bodyStart - 1] == '{') {
bodyStart--;
if (contents[bodyEnd + 1] == '}') {
bodyEnd++;
} else {
throw new SpoonException("Missing body end in\n" + new String(contents, sourceStart, sourceEnd - sourceStart));
}
}
}
return cf.createBodyHolderSourcePosition(cu, sourceStart, sourceEnd, modifiersSourceStart, modifiersSourceEnd, declarationSourceStart, declarationSourceEnd, bodyStart, bodyEnd, lineSeparatorPositions);
}
}
}
return cf.createSourcePosition(cu, sourceStart, sourceEnd, lineSeparatorPositions);
}
Aggregations