summaryrefslogtreecommitdiff
path: root/eclipse/Slice2javaPlugin/src/com/zeroc/slice2javaplugin/builder/Slice2JavaBuilder.java
blob: 7a84a09aa981718ffb94debb8612532974db5413 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
// **********************************************************************
//
// Copyright (c) 2003-2010 ZeroC, Inc. All rights reserved.
//
// This plug-in is provided to you under the terms and conditions
// of the Eclipse Public License Version 1.0 ("EPL"). A copy of
// the EPL is available at http://www.eclipse.org/legal/epl-v10.html.
//
// **********************************************************************

package com.zeroc.slice2javaplugin.builder;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.zeroc.slice2javaplugin.Activator;
import com.zeroc.slice2javaplugin.internal.Configuration;
import com.zeroc.slice2javaplugin.internal.Dependencies;

public class Slice2JavaBuilder extends IncrementalProjectBuilder
{
    public static final String BUILDER_ID = "com.zeroc.Slice2JavaPlugin.Slice2JavaBuilder";
    
    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.core.internal.events.InternalBuilder#build(int,
     * java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
     */
    @SuppressWarnings("unchecked")
    protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
        throws CoreException
    {
        long start = System.currentTimeMillis();
        
        IResourceDelta delta = getDelta(getProject());
        BuildState state = new BuildState(getProject(), delta, monitor);
        state.dependencies.read();

        try
        {
            if(kind == FULL_BUILD)
            {
                fullBuild(state, monitor);
            }
            else
            {
                if(delta == null)
                {
                    fullBuild(state, monitor);
                }
                else
                {
                    incrementalBuild(state, monitor);
                }
            }
        }
        finally
        {
            long end = System.currentTimeMillis();
            if(state.out != null)
            {
                state.out.println("Build complete. Elapsed time: " + (end - start) / 1000 + "s.");
            }
            state.dependencies.write();
        }
        return null;
    }

    protected void clean(IProgressMonitor monitor)
        throws CoreException
    {
        BuildState state = new BuildState(getProject(), null, monitor);
        
        // Don't read the existing dependencies. That will have the
        // effect of trashing them.
        
        try
        {
            // Now, clean the generated sub-directory.
            Set<IFile> files = new HashSet<IFile>();
            getResources(files, state.generated.members());
            
            for(IFile file : files)
            {
                // Don't delete "." files (such as .gitignore).
                if(!file.getName().startsWith("."))
                {
                    file.delete(true, false, monitor);
                }
            }
        }
        finally
        {
            state.dependencies.write();
        }
    }
    
    static class StreamReaderThread extends Thread
    {
        public StreamReaderThread(InputStream in, StringBuffer out)
        {
            _in = new BufferedReader(new InputStreamReader(in), 1024);
            _out = out;
        }

        public void run()
        {
            try
            {
                char[] buf = new char[1024];
                while(true)
                {
                    int read = _in.read(buf);
                    if(read == -1)
                    {
                        break;
                    }
                    _out.append(buf, 0, read);
                }
            }
            catch(Exception e)
            {
            }
            finally
            {
                try
                {
                    _in.close();
                }
                catch(IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }

        private StringBuffer _out;
        private BufferedReader _in;
    }
    
    static class BuildState
    {
        BuildState(IProject project, IResourceDelta delta, IProgressMonitor monitor) throws CoreException
        {
            config = new Configuration(project);
            
            if(config.getConsole())
            {
                initializeConsole();
                out = _consoleout;
                err = _consoleerr;
            }
            
            generated = project.getFolder(config.getGeneratedDir());
            if(!generated.exists())
            {
                generated.create(false, true, monitor);
            }

            _sourceLocations = new HashSet<IFolder>();
            for(Iterator<String> p = config.getSliceSourceDirs().iterator(); p.hasNext();)
            {
                _sourceLocations.add(project.getFolder(p.next()));
            }
            
            project.accept(new IResourceVisitor()
            {
                public boolean visit(IResource resource)
                    throws CoreException
                {
                    if(resource instanceof IFile)
                    {
                        IFile file = (IFile) resource;
                        if(filter(file))
                        {
                            _resources.add((IFile) resource);
                        }
                    }
                    return true;
                }
            });

            if(delta != null)
            {
                delta.accept(new IResourceDeltaVisitor()
                {
                    public boolean visit(IResourceDelta delta)
                        throws CoreException
                    {
                        IResource resource = delta.getResource();
                        if(resource instanceof IFile)
                        {
                            IFile file = (IFile) resource;
                            if(filter(file))
                            {
                                switch (delta.getKind())
                                {
                                case IResourceDelta.ADDED:
                                case IResourceDelta.CHANGED:
                                    _deltaCandidates.add(file);
                                    break;
                                case IResourceDelta.REMOVED:
                                    _removed.add(file);
                                    break;
                                }
                            }
                        }
                        return true;
                    }
                });
            }

            dependencies = new Dependencies(project, _resources, err);
        }
        
        public Set<IFile> deltas() 
        {
            return _deltaCandidates;
        }
        
        public List<IFile> removed()
        {
            return _removed;
        }
        
        public Set<IFile> resources()
        {
            return _resources;
        }

        public boolean filter(IFile file)
        {
            String ext = file.getFileExtension();
            if(ext != null && ext.equals("ice"))
            {
                //
                // The parent may not be an IFolder (e.g., it could be a Project).
                //
                if(file.getParent() instanceof IFolder)
                {
                    IFolder folder = (IFolder)file.getParent();
                    if(_sourceLocations.contains(folder))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        
        synchronized static private void initializeConsole()
        {
            if(_consoleout == null)
            {
                MessageConsole console = new MessageConsole("slice2java", null);
                IConsole[] ics = new IConsole[1];
                ics[0] = console;
                IConsoleManager csmg = ConsolePlugin.getDefault().getConsoleManager();
                csmg.addConsoles(ics);
                csmg.showConsoleView(console);
    
                _consoleout = console.newMessageStream();
                _consoleerr = console.newMessageStream();
    
                final Display display = PlatformUI.getWorkbench().getDisplay();
                display.syncExec(new Runnable() {
                    public void run() {
                        _consoleerr.setColor(display.getSystemColor(SWT.COLOR_RED));
                    }
                });
            }
        }

        Configuration config;
        Dependencies dependencies;
        IFolder generated;
        private Set<IFolder> _sourceLocations;
        
        private Set<IFile> _resources = new HashSet<IFile>();
        private Set<IFile> _deltaCandidates = new HashSet<IFile>();
        private List<IFile> _removed = new ArrayList<IFile>();
        
        private MessageConsoleStream out = null;
        private MessageConsoleStream err = null;
 
        static private MessageConsoleStream _consoleout = null;
        static private MessageConsoleStream _consoleerr = null;
    }
    
    private int build(BuildState state, Set<IFile> files, boolean depend, StringBuffer out, StringBuffer err)
        throws CoreException
    {
        // Clear the output buffer.
        out.setLength(0);
        if(err != null)
        {
            err.setLength(0);
        }

        List<String> cmd = new LinkedList<String>();
        String translator = state.config.getTranslator();
        if(translator == null)
        {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Cannot locate slice2java translator: please fix Ice install location", null));
        }
        
        cmd.add(translator);
        if(depend)
        {
            cmd.add("--depend-xml");
        }
        else
        {
            cmd.add("--output-dir=" + state.generated.getProjectRelativePath().toString());
            cmd.add("--list-generated");
        }
        
        cmd.addAll(state.config.getCommandLine());
        
        for(Iterator<IFile> p = files.iterator(); p.hasNext();)
        {
            cmd.add(p.next().getLocation().toOSString());
        }

        if(state.out != null)
        {
            for(Iterator<String> p = cmd.iterator(); p.hasNext();)
            {
                state.out.print(p.next());
                state.out.print(" ");
            }
            state.out.println("");
        }
        ProcessBuilder builder = new ProcessBuilder(cmd);
        if(err == null)
        {
            builder.redirectErrorStream(true);
        }
        
        IPath rootLocation = getProject().getLocation();
        builder.directory(rootLocation.toFile());
        Map<String, String> env = builder.environment();
        state.config.setupSharedLibraryPath(env);

        try
        {
            Process proc = builder.start();

            StreamReaderThread outThread = new StreamReaderThread(proc.getInputStream(), out);
            outThread.start();
            StreamReaderThread errThread = null;
            if(err != null)
            {
                errThread = new StreamReaderThread(proc.getErrorStream(), err);
                errThread.start();
            }
            
            int status = proc.waitFor();

            outThread.join();
            if(errThread != null)
            {
                errThread.join();
            }
            
            if(status != 0 && state.err != null)
            {
                state.err.println("slice2java status: " + status);
            }

            return status;
        }
        catch(Exception e)
        {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.toString(), null));
        }
        // not reached
    }

    private void
    createMarker(BuildState state, IFile source, IPath filename, int line, String msg)
        throws CoreException
    {
        // Process the error.
        IPath dir = getProject().getLocation();
        
        IFile file = null;
        if(filename != null && dir.isPrefixOf(filename))
        {
            // Locate the file within the project.
            file = getProject().getFile(filename.removeFirstSegments(dir.segmentCount()));

            // If the file is not the current source file, and the file exists in the project
            // then it must already contain a marker, so don't place another.
            if(!file.equals(source) && state.filter(file))
            {
                return;
            }
        }
        
        // If the message isn't contained in the source file, then identify the
        // file:line in the message itself.
        if(file == null)
        {
            if(line != -1)
            {
                msg = filename + ":" + line + ": " + msg;
            }
            else
            {
                msg = filename + ": " + msg;
            }
        }
        
        IMarker marker = source.createMarker(IMarker.PROBLEM);
        marker.setAttribute(IMarker.MESSAGE, msg);
        if(msg.toLowerCase().indexOf("warning:") >= 0)
        {
            marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
        }
        else
        {
            marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
        }
        if(line != -1)
        {
            if(file != null && file.equals(source))
            {
                marker.setAttribute(IMarker.LINE_NUMBER, line);
            }
            else
            {
                marker.setAttribute(IMarker.LINE_NUMBER, 1);
            }
        }
    }
    
    private void createMarkers(BuildState state, IFile source, String output)
        throws CoreException
    {
        output = output.trim();
        if(output.length() == 0)
        {
            return;
        }
        
        String[] lines = output.split("\n");

        IPath filename = null;
        int line = -1;
        StringBuffer msg = new StringBuffer();
        
        boolean continuation = false;

        for(int i = 0; i < lines.length; ++i)
        {
            if(continuation)
            {
                if(lines[i].startsWith(" "))
                {
                    // Continuation of the previous message.
                    msg.append(lines[i]);
                    continue;
                }
                else
                {
                    // Process the message.
                    createMarker(state, source, filename, line, msg.toString());
                }
            }
            
            // We're on a new message.
            msg.setLength(0);
            continuation = false;
            
            // Ignore.
            if(lines[i].contains("errors in preprocessor") || lines[i].contains("error in preprocessor"))
            {
                continue;
            }
            
            //
            // Parse a line of the form:
            //
            // file:[line:] message
            //
            int start = 0;
            int end;
            // Handle drive letters.
            if(lines[i].length() > 2 && lines[i].charAt(1) == ':')
            {
                end = lines[i].indexOf(':', 2);
            }
            else
            {
                end = lines[i].indexOf(':');
            }
            if(end != -1)
            {
                filename = new Path(lines[i].substring(start, end));
                start = end + 1;
                end = lines[i].indexOf(':', start);
                if(end != -1)
                {
                    try
                    {
                        line = Integer.parseInt(lines[i].substring(start, end));
                        start = end + 1;
                    }
                    catch(NumberFormatException e)
                    {
                        // The message may not have a line number.
                        line = -1;
                    }
                    msg.append(lines[i].substring(start, lines[i].length()));

                    continuation = true;
                    continue;
                }
            }
            // Unknown format.
            createMarker(state, source, null, -1, lines[i]);
        }

        if(continuation)
        {
            createMarker(state, source, filename, line, msg.toString());
        }
    }
    
    private void getResources(Set<IFile> files, IResource[] members)
        throws CoreException
    {
        for(int i = 0; i < members.length; ++i)
        {
            if(members[i] instanceof IFile)
            {
                files.add((IFile) members[i]);
            }
            else if(members[i] instanceof IFolder)
            {
                getResources(files, ((IFolder) members[i]).members());
            }
        }
    }

    private void fullBuild(BuildState state, final IProgressMonitor monitor)
        throws CoreException
    {
        clean(monitor);
        Set<IFile> candidates = state.resources();
        if(candidates.isEmpty())
        {
            return;
        }

        if(state.out != null)
        {
            java.util.Date date = new java.util.Date();
            state.out.println("Start full build at " + new SimpleDateFormat("HH:mm:ss").format(date));

            state.out.println("Candidate list:");
            // This is a complete list of Slice files.
            for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
            {
                state.out.println("    " + p.next().getProjectRelativePath().toString());
            }
            state.out.println("Regenerating java source files.");
        }
        
        StringBuffer out = new StringBuffer();

        Set<IFile> depends = new HashSet<IFile>();
        
        // Delete each marker.
        for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
        {
            IFile file = p.next();
            file.deleteMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
        }
            
        // Do the build.
        build(state, candidates, false, out, null);

        // Refresh the generated subdirectory prior to processing the
        // generated files list.
        state.generated.refreshLocal(IResource.DEPTH_INFINITE, monitor);

        // Parse the output.
        Slice2JavaGeneratedParser parser = getGeneratedFiles(state, candidates, out);
        for(Map.Entry<IFile, Slice2JavaGeneratedParser.Entry> entry : parser.output.entrySet())
        {
            IFile source = entry.getKey();

            Slice2JavaGeneratedParser.Entry outputEntry = entry.getValue();
            Set<IFile> newGeneratedJavaFiles = outputEntry.files;

            for(IFile f : newGeneratedJavaFiles)
            {
                // Mark the resource as derived.
                f.setDerived(true);
            }

            if(!outputEntry.error)
            {
                depends.add(source);
                if(state.out != null)
                {
                    if(newGeneratedJavaFiles.isEmpty())
                    {
                        state.out.println(source.getProjectRelativePath().toString() + ": No java files emitted.");
                    }
                    else
                    {
                        state.out.println(source.getProjectRelativePath().toString() + ": Emitted:");
                        for(Iterator<IFile> q = newGeneratedJavaFiles.iterator(); q.hasNext();)
                        {
                            state.out.println("    " + q.next().getProjectRelativePath().toString());
                        }
                    }
                }
            }
            else
            {
                state.dependencies.errorSliceFiles.add(source);
                if(state.out != null)
                {
                    state.out.println(source.getProjectRelativePath().toString() + ": Error.");
                }
            }

            // Update the set of slice -> java dependencies.
            state.dependencies.sliceJavaDependencies.put(source, newGeneratedJavaFiles);
            
            // Create markers for each warning/error.
            createMarkers(state, source, outputEntry.output);
        }
        
        // Update the slice->slice dependencies.
        // Only update the dependencies for those files with no build problems.
        if(!depends.isEmpty())
        {
            if(state.out != null)
            {
                state.out.println("Updating dependencies.");
            }

            StringBuffer err = new StringBuffer();
            if(build(state, depends, true, out, err) == 0)
            {
                // Parse the new dependency set.
                state.dependencies.updateDependencies(out.toString());
            }
            else if(state.err != null)
            {
                state.err.println("Dependencies not updated due to error.");
                state.err.println(err.toString());    
            }
        }
    }

    private void incrementalBuild(BuildState state, IProgressMonitor monitor)
        throws CoreException
    {
        Set<IFile> candidates = state.deltas();
        List<IFile> removed = state.removed();
        
        if(state.out != null)
        {
            java.util.Date date = new java.util.Date();
            state.out.println("Start incremental build at " + new SimpleDateFormat("HH:mm:ss").format(date));
            
            state.out.println("Candidate list:");
            // This is a complete list of slice files.
            for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
            {
                state.out.println("   + " + p.next().getProjectRelativePath().toString());
            }
            for(Iterator<IFile> p = removed.iterator(); p.hasNext();)
            {
                state.out.println("   - " + p.next().getProjectRelativePath().toString());
            }
        }
        
        // The orphan candidate set.
        Set<IFile> orphanCandidateSet = new HashSet<IFile>();
        
        // Go through the removed list, removing the dependencies.
        for(Iterator<IFile> p = removed.iterator(); p.hasNext();)
        {
            IFile f = p.next();
            
            // Remove the file from the error list, if necessary.
            if(state.dependencies.errorSliceFiles.contains(f))
            {
                state.dependencies.errorSliceFiles.remove(f);
            }
            
            Set<IFile> dependents = state.dependencies.sliceSliceDependencies.remove(f);
            if(dependents != null)
            {
                Iterator<IFile> dependentsIterator = dependents.iterator();
                while(dependentsIterator.hasNext())
                {
                    IFile dependent = dependentsIterator.next();
                    Set<IFile> files = state.dependencies.reverseSliceSliceDependencies.get(dependent);
                    if(files != null)
                    {
                        files.remove(f);
                    }
                }
            }
            
            Set<IFile> oldJavaFiles = state.dependencies.sliceJavaDependencies.remove(f);
            if(state.out != null)
            {
                if(oldJavaFiles == null || oldJavaFiles.isEmpty())
                {
                    state.out.println(f.getProjectRelativePath().toString() + ": No orphans.");
                }
                else
                {
                    state.out.println(f.getProjectRelativePath().toString() + ": Orphans:");
                    for(Iterator<IFile> q = oldJavaFiles.iterator(); q.hasNext();)
                    {
                        state.out.println("    " + q.next().getProjectRelativePath().toString());
                    }
                }
            }

            if(oldJavaFiles != null)
            {
                orphanCandidateSet.addAll(oldJavaFiles);
            }
        }

        // Add the removed files to the candidates set
        // prior to determining additional candidates.
        candidates.addAll(removed);
        
        // Add to the candidate set any slice files that are in error. Clear the
        // error list.
        candidates.addAll(state.dependencies.errorSliceFiles);
        state.dependencies.errorSliceFiles.clear();

        for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
        {
            IFile f = p.next();
            
            Set<IFile> files = state.dependencies.reverseSliceSliceDependencies.get(f);
            if(files != null)
            {
                for(Iterator<IFile> q = files.iterator(); q.hasNext();)
                {
                    IFile potentialCandidate = q.next();
                    if(potentialCandidate.exists())
                    {
                        candidates.add(potentialCandidate);
                    }
                }
            }

            // If this is a file in the contained list, then remove the
            // dependency entry.
            if(removed.contains(f))
            {
                state.dependencies.reverseSliceSliceDependencies.remove(f);
            }
        }

        // Remove all the removed files from the candidates list.
        candidates.removeAll(removed);

        if(state.out != null)
        {
            if(candidates.isEmpty())
            {
                state.out.println("No remaining candidates.");
            }
            else
            {
                state.out.println("Expanded candidate list:");
                // This is a complete list of slice files.
                for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
                {
                    state.out.println("    " + p.next().getProjectRelativePath().toString());
                }
            }
        }

        StringBuffer out = new StringBuffer();

        // The set of files that we'll generate dependencies for.
        Set<IFile> depends = new HashSet<IFile>();
        
        if(!candidates.isEmpty())
        {
            if(state.out != null)
            {
                state.out.println("Regenerating java source files.");
            }

            // The complete set of generated java files by this build.
            Set<IFile> generatedJavaFiles = new HashSet<IFile>();

            // Remove all markers for the candidate list.
            for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
            {
                IFile file = p.next();
                file.deleteMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
            }
            
            // Do the build.
            build(state, candidates, false, out, null);
    
            // Refresh the generated directory prior to processing the generated
            // files list.
            state.generated.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    
            // Parse the emitted XML file that describes what was produced by
            // the build.
            Slice2JavaGeneratedParser parser = getGeneratedFiles(state, candidates, out);
            for(Map.Entry<IFile, Slice2JavaGeneratedParser.Entry> entry : parser.output.entrySet())
            {
                IFile source = entry.getKey();
    
                Slice2JavaGeneratedParser.Entry outputEntry = entry.getValue();
                
                Set<IFile> newGeneratedJavaFiles = outputEntry.files;
                for(IFile f : newGeneratedJavaFiles)
                {
                    // Mark the resource as derived.
                    f.setDerived(true);
                }

                // If the build of the file didn't result in an error, add to
                // the dependencies list. Otherwise, add to the error list.
                if(!outputEntry.error)
                {
                    depends.add(source);
                }
                else
                {
                    if(state.out != null)
                    {
                        state.out.println(source.getProjectRelativePath().toString() + ": Error.");
                    }
                    state.dependencies.errorSliceFiles.add(source);
                }
    
                // Compute the set difference between the old set and new set
                // of generated files. The difference should be added to the
                // orphan candidate set.
                Set<IFile> oldJavaFiles = state.dependencies.sliceJavaDependencies.get(source);
                if(oldJavaFiles != null)
                {
                    // Compute the set difference.
                    oldJavaFiles.removeAll(newGeneratedJavaFiles);
                    if(state.out != null)
                    {
                        if(oldJavaFiles.isEmpty())
                        {
                            state.out.println(source.getProjectRelativePath().toString() + ": No orphans.");
                        }
                        else
                        {
                            state.out.println(source.getProjectRelativePath().toString() + ": Orphans:");
                            for(Iterator<IFile> q = oldJavaFiles.iterator(); q.hasNext();)
                            {
                                state.out.println("    " + q.next().getProjectRelativePath().toString());
                            }
                        }
                    }
                    orphanCandidateSet.addAll(oldJavaFiles);
                }
    
                // Update the set of slice -> java dependencies.
                state.dependencies.sliceJavaDependencies.put(source, newGeneratedJavaFiles);
    
                // If the build resulted in an error, there will be no java source files.
                if(state.out != null && !outputEntry.error)
                {
                    if(newGeneratedJavaFiles.isEmpty())
                    {
                        state.out.println(source.getProjectRelativePath().toString() + ": No java files emitted.");
                    }
                    else
                    {
                        state.out.println(source.getProjectRelativePath().toString() + ": Emitted:");
                        for(Iterator<IFile> q = newGeneratedJavaFiles.iterator(); q.hasNext();)
                        {
                            state.out.println("    " + q.next().getProjectRelativePath().toString());
                        }
                    }
                }
    
                generatedJavaFiles.addAll(newGeneratedJavaFiles);
                
                // Create markers for each warning/error.
                createMarkers(state, source, outputEntry.output);
            }
            
            // Do a set difference between the orphan candidate set
            // and the complete set of generated java source files.
            // Any remaining are complete orphans and should
            // be removed.
            orphanCandidateSet.removeAll(generatedJavaFiles);
        }

        if(state.out != null)
        {
            if(orphanCandidateSet.isEmpty())
            {
                state.out.println("No orphans from this build.");
            }
            else
            {
                state.out.println("Orphans from this build:");
                for(Iterator<IFile> p = orphanCandidateSet.iterator(); p.hasNext();)
                {
                    state.out.println("    " + p.next().getProjectRelativePath().toString());
                }
            }
        }

        //
        // Remove orphans.
        //
        for(Iterator<IFile> p = orphanCandidateSet.iterator(); p.hasNext();)
        {
            p.next().delete(true, false, monitor);
        }

        // The dependencies of any files without build errors should be updated.
        if(!depends.isEmpty())
        {
            if(state.out != null)
            {
                state.out.println("Updating dependencies.");
            }

            StringBuffer err = new StringBuffer();

            // We've already added markers for any errors... Only update the
            // dependencies if no problems resulted in the build.
            if(build(state, depends, true, out, err) == 0)
            {
                // Parse the new dependency set.
                state.dependencies.updateDependencies(out.toString());
            }
            else if(state.err != null)
            {
                state.err.println("Dependencies not updated due to error.");
                state.err.println(err.toString());    
            }
        }
    }

    private static class Slice2JavaGeneratedParser
    {
        static class Entry
        {
            boolean error; // Did the build result in an error.
            String output; // Any warnings/errors from the build.
            Set<IFile> files; // The set of java source files associated with the source file.
        }
        Map<IFile, Entry> output = new HashMap<IFile, Entry>(); // Map of source files to build entry.

        private IFolder _generated;
        // Map of absolute path to project location.
        private Map<IPath, IFile> _sources = new HashMap<IPath, IFile>();
        
        Slice2JavaGeneratedParser(IFolder generated, Set<IFile> candidates)
        {
            _generated = generated;
            for(IFile f : candidates)
            {
                _sources.put(f.getLocation(), f);
            }
        }

        private Node findNode(Node n, String qName)
            throws SAXException
        {
            NodeList children = n.getChildNodes();
            for(int i = 0; i < children.getLength(); ++i)
            {
                Node child = children.item(i);
                if(child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals(qName))
                {
                    return child;
                }
            }
            throw new SAXException("no such node: " + qName);
        }
        
        private IFile convert(String fname)
        {
            IPath p = new Path(fname); // fname contains "generated/...".
            return _generated.getFile(p.removeFirstSegments(1));
        }            

        public Set<IFile> visitSource(Node source) throws SAXException
        {
            Set<IFile> files = new HashSet<IFile>();
            NodeList sourceNodes = source.getChildNodes();
            for(int j = 0; j < sourceNodes.getLength(); ++j)
            {
                if(sourceNodes.item(j).getNodeType() == Node.ELEMENT_NODE && sourceNodes.item(j).getNodeName().equals("file"))
                {
                    Element file = (Element)sourceNodes.item(j);
                    String name = file.getAttribute("name");
                    if(name.length() == 0)
                    {
                        throw new SAXException("empty name attribute");
                    }
                    files.add(convert(name));
                }
            }
            return files;
        }
        
        private String getText(Node n) throws SAXException
        {
            NodeList children = n.getChildNodes();
            if(children.getLength() == 1 && children.item(0).getNodeType() == Node.TEXT_NODE)
            {
                return children.item(0).getNodeValue();
            }
            return "";
        }
        
        public void visit(Node doc) throws SAXException
        {
            Node n = findNode(doc, "generated");
            NodeList fileNodes = n.getChildNodes();
            for(int j = 0; j < fileNodes.getLength(); ++j)
            {
                if(fileNodes.item(j).getNodeType() == Node.ELEMENT_NODE && fileNodes.item(j).getNodeName().equals("source"))
                {
                    Element sourceElement = (Element)fileNodes.item(j);
                    String name = sourceElement.getAttribute("name");
                    if(name.length() == 0)
                    {
                        throw new SAXException("empty name attribute");
                    }
                    
                    // The source file 
                    IFile source = _sources.get(new Path(name));
                    if(source == null)
                    {
                        throw new SAXException("unknown source file: " + name);
                    }

                    Entry e = new Entry();
                    e.error = true;
                    e.output = getText(findNode(sourceElement, "output"));

                    String error = sourceElement.getAttribute("error");
                    if(error.equals("true"))
                    {
                        e.error = true;
                        e.files = new HashSet<IFile>();
                    }
                    else
                    {
                        e.error = false;
                        e.files = visitSource(sourceElement);
                    }
                    output.put(source, e);
                }
            }
        }
    }
    
    private Slice2JavaGeneratedParser getGeneratedFiles(BuildState state, Set<IFile> candidates, StringBuffer out)
        throws CoreException
    {
        Slice2JavaGeneratedParser parser = new Slice2JavaGeneratedParser(state.generated, candidates);
        try
        {
            InputStream in = new ByteArrayInputStream(out.toString().getBytes());
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new BufferedInputStream(in));
            parser.visit(doc);
        }
        catch(SAXException e)
        {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    "internal error reading the generated output list", e));
        }
        catch(ParserConfigurationException e)
        {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    "internal error reading the generated output list", e));
        }
        catch(IOException e)
        {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    "internal error reading the generated output list", e));
        }
        return parser;
    }
}