public static boolean compilesWithFix ( Fix fix , VisitorState state ) { if ( fix . isEmpty ( ) ) { return true ; } JCCompilationUnit compilationUnit = ( JCCompilationUnit ) state . getPath ( ) . getCompilationUnit ( ) ; JavaFileObject modifiedFile = compilationUnit . getSourceFile ( ) ; BasicJavacTask javacTask = ( BasicJavacTask ) state . context . get ( JavacTask . class ) ; if ( javacTask == null ) { throw new IllegalArgumentException ( "No JavacTask in context." ) ; } Arguments arguments = Arguments . instance ( javacTask . getContext ( ) ) ; List < JavaFileObject > fileObjects = new ArrayList <> ( arguments . getFileObjects ( ) ) ; for ( int i = 0 ; i < fileObjects . size ( ) ; i ++ ) { final JavaFileObject oldFile = fileObjects . get ( i ) ; if ( modifiedFile . toUri ( ) . equals ( oldFile . toUri ( ) ) ) { DescriptionBasedDiff diff = DescriptionBasedDiff . create ( compilationUnit , ImportOrganizer . STATIC_FIRST_ORGANIZER ) ; diff . handleFix ( fix ) ; SourceFile fixSource ; try { fixSource = new SourceFile ( modifiedFile . getName ( ) , modifiedFile . getCharContent ( false /*ignoreEncodingErrors*/ ) ) ; } catch ( IOException e ) { return false ; } diff . applyDifferences ( fixSource ) ; fileObjects . set ( i , new SimpleJavaFileObject ( sourceURI ( modifiedFile . toUri ( ) ) , Kind . SOURCE ) { @ Override public CharSequence getCharContent ( boolean ignoreEncodingErrors ) throws IOException { return fixSource . getAsSequence ( ) ; } } ) ; break ; } } DiagnosticCollector < JavaFileObject > diagnosticListener = new DiagnosticCollector <> ( ) ; Context context = new Context ( ) ; Options options = Options . instance ( context ) ; Options originalOptions = Options . instance ( javacTask . getContext ( ) ) ; for ( String key : originalOptions . keySet ( ) ) { String value = originalOptions . get ( key ) ; if ( key . equals ( "-Xplugin:" ) && value . startsWith ( "ErrorProne" ) ) { // When using the -Xplugin Error Prone integration, disable Error Prone for speculative // recompiles to avoid infinite recurison. continue ; } options . put ( key , value ) ; } JavacTask newTask = JavacTool . create ( ) . getTask ( CharStreams . nullWriter ( ) , state . context . get ( JavaFileManager . class ) , diagnosticListener , ImmutableList . of ( ) , arguments . getClassNames ( ) , fileObjects , context ) ; try { newTask . analyze ( ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } return countErrors ( diagnosticListener ) == 0 ; }
Returns true if the current compilation would succeed with the given fix applied . Note that calling this method is very expensive as it requires rerunning the entire compile so it should be used with restraint .