summaryrefslogtreecommitdiff
path: root/Tools/Java/Source/Cpptasks/net/sf/antcontrib/cpptasks/DependencyTable.java
blob: 3cbee7a625db29830620f3aa687c97adb2a0fa59 (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
/*
 * 
 * Copyright 2002-2004 The Ant-Contrib project
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package net.sf.antcontrib.cpptasks;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import net.sf.antcontrib.cpptasks.compiler.CompilerConfiguration;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
 * @author Curt Arnold
 */
public final class DependencyTable {
    /**
     * This class handles populates the TargetHistory hashtable in response to
     * SAX parse events
     */
    private class DependencyTableHandler extends DefaultHandler {
        private File baseDir;
        private final DependencyTable dependencyTable;
        private String includePath;
        private Vector includes;
        private String source;
        private long sourceLastModified;
        private Vector sysIncludes;
        /**
         * Constructor
         * 
         * @param history
         *            hashtable of TargetHistory keyed by output name
         * @param outputFiles
         *            existing files in output directory
         */
        private DependencyTableHandler(DependencyTable dependencyTable,
                File baseDir) {
            this.dependencyTable = dependencyTable;
            this.baseDir = baseDir;
            includes = new Vector();
            sysIncludes = new Vector();
            source = null;
        }
        public void endElement(String namespaceURI, String localName,
                String qName) throws SAXException {
            //
            //   if </source> then
            //       create Dependency object and add to hashtable
            //           if corresponding source file exists and
            //           has the same timestamp
            //
            if (qName.equals("source")) {
                if (source != null && includePath != null) {
                    File existingFile = new File(baseDir, source);
                    //
                    //   if the file exists and the time stamp is right
                    //       preserve the dependency info
                    if (existingFile.exists()) {
                        //
                        //   would have expected exact matches
                        //       but was seeing some unexpected difference by
                        //       a few tens of milliseconds, as long
                        //       as the times are within a second
                        long existingLastModified = existingFile.lastModified();
                        long diff = existingLastModified - sourceLastModified;
                        if (diff >= -500 && diff <= 500) {
                            DependencyInfo dependInfo = new DependencyInfo(
                                    includePath, source, sourceLastModified,
                                    includes, sysIncludes);
                            dependencyTable.putDependencyInfo(source,
                                    dependInfo);
                        }
                    }
                    source = null;
                    includes.setSize(0);
                }
            } else {
                //
                //    this causes any <source> elements outside the
                //       scope of an <includePath> to be discarded
                //
                if (qName.equals("includePath")) {
                    includePath = null;
                }
            }
        }
        /**
         * startElement handler
         */
        public void startElement(String namespaceURI, String localName,
                String qName, Attributes atts) throws SAXException {
            //
            //   if includes, then add relative file name to vector
            //
            if (qName.equals("include")) {
                includes.addElement(atts.getValue("file"));
            } else {
                if (qName.equals("sysinclude")) {
                    sysIncludes.addElement(atts.getValue("file"));
                } else {
                    //
                    //    if source then
                    //        capture source file name,
                    //        modification time and reset includes vector
                    //
                    if (qName.equals("source")) {
                        source = atts.getValue("file");
                        sourceLastModified = Long.parseLong(atts
                                .getValue("lastModified"), 16);
                        includes.setSize(0);
                        sysIncludes.setSize(0);
                    } else {
                        if (qName.equals("includePath")) {
                            includePath = atts.getValue("signature");
                        }
                    }
                }
            }
        }
    }
    public abstract class DependencyVisitor {
        /**
         * Previews all the children of this source file.
         * 
         * May be called multiple times as DependencyInfo's for children are
         * filled in.
         * 
         * @return true to continue towards recursion into included files
         */
        public abstract boolean preview(DependencyInfo parent,
                DependencyInfo[] children);
        /**
         * Called if the dependency depth exhausted the stack.
         */
        public abstract void stackExhausted();
        /**
         * Visits the dependency info.
         * 
         * @returns true to continue towards recursion into included files
         */
        public abstract boolean visit(DependencyInfo dependInfo);
    }
    public class TimestampChecker extends DependencyVisitor {
        private boolean noNeedToRebuild;
        private long outputLastModified;
        private boolean rebuildOnStackExhaustion;
        public TimestampChecker(final long outputLastModified,
                boolean rebuildOnStackExhaustion) {
            this.outputLastModified = outputLastModified;
            noNeedToRebuild = true;
            this.rebuildOnStackExhaustion = rebuildOnStackExhaustion;
        }
        public boolean getMustRebuild() {
            return !noNeedToRebuild;
        }
        public boolean preview(DependencyInfo parent, DependencyInfo[] children) {
            int withCompositeTimes = 0;
            long parentCompositeLastModified = parent.getSourceLastModified();
            for (int i = 0; i < children.length; i++) {
                if (children[i] != null) {
                    //
                    //  expedient way to determine if a child forces us to
                    // rebuild
                    //
                    visit(children[i]);
                    long childCompositeLastModified = children[i]
                            .getCompositeLastModified();
                    if (childCompositeLastModified != Long.MIN_VALUE) {
                        withCompositeTimes++;
                        if (childCompositeLastModified > parentCompositeLastModified) {
                            parentCompositeLastModified = childCompositeLastModified;
                        }
                    }
                }
            }
            if (withCompositeTimes == children.length) {
                parent.setCompositeLastModified(parentCompositeLastModified);
            }
            //
            //  may have been changed by an earlier call to visit()
            //
            return noNeedToRebuild;
        }
        public void stackExhausted() {
            if (rebuildOnStackExhaustion) {
                noNeedToRebuild = false;
            }
        }
        public boolean visit(DependencyInfo dependInfo) {
            if (noNeedToRebuild) {
                if (dependInfo.getSourceLastModified() > outputLastModified
                        || dependInfo.getCompositeLastModified() > outputLastModified) {
                    noNeedToRebuild = false;
                }
            }
            //
            //   only need to process the children if
            //      it has not yet been determined whether
            //      we need to rebuild and the composite modified time
            //         has not been determined for this file
            return noNeedToRebuild
                    && dependInfo.getCompositeLastModified() == Long.MIN_VALUE;
        }
    }
    private/* final */File baseDir;
    private String baseDirPath;
    /**
     * a hashtable of DependencyInfo[] keyed by output file name
     */
    private final Hashtable dependencies = new Hashtable();
    /** The file the cache was loaded from. */
    private/* final */File dependenciesFile;
    /** Flag indicating whether the cache should be written back to file. */
    private boolean dirty;
    /**
     * Creates a target history table from dependencies.xml in the prject
     * directory, if it exists. Otherwise, initializes the dependencies empty.
     * 
     * @param task
     *            task used for logging history load errors
     * @param baseDir
     *            output directory for task
     */
    public DependencyTable(File baseDir) {
        if (baseDir == null) {
            throw new NullPointerException("baseDir");
        }
        this.baseDir = baseDir;
        try {
            baseDirPath = baseDir.getCanonicalPath();
        } catch (IOException ex) {
            baseDirPath = baseDir.toString();
        }
        dirty = false;
        //
        //   load any existing dependencies from file
        dependenciesFile = new File(baseDir, "dependencies.xml");
    }
    public void commit(CCTask task) {
        //
        //   if not dirty, no need to update file
        //
        if (dirty) {
            //
            //   walk through dependencies to get vector of include paths
            // identifiers
            //
            Vector includePaths = getIncludePaths();
            //
            //
            //   write dependency file
            //
            try {
                FileOutputStream outStream = new FileOutputStream(
                        dependenciesFile);
                OutputStreamWriter streamWriter;
                //
                //    Early VM's may not have UTF-8 support
                //       fallback to default code page which
                //           "should" be okay unless there are
                //            non ASCII file names
                String encodingName = "UTF-8";
                try {
                    streamWriter = new OutputStreamWriter(outStream, "UTF-8");
                } catch (UnsupportedEncodingException ex) {
                    streamWriter = new OutputStreamWriter(outStream);
                    encodingName = streamWriter.getEncoding();
                }
                BufferedWriter writer = new BufferedWriter(streamWriter);
                writer.write("<?xml version='1.0' encoding='");
                writer.write(encodingName);
                writer.write("'?>\n");
                writer.write("<dependencies>\n");
                StringBuffer buf = new StringBuffer();
                Enumeration includePathEnum = includePaths.elements();
                while (includePathEnum.hasMoreElements()) {
                    writeIncludePathDependencies((String) includePathEnum
                            .nextElement(), writer, buf);
                }
                writer.write("</dependencies>\n");
                writer.close();
                dirty = false;
            } catch (IOException ex) {
                task.log("Error writing " + dependenciesFile.toString() + ":"
                        + ex.toString());
            }
        }
    }
    /**
     * Returns an enumerator of DependencyInfo's
     */
    public Enumeration elements() {
        return dependencies.elements();
    }
    /**
     * This method returns a DependencyInfo for the specific source file and
     * include path identifier
     *  
     */
    public DependencyInfo getDependencyInfo(String sourceRelativeName,
            String includePathIdentifier) {
        DependencyInfo dependInfo = null;
        DependencyInfo[] dependInfos = (DependencyInfo[]) dependencies
                .get(sourceRelativeName);
        if (dependInfos != null) {
            for (int i = 0; i < dependInfos.length; i++) {
                dependInfo = dependInfos[i];
                if (dependInfo.getIncludePathIdentifier().equals(
                        includePathIdentifier)) {
                    return dependInfo;
                }
            }
        }
        return null;
    }
    private Vector getIncludePaths() {
        Vector includePaths = new Vector();
        DependencyInfo[] dependInfos;
        Enumeration dependenciesEnum = dependencies.elements();
        while (dependenciesEnum.hasMoreElements()) {
            dependInfos = (DependencyInfo[]) dependenciesEnum.nextElement();
            for (int i = 0; i < dependInfos.length; i++) {
                DependencyInfo dependInfo = dependInfos[i];
                boolean matchesExisting = false;
                final String dependIncludePath = dependInfo
                        .getIncludePathIdentifier();
                Enumeration includePathEnum = includePaths.elements();
                while (includePathEnum.hasMoreElements()) {
                    if (dependIncludePath.equals(includePathEnum.nextElement())) {
                        matchesExisting = true;
                        break;
                    }
                }
                if (!matchesExisting) {
                    includePaths.addElement(dependIncludePath);
                }
            }
        }
        return includePaths;
    }
    public void load() throws IOException, ParserConfigurationException,
            SAXException {
        dependencies.clear();
        if (dependenciesFile.exists()) {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setValidating(false);
            SAXParser parser = factory.newSAXParser();
            parser.parse(dependenciesFile, new DependencyTableHandler(this,
                    baseDir));
            dirty = false;
        }
    }
    /**
     * Determines if the specified target needs to be rebuilt.
     * 
     * This task may result in substantial IO as files are parsed to determine
     * their dependencies
     */
    public boolean needsRebuild(CCTask task, TargetInfo target,
            int dependencyDepth) {
        //    look at any files where the compositeLastModified
        //    is not known, but the includes are known
        //
        boolean mustRebuild = false;
        CompilerConfiguration compiler = (CompilerConfiguration) target
                .getConfiguration();
        String includePathIdentifier = compiler.getIncludePathIdentifier();
        File[] sources = target.getSources();
        DependencyInfo[] dependInfos = new DependencyInfo[sources.length];
        long outputLastModified = target.getOutput().lastModified();
        //
        //   try to solve problem using existing dependency info
        //      (not parsing any new files)
        //
        DependencyInfo[] stack = new DependencyInfo[50];
        boolean rebuildOnStackExhaustion = true;
        if (dependencyDepth >= 0) {
            if (dependencyDepth < 50) {
                stack = new DependencyInfo[dependencyDepth];
            }
            rebuildOnStackExhaustion = false;
        }
        TimestampChecker checker = new TimestampChecker(outputLastModified,
                rebuildOnStackExhaustion);
        for (int i = 0; i < sources.length && !mustRebuild; i++) {
            File source = sources[i];
            String relative = CUtil.getRelativePath(baseDirPath, source);
            DependencyInfo dependInfo = getDependencyInfo(relative,
                    includePathIdentifier);
            if (dependInfo == null) {
                task.log("Parsing " + relative, Project.MSG_VERBOSE);
                dependInfo = parseIncludes(task, compiler, source);
            }
            walkDependencies(task, dependInfo, compiler, stack, checker);
            mustRebuild = checker.getMustRebuild();
        }
        return mustRebuild;
    }
    public DependencyInfo parseIncludes(CCTask task,
            CompilerConfiguration compiler, File source) {
        DependencyInfo dependInfo = compiler.parseIncludes(task, baseDir,
                source);
        String relativeSource = CUtil.getRelativePath(baseDirPath, source);
        putDependencyInfo(relativeSource, dependInfo);
        return dependInfo;
    }
    private void putDependencyInfo(String key, DependencyInfo dependInfo) {
        //
        //   optimistic, add new value
        //
        DependencyInfo[] old = (DependencyInfo[]) dependencies.put(key,
                new DependencyInfo[]{dependInfo});
        dirty = true;
        //
        //   something was already there
        //
        if (old != null) {
            //
            //   see if the include path matches a previous entry
            //       if so replace it
            String includePathIdentifier = dependInfo
                    .getIncludePathIdentifier();
            for (int i = 0; i < old.length; i++) {
                DependencyInfo oldDepend = old[i];
                if (oldDepend.getIncludePathIdentifier().equals(
                        includePathIdentifier)) {
                    old[i] = dependInfo;
                    dependencies.put(key, old);
                    return;
                }
            }
            //
            //   no match prepend the new entry to the array
            //      of dependencies for the file
            DependencyInfo[] combined = new DependencyInfo[old.length + 1];
            combined[0] = dependInfo;
            for (int i = 0; i < old.length; i++) {
                combined[i + 1] = old[i];
            }
            dependencies.put(key, combined);
        }
        return;
    }
    public void walkDependencies(CCTask task, DependencyInfo dependInfo,
            CompilerConfiguration compiler, DependencyInfo[] stack,
            DependencyVisitor visitor) throws BuildException {
        //
        //   visit this node
        //       if visit returns true then
        //          visit the referenced include and sysInclude dependencies
        //
        if (visitor.visit(dependInfo)) {
            //
            //   find first null entry on stack
            //
            int stackPosition = -1;
            for (int i = 0; i < stack.length; i++) {
                if (stack[i] == null) {
                    stackPosition = i;
                    stack[i] = dependInfo;
                    break;
                } else {
                    //
                    //   if we have appeared early in the calling history
                    //      then we didn't exceed the criteria
                    if (stack[i] == dependInfo) {
                        return;
                    }
                }
            }
            if (stackPosition == -1) {
                visitor.stackExhausted();
                return;
            }
            //
            //   locate dependency infos
            //
            String[] includes = dependInfo.getIncludes();
            String includePathIdentifier = compiler.getIncludePathIdentifier();
            DependencyInfo[] includeInfos = new DependencyInfo[includes.length];
            for (int i = 0; i < includes.length; i++) {
                DependencyInfo includeInfo = getDependencyInfo(includes[i],
                        includePathIdentifier);
                includeInfos[i] = includeInfo;
            }
            //
            //   preview with only the already available dependency infos
            //
            if (visitor.preview(dependInfo, includeInfos)) {
                //
                //   now need to fill in the missing DependencyInfos
                //
                int missingCount = 0;
                for (int i = 0; i < includes.length; i++) {
                    if (includeInfos[i] == null) {
                        missingCount++;
                        task.log("Parsing " + includes[i], Project.MSG_VERBOSE);
                        // If the include is part of a UNC don't go building a
                        // relative file name.
                        File src = includes[i].startsWith("\\\\") ? new File(
                                includes[i]) : new File(baseDir, includes[i]);
                        DependencyInfo includeInfo = parseIncludes(task,
                                compiler, src);
                        includeInfos[i] = includeInfo;
                    }
                }
                //
                //   if it passes a review the second time
                //      then recurse into all the children
                if (missingCount == 0
                        || visitor.preview(dependInfo, includeInfos)) {
                    //
                    //   recurse into
                    //
                    for (int i = 0; i < includeInfos.length; i++) {
                        DependencyInfo includeInfo = includeInfos[i];
                        walkDependencies(task, includeInfo, compiler, stack,
                                visitor);
                    }
                }
            }
            stack[stackPosition] = null;
        }
    }
    private void writeDependencyInfo(BufferedWriter writer, StringBuffer buf,
            DependencyInfo dependInfo) throws IOException {
        String[] includes = dependInfo.getIncludes();
        String[] sysIncludes = dependInfo.getSysIncludes();
        //
        //   if the includes have not been evaluted then
        //       it is not worth our time saving it
        //       and trying to distiguish between files with
        //       no dependencies and those with undetermined dependencies
        buf.setLength(0);
        buf.append("      <source file=\"");
        buf.append(CUtil.xmlAttribEncode(dependInfo.getSource()));
        buf.append("\" lastModified=\"");
        buf.append(Long.toHexString(dependInfo.getSourceLastModified()));
        buf.append("\">\n");
        writer.write(buf.toString());
        for (int i = 0; i < includes.length; i++) {
            buf.setLength(0);
            buf.append("         <include file=\"");
            buf.append(CUtil.xmlAttribEncode(includes[i]));
            buf.append("\"/>\n");
            writer.write(buf.toString());
        }
        for (int i = 0; i < sysIncludes.length; i++) {
            buf.setLength(0);
            buf.append("         <sysinclude file=\"");
            buf.append(CUtil.xmlAttribEncode(sysIncludes[i]));
            buf.append("\"/>\n");
            writer.write(buf.toString());
        }
        writer.write("      </source>\n");
        return;
    }
    private void writeIncludePathDependencies(String includePathIdentifier,
            BufferedWriter writer, StringBuffer buf) throws IOException {
        //
        //  include path element
        //
        buf.setLength(0);
        buf.append("   <includePath signature=\"");
        buf.append(CUtil.xmlAttribEncode(includePathIdentifier));
        buf.append("\">\n");
        writer.write(buf.toString());
        Enumeration dependenciesEnum = dependencies.elements();
        while (dependenciesEnum.hasMoreElements()) {
            DependencyInfo[] dependInfos = (DependencyInfo[]) dependenciesEnum
                    .nextElement();
            for (int i = 0; i < dependInfos.length; i++) {
                DependencyInfo dependInfo = dependInfos[i];
                //
                //   if this is for the same include path
                //      then output the info
                if (dependInfo.getIncludePathIdentifier().equals(
                        includePathIdentifier)) {
                    writeDependencyInfo(writer, buf, dependInfo);
                }
            }
        }
        writer.write("   </includePath>\n");
    }
}