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

The following examples show how to use org.eclipse.jdt.internal.compiler.Compiler. 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: CompilerJdt.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public int compile(Classpath namingEnvironment, Compiler compiler) throws IOException {
  processSources();

  if (aptstate != null) {
    staleOutputs.addAll(aptstate.writtenOutputs);
    aptstate = null;
  }

  if (!compileQueue.isEmpty()) {
    ICompilationUnit[] compilationUnits = compileQueue.values().toArray(new ICompilationUnit[compileQueue.size()]);
    compiler.compile(compilationUnits);
  }

  persistAnnotationProcessingState(compiler, null);

  deleteStaleOutputs();

  return compileQueue.size();
}
 
Example #2
Source File: CompilerJdt.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This loop handles the incremental compilation of classes in the compileQueue. Regular apt rounds may occur in this loop, but the apt final round will not.
 * 
 * This loop will be called once after the apt final round is processed to compile all effected types. All prior error/warn/info messages, referenced types, generated outputs and other per-input
 * information tracked by in build context are ignored when a type is recompiled.
 */
private void incrementalCompilationLoop(Classpath namingEnvironment, Compiler compiler, AnnotationProcessorManager aptmanager) throws IOException {
  while (!compileQueue.isEmpty() || !staleOutputs.isEmpty()) {
    processedQueue.clear();
    processedQueue.addAll(compileQueue.keySet());

    // All prior error/warn/info messages, referenced types, generated outputs and other per-input information tracked by in build context are wiped away within.
    processSources();

    // invoke the compiler
    ICompilationUnit[] compilationUnits = compileQueue.values().toArray(new ICompilationUnit[compileQueue.size()]);
    compileQueue.clear();
    compiler.compile(compilationUnits);
    namingEnvironment.reset();

    if (aptmanager != null) {
      aptmanager.incrementalIterationReset();
    }

    deleteStaleOutputs(); // delete stale outputs and enqueue affected sources

    enqueueAffectedSources();
  }
}
 
Example #3
Source File: AppCompiler.java    From actframework with Apache License 2.0 6 votes vote down vote up
public void compile(String className) {
    Timer timer = metric.startTimer("act:classload:compile:" + className);
    ICompilationUnit[] compilationUnits = new ICompilationUnit[1];
    compilationUnits[0] = classLoader.source(className).compilationUnit();
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH);

    org.eclipse.jdt.internal.compiler.Compiler jdtCompiler = new Compiler(
            nameEnv, policy, compilerOptions, requestor, problemFactory) {
        @Override
        protected void handleInternalException(Throwable e, CompilationUnitDeclaration ud, CompilationResult result) {
        }
    };

    jdtCompiler.compile(compilationUnits);
    timer.stop();
}
 
Example #4
Source File: AppCompiler.java    From actframework with Apache License 2.0 6 votes vote down vote up
public void compile(Collection<Source> sources) {
    Timer timer = metric.startTimer("act:classload:compile:_all");
    int len = sources.size();
    ICompilationUnit[] compilationUnits = new ICompilationUnit[len];
    int i = 0;
    for (Source source: sources) {
        compilationUnits[i++] = source.compilationUnit();
    }
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH);

    org.eclipse.jdt.internal.compiler.Compiler jdtCompiler = new Compiler(
            nameEnv, policy, compilerOptions, requestor, problemFactory) {
        @Override
        protected void handleInternalException(Throwable e, CompilationUnitDeclaration ud, CompilationResult result) {
        }
    };

    jdtCompiler.compile(compilationUnits);
    timer.stop();
}
 
Example #5
Source File: JdtCompiler.java    From jetbrick-template-1x with Apache License 2.0 5 votes vote down vote up
@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();
            int column = start; // default
            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());
}
 
Example #6
Source File: JRJdtCompiler.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected String compileUnits(final JRCompilationUnit[] units, String classpath, File tempDirFile)
{
	final INameEnvironment env = getNameEnvironment(units);

	final IErrorHandlingPolicy policy = 
		DefaultErrorHandlingPolicies.proceedWithAllProblems();

	final CompilerOptions options = new CompilerOptions(getJdtSettings());

	final IProblemFactory problemFactory = 
		new DefaultProblemFactory(Locale.getDefault());

	final CompilerRequestor requestor = getCompilerRequestor(units);

	final Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);

	do
	{
		CompilationUnit[] compilationUnits = requestor.processCompilationUnits();

		compiler.compile(compilationUnits);
	}
	while (requestor.hasMissingMethods());
	
	requestor.processProblems();

	return requestor.getFormattedProblems();
}
 
Example #7
Source File: FilerImplTest.java    From takari-lifecycle with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testBinaryOriginatingElements() throws Exception {
  // the point of this test is to assert Filer#createSourceFile does not puke when originatingElements are not sources

  // originating source elements are used to cleanup generated outputs when corresponding sources change
  // originating binary elements are not currently fully supported and are not tracked during incremental build

  Classpath namingEnvironment = createClasspath();
  IErrorHandlingPolicy errorHandlingPolicy = DefaultErrorHandlingPolicies.exitAfterAllProblems();
  IProblemFactory problemFactory = ProblemFactory.getProblemFactory(Locale.getDefault());
  CompilerOptions compilerOptions = new CompilerOptions();
  ICompilerRequestor requestor = null;
  Compiler compiler = new Compiler(namingEnvironment, errorHandlingPolicy, compilerOptions, requestor, problemFactory);

  EclipseFileManager fileManager = new EclipseFileManager(null, Charsets.UTF_8);
  File outputDir = temp.newFolder();
  fileManager.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(outputDir));

  CompilerBuildContext context = null;
  Map<String, String> processorOptions = null;
  CompilerJdt incrementalCompiler = null;
  ProcessingEnvImpl env = new ProcessingEnvImpl(context, fileManager, processorOptions, compiler, incrementalCompiler);

  TypeElement typeElement = env.getElementUtils().getTypeElement("java.lang.Object");

  FilerImpl filer = new FilerImpl(null /* context */, fileManager, null /* compiler */, null /* env */);
  filer.createSourceFile("test.Source", typeElement);
}
 
Example #8
Source File: CompilerJdt.java    From takari-lifecycle with Eclipse Public License 1.0 5 votes vote down vote up
private void persistAnnotationProcessingState(Compiler compiler, AnnotationProcessingState carryOverState) {
  if (compiler.annotationProcessorManager == null) {
    return; // not processing annotations
  }
  final AnnotationProcessingState aptstate;
  if (carryOverState != null) {
    // incremental build did not need to process annotations, carry over the state and outputs to the next build
    aptstate = carryOverState;
    aptstate.writtenOutputs.forEach(context::markUptodateOutput);
  } else {
    AnnotationProcessorManager aptmanager = (AnnotationProcessorManager) compiler.annotationProcessorManager;
    aptstate = new AnnotationProcessingState(aptmanager.getProcessedSources(), aptmanager.getReferencedTypes(), aptmanager.getWittenOutputs());
  }
  context.setAttribute(ATTR_APTSTATE, aptstate);
}
 
Example #9
Source File: CompilerJdt.java    From takari-lifecycle with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public int compile(Classpath namingEnvironment, Compiler compiler) throws IOException {
  AnnotationProcessorManager aptmanager = (AnnotationProcessorManager) compiler.annotationProcessorManager;

  if (aptmanager != null) {
    // suppress APT lastRound during incremental compile loop
    aptmanager.suppressLastRound(true);
  }

  // incremental compilation loop
  // keep calling the compiler while there are sources in the queue
  incrementalCompilationLoop(namingEnvironment, compiler, aptmanager);

  // run apt last round iff doing annotation processing and ran regular apt rounds
  if (aptmanager != null && aptstate == null) {
    // tell apt manager we are running APT lastRound
    aptmanager.suppressRegularRounds(true);
    aptmanager.suppressLastRound(false);

    // even if a class was processed it would need recompiled once types are generated.
    processedQueue.clear();

    // trick the compiler to run APT without any source or binary types
    compiler.referenceBindings = new ReferenceBinding[0];
    compiler.compile(new ICompilationUnit[0]);
    namingEnvironment.reset();
    aptmanager.incrementalIterationReset();
    deleteStaleOutputs();

    enqueueAffectedSources();
    // all apt rounds are now suppressed.
    aptmanager.suppressLastRound(true);
    // compile class that rely on apt completing
    incrementalCompilationLoop(namingEnvironment, compiler, aptmanager);
  }

  persistAnnotationProcessingState(compiler, aptstate);

  return processedSources.size();
}
 
Example #10
Source File: Evaluator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates and returns a compiler for this evaluator.
 */
Compiler getCompiler(ICompilerRequestor compilerRequestor) {
	CompilerOptions compilerOptions = new CompilerOptions(this.options);
	compilerOptions.performMethodsFullRecovery = true;
	compilerOptions.performStatementsRecovery = true;
	return new Compiler(
		this.environment,
		DefaultErrorHandlingPolicies.exitAfterAllProblems(),
		compilerOptions,
		compilerRequestor,
		this.problemFactory);
}
 
Example #11
Source File: AbstractImageBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void initializeAnnotationProcessorManager(Compiler newCompiler) {
	AbstractAnnotationProcessorManager annotationManager = JavaModelManager.getJavaModelManager().createAnnotationProcessorManager();
	if (annotationManager != null) {
		annotationManager.configureFromPlatform(newCompiler, this, this.javaBuilder.javaProject);
		annotationManager.setErr(new PrintWriter(System.err));
		annotationManager.setOut(new PrintWriter(System.out));
	}
	newCompiler.annotationProcessorManager = annotationManager;
}
 
Example #12
Source File: BindingKeyResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private BindingKeyResolver(BindingKeyParser parser, Compiler compiler, LookupEnvironment environment, CompilationUnitDeclaration outerMostParsedUnit, HashtableOfObject parsedUnits) {
	super(parser);
	this.compiler = compiler;
	this.environment = environment;
	this.outerMostParsedUnit = outerMostParsedUnit;
	this.resolvedUnits = parsedUnits;
}
 
Example #13
Source File: Main.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void performCompilation() {

	this.startTime = System.currentTimeMillis();

	FileSystem environment = getLibraryAccess();
	this.compilerOptions = new CompilerOptions(this.options);
	this.compilerOptions.performMethodsFullRecovery = false;
	this.compilerOptions.performStatementsRecovery = false;
	this.batchCompiler =
		new Compiler(
			environment,
			getHandlingPolicy(),
			this.compilerOptions,
			getBatchRequestor(),
			getProblemFactory(),
			this.out,
			this.progress);
	this.batchCompiler.remainingIterations = this.maxRepetition-this.currentRepetition/*remaining iterations including this one*/;
	// temporary code to allow the compiler to revert to a single thread
	String setting = System.getProperty("jdt.compiler.useSingleThread"); //$NON-NLS-1$
	this.batchCompiler.useSingleThread = setting != null && setting.equals("true"); //$NON-NLS-1$

	if (this.compilerOptions.complianceLevel >= ClassFileConstants.JDK1_6
			&& this.compilerOptions.processAnnotations) {
		if (checkVMVersion(ClassFileConstants.JDK1_6)) {
			initializeAnnotationProcessorManager();
			if (this.classNames != null) {
				this.batchCompiler.setBinaryTypes(processClassNames(this.batchCompiler.lookupEnvironment));
			}
		} else {
			// report a warning
			this.logger.logIncorrectVMVersionForAnnotationProcessing();
		}
	}

	// set the non-externally configurable options.
	this.compilerOptions.verbose = this.verbose;
	this.compilerOptions.produceReferenceInfo = this.produceRefInfo;
	try {
		this.logger.startLoggingSources();
		this.batchCompiler.compile(getCompilationUnits());
	} finally {
		this.logger.endLoggingSources();
	}

	if (this.extraProblems != null) {
		loggingExtraProblems();
		this.extraProblems = null;
	}
	if (this.compilerStats != null) {
		this.compilerStats[this.currentRepetition] = this.batchCompiler.stats;
	}
	this.logger.printStats();

	// cleanup
	environment.cleanup();
}
 
Example #14
Source File: ProcessingEnvImpl.java    From takari-lifecycle with Eclipse Public License 1.0 4 votes vote down vote up
public ProcessingEnvImpl(CompilerBuildContext context, StandardJavaFileManager fileManager, Map<String, String> processorOptions, Compiler compiler, CompilerJdt incrementalCompiler) {
  this._filer = new FilerImpl(context, fileManager, incrementalCompiler, this);
  this._messager = new MessagerImpl(context, this);
  this._processorOptions = processorOptions != null ? processorOptions : Collections.<String, String>emptyMap();
  this._compiler = compiler;

  this._elementUtils = new ElementsImpl(this) {
    @Override
    public TypeElement getTypeElement(CharSequence name) {
      observeType(name.toString());
      return super.getTypeElement(name);
    }

    @Override
    public PackageElement getPackageElement(CharSequence name) {
      observeType(name.toString());
      return super.getPackageElement(name);
    }
  };

  this._factory = new Factory(this) {
    private void observeType(Binding binding) {
      if (binding instanceof ImportBinding) {
        observeType(((ImportBinding) binding).compoundName);
      } else if (binding instanceof PackageBinding) {
        observeType(((PackageBinding) binding).compoundName);
      } else if (binding instanceof TypeBinding) {
        observeType((TypeBinding) binding);
      }

      // no need to explicitly handle variable references
      // - variable elements can only obtained through enclosing type,
      // which means the enclosing type is already observed
      // - to obtain type of the variable itself, processors need
      // to call Element.asType, which triggers subsequent calls here

      // ditto method references
    }

    private void observeType(TypeBinding binding) {
      binding = binding.leafComponentType().erasure();
      if (binding instanceof ReferenceBinding) {
        ReferenceBinding referenceBinding = (ReferenceBinding) binding;
        observeType(referenceBinding.compoundName);
        // TODO only track referenced member types (requires jdt.apt changes)
        for (ReferenceBinding memberType : referenceBinding.memberTypes()) {
          observeType(memberType.compoundName);
        }
      }
    }

    private void observeType(char[][] compoundName) {
      ProcessingEnvImpl.this.observeType(CharOperation.toString(compoundName));
    }

    @Override
    public Element newElement(Binding binding, ElementKind kindHint) {
      observeType(binding);
      return super.newElement(binding, kindHint);
    }

    @Override
    public TypeMirror newTypeMirror(Binding binding) {
      observeType(binding);
      return super.newTypeMirror(binding);
    }

    // TODO newTypeParameterElement
    // TODO newPackageElement
  };
}
 
Example #15
Source File: BindingKeyResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public BindingKeyResolver(String key, Compiler compiler, LookupEnvironment environment) {
	super(key);
	this.compiler = compiler;
	this.environment = environment;
	this.resolvedUnits = new HashtableOfObject();
}
 
Example #16
Source File: JavaModelManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Configure the plugin with respect to option settings defined in ".options" file
 */
public void configurePluginDebugOptions(){
	if(JavaCore.getPlugin().isDebugging()){
		String option = Platform.getDebugOption(BUFFER_MANAGER_DEBUG);
		if(option != null) BufferManager.VERBOSE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(BUILDER_DEBUG);
		if(option != null) JavaBuilder.DEBUG = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(COMPILER_DEBUG);
		if(option != null) Compiler.DEBUG = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(BUILDER_STATS_DEBUG);
		if(option != null) JavaBuilder.SHOW_STATS = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(COMPLETION_DEBUG);
		if(option != null) CompletionEngine.DEBUG = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(CP_RESOLVE_DEBUG);
		if(option != null) JavaModelManager.CP_RESOLVE_VERBOSE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(CP_RESOLVE_ADVANCED_DEBUG);
		if(option != null) JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(CP_RESOLVE_FAILURE_DEBUG);
		if(option != null) JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(DELTA_DEBUG);
		if(option != null) DeltaProcessor.DEBUG = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(DELTA_DEBUG_VERBOSE);
		if(option != null) DeltaProcessor.VERBOSE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(DOM_AST_DEBUG);
		if(option != null) SourceRangeVerifier.DEBUG = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(DOM_AST_DEBUG_THROW);
		if(option != null) {
			SourceRangeVerifier.DEBUG_THROW = option.equalsIgnoreCase(TRUE) ;
			SourceRangeVerifier.DEBUG |= SourceRangeVerifier.DEBUG_THROW;
		}
		
		option = Platform.getDebugOption(DOM_REWRITE_DEBUG);
		if(option != null) RewriteEventStore.DEBUG = option.equalsIgnoreCase(TRUE) ;
		
		option = Platform.getDebugOption(HIERARCHY_DEBUG);
		if(option != null) TypeHierarchy.DEBUG = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(INDEX_MANAGER_DEBUG);
		if(option != null) JobManager.VERBOSE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(INDEX_MANAGER_ADVANCED_DEBUG);
		if(option != null) IndexManager.DEBUG = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(JAVAMODEL_DEBUG);
		if(option != null) JavaModelManager.VERBOSE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(JAVAMODELCACHE_DEBUG);
		if(option != null) JavaModelCache.VERBOSE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(POST_ACTION_DEBUG);
		if(option != null) JavaModelOperation.POST_ACTION_VERBOSE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(RESOLUTION_DEBUG);
		if(option != null) NameLookup.VERBOSE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(SEARCH_DEBUG);
		if(option != null) BasicSearchEngine.VERBOSE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(SELECTION_DEBUG);
		if(option != null) SelectionEngine.DEBUG = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(ZIP_ACCESS_DEBUG);
		if(option != null) JavaModelManager.ZIP_ACCESS_VERBOSE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(SOURCE_MAPPER_DEBUG_VERBOSE);
		if(option != null) SourceMapper.VERBOSE = option.equalsIgnoreCase(TRUE) ;

		option = Platform.getDebugOption(FORMATTER_DEBUG);
		if(option != null) DefaultCodeFormatter.DEBUG = option.equalsIgnoreCase(TRUE) ;
	}

	// configure performance options
	if(PerformanceStats.ENABLED) {
		CompletionEngine.PERF = PerformanceStats.isEnabled(COMPLETION_PERF);
		SelectionEngine.PERF = PerformanceStats.isEnabled(SELECTION_PERF);
		DeltaProcessor.PERF = PerformanceStats.isEnabled(DELTA_LISTENER_PERF);
		JavaModelManager.PERF_VARIABLE_INITIALIZER = PerformanceStats.isEnabled(VARIABLE_INITIALIZER_PERF);
		JavaModelManager.PERF_CONTAINER_INITIALIZER = PerformanceStats.isEnabled(CONTAINER_INITIALIZER_PERF);
		ReconcileWorkingCopyOperation.PERF = PerformanceStats.isEnabled(RECONCILE_PERF);
	}
}
 
Example #17
Source File: BaseProcessingEnvImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public Compiler getCompiler() {
	return _compiler;
}
 
Example #18
Source File: BaseAnnotationProcessorManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void configureFromPlatform(Compiler compiler, Object compilationUnitLocator, Object javaProject) {
	// Implemented by IdeAnnotationProcessorManager.
	throw new UnsupportedOperationException();
}
 
Example #19
Source File: CompilerJdt.java    From takari-lifecycle with Eclipse Public License 1.0 votes vote down vote up
public abstract int compile(Classpath namingEnvironment, Compiler compiler) throws IOException;