about summary refs log tree commit diff
path: root/docs/tool/Modules/NaturalDocs/SymbolTable.pm
blob: 02f010f31d331a487f34eb610303ca326144019a (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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
###############################################################################
#
#   Package: NaturalDocs::SymbolTable
#
###############################################################################
#
#   A package that handles all the gory details of managing symbols.  It handles where they are defined, which files
#   reference them, if any are undefined or duplicated, and loading and saving them to a file.
#
#   Usage and Dependencies:
#
#       - At any time, <RebuildAllIndexes()> can be called.
#
#       - <NaturalDocs::Settings>, <NaturalDocs::Languages>, and <NaturalDocs::Project> must be initialized before use.
#
#       - <Load()> must be called to initialize the package.  At this point, the <Information Functions> will return the symbol
#         table as of the last time Natural Docs was run.
#
#       - Note that <Load()> and <Save()> only manage <REFERENCE_TEXT> references.  All other reference types must be
#         managed by their respective classes.  They should be readded after <Load()> to recreate the state of the last time
#         Natural Docs was run.
#
#       - <Purge()> must be called, and then <NaturalDocs::Parser->ParseForInformation()> on all files that have changed so it
#         can fully resolve the symbol table via the <Modification Functions>.  Afterwards <PurgeResolvingInfo()> can be called
#         to reclaim some memory, and the symbol table will reflect the current state of the code.
#
#       - <Save()> must be called to commit any changes to the symbol table back to disk.
#
###############################################################################

# This file is part of Natural Docs, which is Copyright (C) 2003-2008 Greg Valure
# Natural Docs is licensed under the GPL


use NaturalDocs::SymbolTable::Symbol;
use NaturalDocs::SymbolTable::SymbolDefinition;
use NaturalDocs::SymbolTable::Reference;
use NaturalDocs::SymbolTable::File;
use NaturalDocs::SymbolTable::ReferenceTarget;
use NaturalDocs::SymbolTable::IndexElement;

use strict;
use integer;

package NaturalDocs::SymbolTable;



###############################################################################
# Group: Variables

#
#   handle: SYMBOLTABLE_FILEHANDLE
#
#   The file handle used with <SymbolTable.nd>.
#

#
#   hash: symbols
#
#   A hash of all <SymbolStrings>.  The keys are the <SymbolStrings> and the values are <NaturalDocs::SymbolTable::Symbol>
#   objects.
#
#   Prior to <PurgeResolvingInfo()>, both defined symbols and symbols that are merely potential interpretations of references
#   will be here.  Afterwards, only defined symbols will be here.
#
my %symbols;

#
#   hash: references
#
#   A hash of all references in the project.  The keys are <ReferenceStrings> and the values are
#   <NaturalDocs::SymbolTable::Reference> objects.
#
#   Prior to <PurgeResolvingInfo()>, all possible interpretations will be stored for each reference.  Afterwards, only the current
#   interpretation will be.
#
my %references;

#
#   hash: files
#
#   A hash of all the files that define symbols and references in the project.  The keys are the <FileNames>, and the values are
#   <NaturalDocs::SymbolTable::File> objects.
#
#   After <PurgeResolvingInfo()>, this hash will be empty.
#
my %files;

#
#   object: watchedFile
#
#   A <NaturalDocs::SymbolTable::File> object of the file being watched for changes.  This is compared to the version in <files>
#   to see if anything was changed since the last parse.
#
my $watchedFile;

#
#   string: watchedFileName
#
#   The <FileName> of the watched file, if any.  If there is no watched file, this will be undef.
#
my $watchedFileName;

#
#   hash: watchedFileSymbolDefinitions
#
#   A hashref of the symbol definition information for all the <SymbolStrings> in the watched file.  The keys are the symbol strings,
#   and the values are <NaturalDocs::SymbolTable::SymbolDefinition> objects.
#
my %watchedFileSymbolDefinitions;


#
#   hash: indexes
#
#   A hash of generated symbol indexes.  The keys are <TopicTypes> and the values are sorted arrayrefs of
#   <NaturalDocs::SymbolTable::IndexElements>, or undef if its empty.
#
my %indexes;


#
#   hash: indexChanges
#
#   A hash of all the indexes that have changed.  The keys are the <TopicTypes> and the entries are undef if they have not
#   changed, or 1 if they have.  The key will not exist if the <TopicType> has not been checked.
#
my %indexChanges;


#
#   hash: indexSectionsWithContent
#
#   A hash of which sections in an index have content.  The keys are the <TopicTypes> of each index, and the values are
#   arrayrefs of bools where the first represents symbols, the second numbers, and the rest A-Z.  If there is no information
#   available for an index, it's entry will not exist here.
#
my %indexSectionsWithContent;


#
#   bool: rebuildIndexes
#
#   Whether all indexes should be rebuilt regardless of whether they have been changed.
#
my $rebuildIndexes;



###############################################################################
# Group: Files


#
#   File: SymbolTable.nd
#
#   The storage file for the symbol table.
#
#   Format:
#
#       > [BINARY_FORMAT]
#       > [VersionInt: app version]
#
#       The file starts with the standard <BINARY_FORMAT> <VersionInt> header.
#
#       The first stage of the file is for symbol definitions, analogous to <symbols>.
#
#       > [SymbolString: symbol or undef to end] ...
#       >
#       > [UInt16: number of definitions]
#       >
#       >    [AString16: global definition file] [AString16: TopicType]
#       >       [AString16: prototype] [AString16: summary]
#       >
#       >    [AString16: definition file] ...
#       >
#       >    ...
#
#       These blocks continue until the <SymbolString> is undef.  Only defined symbols will be included in this file, so
#       number of definitions will never be zero.  The first one is always the global definition.  If a symbol does not have a
#       prototype or summary, the UInt16 length of the string will be zero.
#
#       The second stage is for references, which is analogous to <references>.  Only <REFERENCE_TEXT> references are
#       stored in this file, and their <Resolving Flags> are implied so they aren't stored either.
#
#       > [ReferenceString (no type, resolving flags): reference or undef to end]
#       >
#       > [UInt8: number of definition files]
#       >    [AString16: definition file] [AString16: definition file] ...
#
#       These blocks continue until the <ReferenceString> is undef.  Since there can be multiple using <SymbolStrings>, those
#       continue until the number of identifiers is zero.  Note that all interpretations are rebuilt rather than stored.
#
#   See Also:
#
#       <File Format Conventions>
#
#   Revisions:
#
#       1.3:
#
#           - Symbol <TopicTypes> were changed from UInt8s to AString16s, now that <TopicTypes> are strings instead of
#             integer constants.
#
#       1.22:
#
#           - File format was completely rebuilt to accommodate the new symbol format and to be in binary.  To see the plain text
#             format prior to 1.22, check out 1.21's version of this file from CVS.  It is too big a change to note here.
#


#
#   File: IndexInfo.nd
#
#   The storage file for information about the indexes.
#
#   Format:
#
#       > [Standard Header]
#
#       The standard binary file header.
#
#       > [AString16: index topic name]
#       > [uint8: symbols have content (0 or 1)]
#       > [uint8: numbers have content (0 or 1)]
#       > [uint8: A has content] [uint8: B has content] ...
#       > ...
#
#       Every index that has information about it is stored with the topic type name first, then 28 uint8s that say whether that
#       part of the index has content or not.  The first is for symbols, the second is for numbers, and the rest are for A-Z.  If an
#       index's state is unknown, it won't appear in this file.
#
#   Revisions:
#
#       1.4:
#
#           - The file is introduced.
#



###############################################################################
# Group: File Functions


#
#   Function: Load
#
#   Loads all data files from disk.
#
sub Load
    {
    my ($self) = @_;

    $self->LoadSymbolTable();
    $self->LoadIndexInfo();
    };


#
#   Function: LoadSymbolTable
#
#   Loads <SymbolTable.nd> from disk.
#
sub LoadSymbolTable
    {
    my ($self) = @_;

    my $fileIsOkay;

    if (!NaturalDocs::Settings->RebuildData() &&
        open(SYMBOLTABLE_FILEHANDLE, '<' . NaturalDocs::Project->DataFile('SymbolTable.nd')) )
        {
        # See if it's binary.
        binmode(SYMBOLTABLE_FILEHANDLE);

        my $firstChar;
        read(SYMBOLTABLE_FILEHANDLE, $firstChar, 1);

        if ($firstChar == ::BINARY_FORMAT())
            {
            my $version = NaturalDocs::Version->FromBinaryFile(\*SYMBOLTABLE_FILEHANDLE);

            # 1.3 is incompatible with previous versions.

            if (NaturalDocs::Version->CheckFileFormat( $version, NaturalDocs::Version->FromString('1.3') ))
                {  $fileIsOkay = 1;  }
            else
                {  close(SYMBOLTABLE_FILEHANDLE);  };
            }

        else
            {  close(SYMBOLTABLE_FILEHANDLE);  };
        };


    if (!$fileIsOkay)
        {
        NaturalDocs::Project->ReparseEverything();
        return;
        }

    my $raw;


    # Symbols

    for (;;)
        {
        # [SymbolString: symbol or undef to end]

        my $symbol = NaturalDocs::SymbolString->FromBinaryFile(\*SYMBOLTABLE_FILEHANDLE);

        if (!defined $symbol)
            {  last;  };

        my $symbolObject = NaturalDocs::SymbolTable::Symbol->New();
        $symbols{$symbol} = $symbolObject;

        # [UInt16: number of definitions]

        read(SYMBOLTABLE_FILEHANDLE, $raw, 2);
        my $definitionCount = unpack('n', $raw);

        do
            {
            # [AString16: (global?) definition file]

            read(SYMBOLTABLE_FILEHANDLE, $raw, 2);
            my $fileLength = unpack('n', $raw);

            my $file;
            read(SYMBOLTABLE_FILEHANDLE, $file, $fileLength);

            # [AString16: TopicType]

            read(SYMBOLTABLE_FILEHANDLE, $raw, 2);
            my $typeLength = unpack('n', $raw);

            my $type;
            read(SYMBOLTABLE_FILEHANDLE, $type, $typeLength);

            # [AString16: prototype]

            read(SYMBOLTABLE_FILEHANDLE, $raw, 2);
            my $prototypeLength = unpack('n', $raw);

            my $prototype;
            if ($prototypeLength)
                {  read(SYMBOLTABLE_FILEHANDLE, $prototype, $prototypeLength);  };

            # [AString16: summary]

            read(SYMBOLTABLE_FILEHANDLE, $raw, 2);
            my $summaryLength = unpack('n', $raw);

            my $summary;
            if ($summaryLength)
                {  read(SYMBOLTABLE_FILEHANDLE, $summary, $summaryLength);  };

            $symbolObject->AddDefinition($file, $type, $prototype, $summary);

            # Add it.

            if (!exists $files{$file})
                {  $files{$file} = NaturalDocs::SymbolTable::File->New();  };

            $files{$file}->AddSymbol($symbol);

            $definitionCount--;
            }
        while ($definitionCount);
        };


    # References

    for (;;)
        {
        # [ReferenceString (no type, resolving flags): reference or undef to end]

        my $referenceString = NaturalDocs::ReferenceString->FromBinaryFile(\*SYMBOLTABLE_FILEHANDLE,
                                                                                                              ::BINARYREF_NOTYPE() |
                                                                                                              ::BINARYREF_NORESOLVINGFLAGS(),
                                                                                                              ::REFERENCE_TEXT(), undef);

        if (!defined $referenceString)
            {  last;  };

        my $referenceObject = NaturalDocs::SymbolTable::Reference->New();
        $references{$referenceString} = $referenceObject;

        # [UInt8: number of definition files]

        read(SYMBOLTABLE_FILEHANDLE, $raw, 1);
        my $definitionCount = unpack('C', $raw);
        do
            {
            # [AString16: definition file] [AString16: definition file] ...

            read(SYMBOLTABLE_FILEHANDLE, $raw, 2);
            my $definitionLength = unpack('n', $raw);

            my $definition;
            read(SYMBOLTABLE_FILEHANDLE, $definition, $definitionLength);

            # Add it.

            $referenceObject->AddDefinition($definition);

            if (!exists $files{$definition})
                {  $files{$definition} = NaturalDocs::SymbolTable::File->New();  };

            $files{$definition}->AddReference($referenceString);

            $definitionCount--;
            }
        while ($definitionCount);

        $self->GenerateInterpretations($referenceString);
        $self->InterpretReference($referenceString);
        };

    close(SYMBOLTABLE_FILEHANDLE);
    };


#
#   Function: LoadIndexInfo
#
#   Loads <IndexInfo.nd> from disk.
#
sub LoadIndexInfo
    {
    my ($self) = @_;

    if (NaturalDocs::Settings->RebuildData())
        {  return;  };

    my $version = NaturalDocs::BinaryFile->OpenForReading( NaturalDocs::Project->DataFile('IndexInfo.nd') );

    if (!defined $version)
        {  return;  }

    # The file format hasn't changed since it was introduced.
    if (!NaturalDocs::Version->CheckFileFormat($version))
        {
        NaturalDocs::BinaryFile->Close();
        return;
        };

    my $topicTypeName;
    while ($topicTypeName = NaturalDocs::BinaryFile->GetAString16())
        {
        my $topicType = NaturalDocs::Topics->TypeFromName($topicTypeName);
        my $content = [ ];

        for (my $i = 0; $i < 28; $i++)
            {  push @$content, NaturalDocs::BinaryFile->GetUInt8();  };

        if (defined $topicType)  # The name in the file could be from a type that was deleted
            {  $indexSectionsWithContent{$topicType} = $content;  };
        };

    NaturalDocs::BinaryFile->Close();
    };


#
#   Function: Purge
#
#   Purges the symbol table of all symbols and references from files that no longer have Natural Docs content.
#
sub Purge
    {
    my ($self) = @_;

    my $filesToPurge = NaturalDocs::Project->FilesToPurge();

    # We do this in two stages.  First we delete all the references, and then we delete all the definitions.  This causes us to go
    # through the list twice, but it makes sure no purged files get added to the build list.  For example, if we deleted all of
    # Purge File A's references and definitions, and Purge File B had a reference to one of those symbols, Purge File B
    # would be added to the build list because one of its references changed.  By removing all the references in all the files
    # before removing the definitions, we avoid this.

    foreach my $file (keys %$filesToPurge)
        {
        if (exists $files{$file})
            {
            my @references = $files{$file}->References();
            foreach my $reference (@references)
                {  $self->DeleteReference($reference, $file);  };
            };
        };

    foreach my $file (keys %$filesToPurge)
        {
        if (exists $files{$file})
            {
            my @symbols = $files{$file}->Symbols();
            foreach my $symbol (@symbols)
                {  $self->DeleteSymbol($symbol, $file);  };

            delete $files{$file};
            };
        };
    };


#
#   Function: Save
#
#   Saves all data files to disk.
#
sub Save
    {
    my ($self) = @_;

    $self->SaveSymbolTable();
    $self->SaveIndexInfo();
    };


#
#   Function: SaveSymbolTable
#
#   Saves <SymbolTable.nd> to disk.
#
sub SaveSymbolTable
    {
    my ($self) = @_;

    open (SYMBOLTABLE_FILEHANDLE, '>' . NaturalDocs::Project->DataFile('SymbolTable.nd'))
        or die "Couldn't save " . NaturalDocs::Project->DataFile('SymbolTable.nd') . ".\n";

    binmode(SYMBOLTABLE_FILEHANDLE);

    print SYMBOLTABLE_FILEHANDLE '' . ::BINARY_FORMAT();

    NaturalDocs::Version->ToBinaryFile(\*SYMBOLTABLE_FILEHANDLE, NaturalDocs::Settings->AppVersion());


    # Symbols

    while (my ($symbol, $symbolObject) = each %symbols)
        {
        # Only existing symbols.
        if ($symbolObject->IsDefined())
            {
            # [SymbolString: symbol or undef to end]

            NaturalDocs::SymbolString->ToBinaryFile(\*SYMBOLTABLE_FILEHANDLE, $symbol);

            # [UInt16: number of definitions]

            my @definitions = $symbolObject->Definitions();
            print SYMBOLTABLE_FILEHANDLE pack('n', scalar @definitions);

            # [AString16: global definition file] [AString16: TopicType]

            print SYMBOLTABLE_FILEHANDLE pack('nA*nA*', length $symbolObject->GlobalDefinition(),
                                                                                   $symbolObject->GlobalDefinition(),
                                                                                   length $symbolObject->GlobalType(),
                                                                                   $symbolObject->GlobalType());

            # [AString16: prototype]

            my $prototype = $symbolObject->GlobalPrototype();

            if (defined $prototype)
                {  print SYMBOLTABLE_FILEHANDLE pack('nA*', length($prototype), $prototype);  }
            else
                {  print SYMBOLTABLE_FILEHANDLE pack('n', 0);  };

            # [AString16: summary]

            my $summary = $symbolObject->GlobalSummary();

            if (defined $summary)
                {  print SYMBOLTABLE_FILEHANDLE pack('nA*', length($summary), $summary);  }
            else
                {  print SYMBOLTABLE_FILEHANDLE pack('n', 0);  };


            foreach my $definition (@definitions)
                {
                if ($definition ne $symbolObject->GlobalDefinition())
                    {
                    # [AString16: definition file] [AString16: TopicType]

                    print SYMBOLTABLE_FILEHANDLE pack('nA*nA*', length $definition, $definition,
                                                                                           length $symbolObject->TypeDefinedIn($definition),
                                                                                           $symbolObject->TypeDefinedIn($definition));

                    # [AString16: prototype]

                    my $prototype = $symbolObject->PrototypeDefinedIn($definition);

                    if (defined $prototype)
                        {  print SYMBOLTABLE_FILEHANDLE pack('nA*', length($prototype), $prototype);  }
                    else
                        {  print SYMBOLTABLE_FILEHANDLE pack('n', 0);  };

                    # [AString16: summary]

                    my $summary = $symbolObject->SummaryDefinedIn($definition);

                    if (defined $summary)
                        {  print SYMBOLTABLE_FILEHANDLE pack('nA*', length($summary), $summary);  }
                    else
                        {  print SYMBOLTABLE_FILEHANDLE pack('n', 0);  };
                    };
                };
            };
        };

     # [SymbolString: symbol or undef to end]

     NaturalDocs::SymbolString->ToBinaryFile(\*SYMBOLTABLE_FILEHANDLE, undef);


     # References

    while (my ($reference, $referenceObject) = each %references)
        {
        my $type = NaturalDocs::ReferenceString->TypeOf($reference);

        if ($type == ::REFERENCE_TEXT())
            {
            # [ReferenceString (no type, resolving flags): reference or undef to end]

            NaturalDocs::ReferenceString->ToBinaryFile(\*SYMBOLTABLE_FILEHANDLE, $reference,
                                                                             ::BINARYREF_NOTYPE() | ::BINARYREF_NORESOLVINGFLAGS());

            # [UInt8: number of definition files]

            my @definitions = $referenceObject->Definitions();
            print SYMBOLTABLE_FILEHANDLE pack('C', scalar @definitions);

            # [AString16: definition file] [AString16: definition file] ...

            foreach my $definition (@definitions)
                {
                print SYMBOLTABLE_FILEHANDLE pack('nA*', length($definition), $definition);
                };
            };
        };

    # [ReferenceString (no type, resolving flags): reference or undef to end]

    NaturalDocs::ReferenceString->ToBinaryFile(\*SYMBOLTABLE_FILEHANDLE, undef,
                                                                     ::BINARYREF_NOTYPE() | ::BINARYREF_NORESOLVINGFLAGS());

    close(SYMBOLTABLE_FILEHANDLE);
    };


#
#   Function: SaveIndexInfo
#
#   Saves <IndexInfo.nd> to disk.
#
sub SaveIndexInfo
    {
    my ($self) = @_;

    NaturalDocs::BinaryFile->OpenForWriting( NaturalDocs::Project->DataFile('IndexInfo.nd') );

    while (my ($topicType, $content) = each %indexSectionsWithContent)
        {
        NaturalDocs::BinaryFile->WriteAString16( NaturalDocs::Topics->NameOfType($topicType) );

        for (my $i = 0; $i < 28; $i++)
            {
            if ($content->[$i])
                {  NaturalDocs::BinaryFile->WriteUInt8(1);  }
            else
                {  NaturalDocs::BinaryFile->WriteUInt8(0);  };
            };
        };

    NaturalDocs::BinaryFile->Close();
    };



###############################################################################
# Group: Modification Functions
# These functions should not be called after <PurgeResolvingInfo()>.

#
#   Function: AddSymbol
#
#   Adds a symbol definition to the table, if it doesn't already exist.  If the definition changes or otherwise requires the files that
#   reference it to be updated, the function will call <NaturalDocs::Project->RebuildFile()> to make sure that they are.
#
#   Parameters:
#
#       symbol  - The <SymbolString>.
#       file        - The <FileName> where it's defined.
#       type      - The symbol's <TopicType>.
#       prototype - The symbol's prototype, if applicable.
#       summary - The symbol's summary, if applicable.
#
sub AddSymbol #(symbol, file, type, prototype, summary)
    {
    my ($self, $symbol, $file, $type, $prototype, $summary) = @_;


    # If the symbol doesn't exist...
    if (!exists $symbols{$symbol})
        {
        # Create the symbol.  There are no references that could be interpreted as this or else it would have existed already.

        my $newSymbol = NaturalDocs::SymbolTable::Symbol->New();
        $newSymbol->AddDefinition($file, $type, $prototype, $summary);

        $symbols{$symbol} = $newSymbol;

        $self->OnIndexChange($type);
        NaturalDocs::Project->RebuildFile($file);
        }


    # If the symbol already exists...
    else
        {
        my $symbolObject = $symbols{$symbol};

        # If the symbol isn't defined, i.e. it was a potential interpretation only...
        if (!$symbolObject->IsDefined())
            {
            $symbolObject->AddDefinition($file, $type, $prototype, $summary);

            # See if this symbol provides a better interpretation of any references.  We can assume this symbol has interpretations
            # because the object won't exist without either that or definitions.

            my %referencesAndScores = $symbolObject->ReferencesAndScores();

            while (my ($referenceString, $referenceScore) = each %referencesAndScores)
                {
                my $referenceObject = $references{$referenceString};

                if (!$referenceObject->HasCurrentInterpretation() ||
                    $referenceScore > $referenceObject->CurrentScore())
                    {
                    $referenceObject->SetCurrentInterpretation($symbol);
                    $self->OnInterpretationChange($referenceString);
                    };
                };

            $self->OnIndexChange($type);
            NaturalDocs::Project->RebuildFile($file);
            }

        # If the symbol is defined but not in this file...
        elsif (!$symbolObject->IsDefinedIn($file))
            {
            $symbolObject->AddDefinition($file, $type, $prototype, $summary);

            $self->OnIndexChange($type);
            NaturalDocs::Project->RebuildFile($file);

            # We don't have to check other files because if the symbol is defined it already has a global definiton,
            # and everything else is either using that or its own definition, and thus wouldn't be affected by this.
            };

        # If the symbol was already defined in this file, ignore it.

        };


    # Add it to the file index.

    if (!exists $files{$file})
        {  $files{$file} = NaturalDocs::SymbolTable::File->New();  };

    $files{$file}->AddSymbol($symbol);


    # Add it to the watched file, if necessary.

    if (defined $watchedFileName)
        {
        $watchedFile->AddSymbol($symbol);

        if (!exists $watchedFileSymbolDefinitions{$symbol})
            {
            $watchedFileSymbolDefinitions{$symbol} =
                 NaturalDocs::SymbolTable::SymbolDefinition->New($type, $prototype, $summary);
            };
        };
    };


#
#   Function: AddReference
#
#   Adds a reference to the table, if it doesn't already exist.
#
#   Parameters:
#
#       type        - The <ReferenceType>.
#       symbol    - The reference <SymbolString>.
#       scope      - The scope <SymbolString> it appears in.
#       using       - An arrayref of scope <SymbolStrings> accessible to the reference via "using" statements, or undef if none.
#       file          - The <FileName> where the reference appears.  This is not required unless the type is <REFERENCE_TEXT>.
#       resolvingFlags - The <Resolving Flags> of the reference.  They will be ignored if the type is <REFERENCE_TEXT>.
#
#   Alternate Parameters:
#
#       referenceString - The <ReferenceString> to add.
#       file - The <FileName> where the reference appears.  This is not required unless the type is <REFERENCE_TEXT>.
#
sub AddReference #(type, symbol, scope, using, file, resolvingFlags) or (referenceString, file)
    {
    my ($self, $referenceString, $file);

    if (scalar @_ <= 3)
        {
        ($self, $referenceString, $file) = @_;
        }
    else
        {
        my ($type, $symbol, $scope, $using, $resolvingFlags);
        ($self, $type, $symbol, $scope, $using, $file, $resolvingFlags) = @_;

        $referenceString = NaturalDocs::ReferenceString->MakeFrom($type, $symbol,
                                                                                                   NaturalDocs::Languages->LanguageOf($file)->Name(),
                                                                                                   $scope, $using, $resolvingFlags);
        };


    # If the reference doesn't exist...
    if (!exists $references{$referenceString})
        {
        my $referenceObject = NaturalDocs::SymbolTable::Reference->New();

        $references{$referenceString} = $referenceObject;

        $self->GenerateInterpretations($referenceString);
        $self->InterpretReference($referenceString);
        }


    if (defined $file)
        {
        $references{$referenceString}->AddDefinition($file);


        # Add it to the file index.

        if (!exists $files{$file})
            {  $files{$file} = NaturalDocs::SymbolTable::File->New();  };

        $files{$file}->AddReference($referenceString);


        # Add it to the watched file, if necessary.

        if (defined $watchedFileName)
            {  $watchedFile->AddReference($referenceString);  };
        };
    };


#
#   Function: WatchFileForChanges
#
#   Tracks a file to see if any symbols or references were changed or deleted in ways that would require other files to be rebuilt.
#   Assumes that after this function call, the entire file will be parsed again, and thus every symbol and reference will go through
#   <AddSymbol()> and <AddReference()>.  Afterwards, call <AnalyzeChanges()> to handle any differences.
#
#   Parameters:
#
#       file - The <FileName> to watch.
#
sub WatchFileForChanges #(file)
    {
    my ($self, $file) = @_;

    $watchedFile = NaturalDocs::SymbolTable::File->New();
    $watchedFileName = $file;
    %watchedFileSymbolDefinitions = ( );
    };


#
#   Function: AnalyzeChanges
#
#   Handles any changes found when reparsing a file using <WatchFileForChanges()>.
#
sub AnalyzeChanges
    {
    my ($self) = @_;

    if (exists $files{$watchedFileName})
        {

        # Go through the references and remove any that were deleted.  Ones that were added will have already been added to
        # the table in AddReference().

        my @references = $files{$watchedFileName}->References();
        foreach my $reference (@references)
            {
            if (!$watchedFile->DefinesReference($reference))
                {  $self->DeleteReference($reference, $watchedFileName);  };
            };
        };

    # We have to check if the watched file exists again because DeleteReference() could have removed it.  I'm still not sure how a
    # file could have references without symbols, but apparently it's happened in the real world because it's crashed on people.
    if (exists $files{$watchedFileName})
        {
        # Go through the symbols.

        my $rebuildFile;

        my @symbols = $files{$watchedFileName}->Symbols();
        foreach my $symbol (@symbols)
            {
            # Delete symbols that don't exist.

            if (!$watchedFile->DefinesSymbol($symbol))
                {
                $self->DeleteSymbol($symbol, $watchedFileName);
                $rebuildFile = 1;
                }

            else
                {
                my $symbolObject = $symbols{$symbol};
                my $newSymbolDef = $watchedFileSymbolDefinitions{$symbol};

                # Update symbols that changed.

                if ( $symbolObject->TypeDefinedIn($watchedFileName) ne $newSymbolDef->Type() ||
                     $symbolObject->PrototypeDefinedIn($watchedFileName) ne $newSymbolDef->Prototype() ||
                     $symbolObject->SummaryDefinedIn($watchedFileName) ne $newSymbolDef->Summary() )
                    {
                    $self->OnIndexChange($symbolObject->TypeDefinedIn($watchedFileName));
                    $self->OnIndexChange($newSymbolDef->Type());
                    $rebuildFile = 1;

                    $symbolObject->ChangeDefinition($watchedFileName, $newSymbolDef->Type(), $newSymbolDef->Prototype(),
                                                                       $newSymbolDef->Summary());

                    # If the symbol definition was the global one, we need to update all files that reference it.  If it wasn't, the only file
                    # that could references it is itself, and the only way the symbol definition could change in the first place was if it was
                    # itself changed.
                    if ($symbolObject->GlobalDefinition() eq $watchedFileName)
                        {
                        # Rebuild the files that have references to this symbol
                        my @references = $symbolObject->References();
                        foreach my $reference (@references)
                            {
                            if ($references{$reference}->CurrentInterpretation() eq $symbol)
                                {  $self->OnTargetSymbolChange($reference);  };
                            }; # While references
                        }; # If global definition is watched file
                    }; # If the symbol definition changed
                }; # If the symbol still exists
            }; # foreach symbol in watched file

        if ($rebuildFile)
            {  NaturalDocs::Project->RebuildFile($watchedFileName);  };

        };


    $watchedFile = undef;
    $watchedFileName = undef;
    %watchedFileSymbolDefinitions = ( );
    };


#
#   Function: DeleteReference
#
#   Deletes a reference from the table.
#
#   Be careful with this function, as deleting a reference means there are no more of them in the file at all.  The tables do not
#   keep track of how many times references appear in a file.  In these cases you should instead call <WatchFileForChanges()>,
#   reparse the file, thus readding all the references, and call <AnalyzeChanges()>.
#
#   <REFERENCE_TEXT> references should *always* be managed with <WatchFileForChanges()> and <AnalyzeChanges()>.
#   This function should only be used externally for other types of references.
#
#   Parameters:
#
#       referenceString - The <ReferenceString>.
#       file - The <FileName> where the reference is.  This is not required unless the type is <REFERENCE_TEXT>.
#
sub DeleteReference #(referenceString, file)
    {
    my ($self, $referenceString, $file) = @_;


    # If the reference exists...
    if (exists $references{$referenceString})
        {
        my $referenceObject = $references{$referenceString};

        if (defined $file)
            {  $referenceObject->DeleteDefinition($file);  };

        # If there are no other definitions, or it doesn't use file definitions to begin with...
        if (!$referenceObject->IsDefined())
            {
            my @interpretations = $referenceObject->Interpretations();
            foreach my $interpretation (@interpretations)
                {
                $symbols{$interpretation}->DeleteReference($referenceString);
                };

            delete $references{$referenceString};
            };


        if (defined $file)
            {
            # Remove it from the file index.

            $files{$file}->DeleteReference($referenceString);

            if (!$files{$file}->HasAnything())
                {  delete $files{$file};  };

            # We don't need to worry about the watched file, since this function will only be called by AnalyzeChanges() and
            # LoadAndPurge().
            };
        };
    };


#
#   Function: RebuildAllIndexes
#
#   When called, it makes sure all indexes are listed as changed by <IndexChanged()>, regardless of whether they actually did
#   or not.
#
#   This can be called at any time.
#
sub RebuildAllIndexes
    {
    my $self = shift;
    $rebuildIndexes = 1;
    };


#
#   Function: PurgeResolvingInfo
#
#   Purges unnecessary information from the symbol table after it is fully resolved.  This will reduce the memory footprint for the
#   build stage.  After calling this function, you can only call the <Information Functions> and <Save()>.
#
sub PurgeResolvingInfo
    {
    my ($self) = @_;

    # Go through the symbols.  We don't need to keep around potential symbols anymore, nor do we need what references can
    # be interpreted as the defined ones.

    while (my ($symbol, $symbolObject) = each %symbols)
        {
        if ($symbolObject->IsDefined())
            {  $symbolObject->DeleteAllReferences();  }
        else
            {  delete $symbols{$symbol};  };
        };


    # Go through the references.  We don't need any of the interpretations except for the current.

    foreach my $referenceObject (values %references)
        {  $referenceObject->DeleteAllInterpretationsButCurrent();  };


    # We don't need the information by file at all.

    %files = ( );
    };


#
#   Function: PurgeIndexes
#
#   Clears all generated indexes.
#
sub PurgeIndexes
    {
    my ($self) = @_;
    %indexes = ( );
    };


###############################################################################
# Group: Information Functions
# These functions should not be called until the symbol table is fully resolved.


#
#   Function: References
#
#   Returns what the passed reference information resolve to, if anything.  Note that this only works if the reference had
#   been previously added to the table via <AddReference()> with the exact same parameters.
#
#   Parameters:
#
#       type     - The <ReferenceType>.
#       symbol - The reference <SymbolString>.
#       scope   - The scope <SymbolString> the reference appears in, or undef if none.
#       using    - An arrayref of scope <SymbolStrings> available to the reference via using statements.
#       file       - The source <FileName> the reference appears in, or undef if none.
#       resolvingFlags - The <Resolving Flags> of the reference.  Ignored if the type is <REFERENCE_TEXT>.
#
#   Alternate Parameters:
#
#       referenceString - The <ReferenceString> to resolve.
#       file - The source <FileName> the reference appears in, or undef if none.
#
#   Returns:
#
#       A <NaturalDocs::SymbolTable::ReferenceTarget> object, or undef if the reference doesn't resolve to anything.
#
sub References #(type, symbol, scope, using, file, resolvingFlags) or (referenceString, file)
    {
    my ($self, $referenceString, $file);

    if (scalar @_ <= 3)
        {  ($self, $referenceString, $file) = @_;  }
    else
        {
        my ($type, $symbol, $scope, $using, $resolvingFlags);
        ($self, $type, $symbol, $scope, $using, $file, $resolvingFlags) = @_;

        $referenceString = NaturalDocs::ReferenceString->MakeFrom($type, $symbol,
                                                                                                  NaturalDocs::Languages->LanguageOf($file)->Name(),
                                                                                                  $scope, $using, $resolvingFlags);
        };

    if (exists $references{$referenceString} && $references{$referenceString}->HasCurrentInterpretation())
        {
        my $targetSymbol = $references{$referenceString}->CurrentInterpretation();
        my $targetObject = $symbols{$targetSymbol};

        my $targetFile;
        my $targetType;
        my $targetPrototype;
        my $targetSummary;

        if (defined $file && $targetObject->IsDefinedIn($file))
            {
            $targetFile = $file;
            $targetType = $targetObject->TypeDefinedIn($file);
            $targetPrototype = $targetObject->PrototypeDefinedIn($file);
            $targetSummary = $targetObject->SummaryDefinedIn($file);
            }
        else
            {
            $targetFile = $targetObject->GlobalDefinition();
            $targetType = $targetObject->GlobalType();
            $targetPrototype = $targetObject->GlobalPrototype();
            $targetSummary = $targetObject->GlobalSummary();
            };

        return NaturalDocs::SymbolTable::ReferenceTarget->New($targetSymbol, $targetFile, $targetType, $targetPrototype,
                                                                                             $targetSummary);
        }

    else
        {  return undef;  };
    };


#
#   Function: Lookup
#
#   Returns information on the passed <SymbolString>, if it exists.  Note that the symbol must be fully resolved.
#
#   Parameters:
#
#       symbol - The <SymbolString>.
#       file - The source <FileName> the reference appears in, or undef if none.
#
#   Returns:
#
#       A <NaturalDocs::SymbolTable::ReferenceTarget> object, or undef if the symbol isn't defined.
#
sub Lookup #(symbol, file)
    {
    my ($self, $symbol, $file) = @_;

    my $symbolObject = $symbols{$symbol};

    if (defined $symbolObject)
        {
        my $targetFile;
        my $targetType;
        my $targetPrototype;
        my $targetSummary;

        if (defined $file && $symbolObject->IsDefinedIn($file))
            {
            $targetFile = $file;
            $targetType = $symbolObject->TypeDefinedIn($file);
            $targetPrototype = $symbolObject->PrototypeDefinedIn($file);
            $targetSummary = $symbolObject->SummaryDefinedIn($file);
            }
        else
            {
            $targetFile = $symbolObject->GlobalDefinition();
            $targetType = $symbolObject->GlobalType();
            $targetPrototype = $symbolObject->GlobalPrototype();
            $targetSummary = $symbolObject->GlobalSummary();
            };

        return NaturalDocs::SymbolTable::ReferenceTarget->New($symbol, $targetFile, $targetType, $targetPrototype,
                                                                                             $targetSummary);
        }

    else
        {  return undef;  };
    };


#
#   Function: Index
#
#   Returns a symbol index.
#
#   Indexes are generated on demand, but they are stored so subsequent calls for the same index will be fast.  Call
#   <PurgeIndexes()> to clear the generated indexes.
#
#   Parameters:
#
#       type  - The <TopicType> of symbol to limit the index to, or undef for none.
#
#   Returns:
#
#       An arrayref of sections.  The first represents all the symbols, the second the numbers, and the rest A through Z.
#       Each section is a sorted arrayref of <NaturalDocs::SymbolTable::IndexElement> objects.  If a section has no content,
#       it will be undef.
#
sub Index #(type)
    {
    my ($self, $type) = @_;

    if (!exists $indexes{$type})
        {  $indexes{$type} = $self->MakeIndex($type);  };

    return $indexes{$type};
    };


#
#   Function: HasIndexes
#
#   Determines which indexes out of a list actually have content.
#
#   Parameters:
#
#       types  - An existence hashref of the <TopicTypes> to check for indexes.
#
#   Returns:
#
#       An existence hashref of all the specified indexes that have content.  Will return an empty hashref if none.
#
sub HasIndexes #(types)
    {
    my ($self, $types) = @_;

    # EliminationHash is a copy of all the types, and the types will be deleted as they are found.  This allows us to quit early if
    # we've found all the types because the hash will be empty.  We'll later return the original hash minus what was left over
    # in here, which are the ones that weren't found.
    my %eliminationHash = %$types;

    finddefs:
    foreach my $symbolObject (values %symbols)
        {
        foreach my $definition ($symbolObject->Definitions())
            {
            delete $eliminationHash{ $symbolObject->TypeDefinedIn($definition) };
            delete $eliminationHash{ ::TOPIC_GENERAL() };

            if (!scalar keys %eliminationHash)
                {  last finddefs;  };
            };
        };

    my $result = { %$types };

    foreach my $type (keys %eliminationHash)
        {  delete $result->{$type};  };

    return $result;
    };


#
#   Function: IndexChanged
#
#   Returns whether the specified index has changed.
#
#   Parameters:
#
#       type  - The <TopicType> to limit the index to.
#
sub IndexChanged #(TopicType type)
    {
    my ($self, $type) = @_;
    return ($rebuildIndexes || defined $indexChanges{$type});
    };


#
#   Function: IndexSectionsWithContent
#
#   Returns an arrayref of whether each section of the specified index has content.  The first entry will be for symbols, the second
#   for numbers, and the rest A-Z.  Do not change the arrayref.
#
sub IndexSectionsWithContent #(TopicType type)
    {
    my ($self, $type) = @_;

    if (!exists $indexSectionsWithContent{$type})
        {
        # This is okay because Index() stores generated indexes.  It's not an expensive operation unless the index was never asked
        # for before or it will never be asked for otherwise, and this shouldn't be the case.

        my $index = $self->Index($type);
        my $content = [ ];

        for (my $i = 0; $i < 28; $i++)
            {
            push @$content, (defined $index->[$i] ? 1 : 0);
            };

        $indexSectionsWithContent{$type} = $content;
        };

    return $indexSectionsWithContent{$type};
    };



###############################################################################
# Group: Event Handlers


#
#   Function: OnIndexChange
#
#   Called whenever a change happens to a symbol that would cause an index to be regenerated.
#
#   Parameters:
#
#       type - The <TopicType> of the symbol that caused the change.
#
sub OnIndexChange #(TopicType type)
    {
    my ($self, $type) = @_;

    $indexChanges{$type} = 1;
    $indexChanges{::TOPIC_GENERAL()} = 1;
    delete $indexSectionsWithContent{$type};
    };


#
#   Function: OnInterpretationChange
#
#   Called whenever the current interpretation of a reference changes, meaning it switched from one symbol to another.
#
#   Parameters:
#
#       referenceString - The <ReferenceString> whose current interpretation changed.
#
sub OnInterpretationChange #(referenceString)
    {
    my ($self, $referenceString) = @_;
    my $referenceType = NaturalDocs::ReferenceString->TypeOf($referenceString);

    if ($referenceType == ::REFERENCE_TEXT())
        {
        my @referenceDefinitions = $references{$referenceString}->Definitions();

        foreach my $referenceDefinition (@referenceDefinitions)
            {
            NaturalDocs::Project->RebuildFile($referenceDefinition);
            };
        }

    elsif (NaturalDocs::Constants->IsClassHierarchyReference($referenceType))
        {
        NaturalDocs::ClassHierarchy->OnInterpretationChange($referenceString);
        };
    };


#
#   Function: OnTargetSymbolChange
#
#   Called whenever the symbol that serves as the interpretation of a reference changes, but the reference still resolves to
#   the same symbol.  This would happen if the type, prototype, summary, or which file serves as global definition of the symbol
#   changes.
#
#   Parameters:
#
#       referenceString - The <ReferenceString> whose interpretation's symbol changed.
#
sub OnTargetSymbolChange #(referenceString)
    {
    my ($self, $referenceString) = @_;
    my $referenceType = NaturalDocs::ReferenceString->TypeOf($referenceString);

    if ($referenceType == ::REFERENCE_TEXT())
        {
        my @referenceDefinitions = $references{$referenceString}->Definitions();

        foreach my $referenceDefinition (@referenceDefinitions)
            {
            NaturalDocs::Project->RebuildFile($referenceDefinition);
            };
        }

    elsif (NaturalDocs::Constants->IsClassHierarchyReference($referenceType))
        {
        NaturalDocs::ClassHierarchy->OnTargetSymbolChange($referenceString);
        };
    };



###############################################################################
# Group: Support Functions


#
#   Function: DeleteSymbol
#
#   Removes a symbol definition from the table.  It will call <OnInterpretationChange()> for all references that have it as their
#   current interpretation.
#
#   External code should not attempt to delete symbols using this function.  Instead it should call <WatchFileFoChanges()>,
#   reparse the file, and call <AnalyzeChanges()>.
#
#   Parameters:
#
#       symbol - The <SymbolString>.
#       file       - The <FileName> where the definition is.
#
sub DeleteSymbol #(symbol, file)
    {
    my ($self, $symbol, $file) = @_;


    # If the symbol and definition exist...
    if (exists $symbols{$symbol} && $symbols{$symbol}->IsDefinedIn($file))
        {
        my $symbolObject = $symbols{$symbol};
        my $wasGlobal = ($symbolObject->GlobalDefinition() eq $file);

        $self->OnIndexChange($symbolObject->TypeDefinedIn($file));

        $symbolObject->DeleteDefinition($file);

        # If this was one definition of many...
        if ($symbolObject->IsDefined())
            {

            # If this was the global definition...
            if ($wasGlobal)
                {
                # Update every file that referenced the global symbol; i.e. every file that doesn't have its own definition.

                my @references = $symbolObject->References();

                foreach my $reference (@references)
                    {
                    if ($references{$reference}->CurrentInterpretation() eq $symbol)
                        {
                        $self->OnTargetSymbolChange($reference);
                        };
                    };
                }

            # If this wasn't the global definition...
            else
                {
                # It's a safe bet that we don't need to do anything here.  The only thing that we even need to look for here is if the
                # file referenced its own symbol and thus should be rebuilt.  However, if the file is having a symbol deleted, it either
                # changed or was itself deleted.  If it changed and still has other Natural Docs content, it should already be on the
                # rebuild list.  If it was deleted or no longer has Natural Docs content, we certainly don't want to add it to the rebuild
                # list.
                };
            }

        # If this is the only definition...
        else
            {
            # If this symbol is the interpretation of any references...
            if ($symbolObject->HasReferences())
                {
                # If this was the current interpretation of any references, reinterpret them and rebuild their files.

                my @references = $symbolObject->References();

                foreach my $reference (@references)
                    {
                    if ($references{$reference}->CurrentInterpretation() eq $symbol)
                        {
                        $self->InterpretReference($reference);
                        $self->OnInterpretationChange($reference);
                        };
                    };
                }

            # If there are no interpretations of the symbol...
            else
                {
                # Delete the symbol entirely.
                delete $symbols{$symbol};
                };
            };

        # Remove it from the file index.

        $files{$file}->DeleteSymbol($symbol);

        if (!$files{$file}->HasAnything())
            {  delete $files{$file};  };


        # We don't need to worry about the watched file, since this function will only be called by AnalyzeChanges() and
        # LoadAndPurge().
        };
    };


#
#   Function: GenerateInterpretations
#
#   Generates the list of interpretations for the passed reference.  Also creates potential symbols as necessary.
#
#   Parameters:
#
#       referenceString - The <ReferenceString> to generate the interpretations of.
#
sub GenerateInterpretations #(referenceString)
    {
    my ($self, $referenceString) = @_;

    my ($type, $symbol, $languageName, $scope, $using, $resolvingFlags) =
        NaturalDocs::ReferenceString->InformationOf($referenceString);

    # RESOLVE_NOPLURAL is handled by having @singulars be empty.
    my @singulars;
    if (!($resolvingFlags & ::RESOLVE_NOPLURAL()))
        {  @singulars = $self->SingularInterpretationsOf($symbol);  };

    # Since higher scores are better, we'll start at a high number and decrement.
    my $score = 50000;


    # If RESOLVE_RELATIVE is set, we do all the scope relatives before the global.
    if ($resolvingFlags & ::RESOLVE_RELATIVE())
        {
        $score = $self->GenerateRelativeInterpretations($referenceString, $symbol, \@singulars, $scope, $score);
        }

    # If neither RESOLVE_RELATIVE nor RESOLVE_ABSOLUTE is set, we only do the local before the global.
    elsif (!($resolvingFlags & ::RESOLVE_ABSOLUTE()))
        {
        $self->AddInterpretation($referenceString, NaturalDocs::SymbolString->Join($scope, $symbol), $score);
        $score--;

        foreach my $singular (@singulars)
            {
            $self->AddInterpretation($referenceString, NaturalDocs::SymbolString->Join($scope, $singular), $score);
            $score--;
            };
        };


    # Do the global.

    $self->AddInterpretation($referenceString, $symbol, $score);
    $score--;

    foreach my $singular (@singulars)
        {
        $self->AddInterpretation($referenceString, $singular, $score);
        $score--;
        };


    # If neither RESOLVE_RELATIVE nor RESOLVE_ABSOLUTE is set, we need to do the rest of the scope relatives after the global.
    if (!($resolvingFlags & ::RESOLVE_RELATIVE()) && !($resolvingFlags & ::RESOLVE_ABSOLUTE()))
        {
        $score = $self->GenerateRelativeInterpretations($referenceString, $symbol, \@singulars, $scope, $score, 1);
        };


    # Finally, if RESOLVE_NOUSING isn't set, go through the using scopes.
    if (!($resolvingFlags & ::RESOLVE_NOUSING()) && defined $using)
        {
        foreach my $usingScope (@$using)
            {
            if ($resolvingFlags & ::RESOLVE_ABSOLUTE())
                {
                $self->AddInterpretation($referenceString, NaturalDocs::SymbolString->Join($usingScope, $symbol), $score);
                $score--;

                foreach my $singular (@singulars)
                    {
                    $self->AddInterpretation($referenceString, NaturalDocs::SymbolString->Join($usingScope, $singular), $score);
                    $score--;
                    };
                }
            else
                {
                $score = $self->GenerateRelativeInterpretations($referenceString, $symbol, \@singulars, $usingScope, $score);
                };
            };
        };
    };


#
#   Function: GenerateRelativeInterpretations
#
#   Generates the list of relative interpretations for the passed reference and packages.  Also creates potential symbols as
#   necessary.
#
#   This function will _not_ create global interpretations.  It _will_ create a local interpretations (symbol + all packages) unless
#   you set dontUseFull.
#
#   Parameters:
#
#       referenceString - The <ReferenceString> to generate interpretations for.
#       symbol - The <SymbolString> to generate interpretations of.
#       singulars - A reference to an array of singular <SymbolStrings> to also generate interpretations of.  Set to an empty array
#                       if none.
#       package - The package <SymbolString> to use.  May be undef.
#       score - The starting score to apply.
#       dontUseFull - Whether to not generate an interpretation including the full package identifier.  If set, generated interpretations
#                           will start one level down.
#
#   Returns:
#
#       The next unused score.  This is basically the passed score minus the number of interpretations created.
#
sub GenerateRelativeInterpretations #(referenceString, symbol, singulars, package, score, dontUseFull)
    {
    my ($self, $referenceString, $symbol, $singulars, $package, $score, $dontUseFull) = @_;

    my @packages = NaturalDocs::SymbolString->IdentifiersOf($package);

    # The last package index to include.  This number is INCLUSIVE!
    my $packageLevel = scalar @packages - 1;

    if ($dontUseFull)
        {  $packageLevel--;  };

    while ($packageLevel >= 0)
        {
        $self->AddInterpretation($referenceString, NaturalDocs::SymbolString->Join(@packages[0..$packageLevel], $symbol),
                                             $score);
        $score--;

        foreach my $singular (@$singulars)
            {
            $self->AddInterpretation($referenceString, NaturalDocs::SymbolString->Join(@packages[0..$packageLevel], $singular),
                                                 $score);
            $score--;
            };

        $packageLevel--;
        };

    return $score;
    };


#
#   Function: SingularInterpretationsOf
#
#   Generates singular interpretations of a <SymbolString> if it can be interpreted as a plural.  Not all of them will be valid singular
#   forms, but that doesn't matter since it's incredibly unlikely an invalid form would exist as a symbol.  What matters is that the
#   legimate singular is present on the list.
#
#   Parameters:
#
#       symbol - The <SymbolString>.
#
#   Returns:
#
#       An array of potential singular interpretations as <SymbolStrings>, in no particular order.  If the symbol can't be interpreted
#       as a plural, returns an empty array.
#
sub SingularInterpretationsOf #(symbol)
    {
    my ($self, $symbol) = @_;

    my @identifiers = NaturalDocs::SymbolString->IdentifiersOf($symbol);
    my $lastIdentifier = pop @identifiers;
    my $preIdentifiers = NaturalDocs::SymbolString->Join(@identifiers);

    my @results;

    # First cut off any 's or ' at the end, since they can appear after other plural forms.
    if ($lastIdentifier =~ s/\'s?$//i)
        {
        push @results, NaturalDocs::SymbolString->Join($preIdentifiers, $lastIdentifier);
        };

    # See http://www.gsu.edu/~wwwesl/egw/crump.htm for a good list of potential plural forms.  There are a couple more than
    # listed below, but they're fairly rare and this is already seriously over-engineered.  This is split by suffix length to make
    # comparisons more efficient.

    # The fact that this will generate some impossible combinations (leaves => leave, leav, leaf, leafe) doesn't matter.  It's very
    # unlikely that more than one will manage to match a defined symbol.  Even if they do (leave, leaf), it's incredibly unlikely
    # that someone has defined an impossible one (leav, leafe).  So it's not so important that we remove impossible combinations,
    # just that we include all the possible ones.

    my @suffixGroups = ( [ 's', undef,  # boys => boy
                                       'i', 'us',  # alumni => alumnus
                                       'a', 'um', # errata => erratum
                                       'a', 'on' ],  # phenomena => phenomenon

                                    [ 'es', undef,  # foxes => fox
                                      'ae', 'a' ],  # amoebae => amoeba

                                    [ 'ies', 'y',  # pennies => penny
                                      'ves', 'f',  # calves => calf
                                      'ves', 'fe',  # knives => knife
                                      'men', 'man',  # women => woman
                                      'ice', 'ouse',  # mice => mouse
                                      'oes', 'o',  # vetoes => veto
                                      'ces', 'x',  # matrices => matrix
                                      'xen', 'x' ],  # oxen => ox

                                    [ 'ices', 'ex',  # indices => index
                                      'feet', 'foot',  # feet => foot
                                      'eese', 'oose',  # geese => goose
                                      'eeth', 'ooth',  # teeth => tooth
                                      'dren', 'd' ] );  # children => child

    my $suffixLength = 1;

    foreach my $suffixGroup (@suffixGroups)
        {
        my $identifierSuffix = lc( substr($lastIdentifier, 0 - $suffixLength) );
        my $cutIdentifier = substr($lastIdentifier, 0, 0 - $suffixLength);

        for (my $i = 0; $i + 1 < scalar @$suffixGroup; $i += 2)
            {
            my $suffix = $suffixGroup->[$i];
            my $replacement = $suffixGroup->[$i + 1];

            if ($identifierSuffix eq $suffix)
                {
                if (defined $replacement)
                    {
                    push @results, NaturalDocs::SymbolString->Join($preIdentifiers, $cutIdentifier . $replacement);
                    push @results, NaturalDocs::SymbolString->Join($preIdentifiers, $cutIdentifier . uc($replacement));
                    }
                else
                    {
                    push @results, NaturalDocs::SymbolString->Join($preIdentifiers, $cutIdentifier);
                    };
                };
            };

        $suffixLength++;
        };

    return @results;
    };


#
#   Function: AddInterpretation
#
#   Adds an interpretation to an existing reference.  Creates potential symbols as necessary.
#
#   Parameters:
#
#       referenceString - The <ReferenceString> to add the interpretation to.
#       symbol - The <SymbolString> the reference can be interpreted as.
#       score - The score of the interpretation.
#
sub AddInterpretation #(referenceString, symbol, score)
    {
    my ($self, $referenceString, $symbol, $score) = @_;

    $references{$referenceString}->AddInterpretation($symbol, $score);

    # Create a potential symbol if it doesn't exist.

    if (!exists $symbols{$symbol})
        {  $symbols{$symbol} = NaturalDocs::SymbolTable::Symbol->New();  };

    $symbols{$symbol}->AddReference($referenceString, $score);
    };


#
#   Function: InterpretReference
#
#   Interprets the passed reference, matching it to the defined symbol with the highest score.  If the symbol is already
#   interpreted, it will reinterpret it.  If there are no matches, it will make it an undefined reference.
#
#   Parameters:
#
#       referenceString - The <ReferenceString> to interpret.
#
sub InterpretReference #(referenceString)
    {
    my ($self, $referenceString) = @_;

    my $interpretation;
    my $currentInterpretation;
    my $score;
    my $currentScore = -1;

    my $referenceObject = $references{$referenceString};

    my %interpretationsAndScores = $referenceObject->InterpretationsAndScores();
    while ( ($interpretation, $score) = each %interpretationsAndScores )
        {
        if ($score > $currentScore && $symbols{$interpretation}->IsDefined())
            {
            $currentScore = $score;
            $currentInterpretation = $interpretation;
            };
        };

    if ($currentScore > -1)
        {  $referenceObject->SetCurrentInterpretation($currentInterpretation);  }
    else
        {  $referenceObject->SetCurrentInterpretation(undef);  };
    };


#
#   Function: MakeIndex
#
#   Generates a symbol index.
#
#   Parameters:
#
#       type  - The <TopicType> to limit the index to.
#
#   Returns:
#
#       An arrayref of sections.  The first represents all the symbols, the second the numbers, and the rest A through Z.
#       Each section is a sorted arrayref of <NaturalDocs::SymbolTable::IndexElement> objects.  If a section has no content,
#       it will be undef.
#
sub MakeIndex #(type)
    {
    my ($self, $type) = @_;


    # Go through the symbols and generate IndexElements for any that belong in the index.

    # Keys are the symbol strings, values are IndexElements.
    my %indexSymbols;

    while (my ($symbolString, $object) = each %symbols)
        {
        my ($symbol, $package) = $self->SplitSymbolForIndex($symbolString, $object->GlobalType());
        my @definitions = $object->Definitions();

        foreach my $definition (@definitions)
            {
            my $definitionType = $object->TypeDefinedIn($definition);

            if ($type eq ::TOPIC_GENERAL() || $type eq $definitionType)
                {
                if (!exists $indexSymbols{$symbol})
                    {
                    $indexSymbols{$symbol} =
                        NaturalDocs::SymbolTable::IndexElement->New($symbol, $package, $definition, $definitionType,
                                                                                               $object->PrototypeDefinedIn($definition),
                                                                                               $object->SummaryDefinedIn($definition) );
                    }
                else
                    {
                    $indexSymbols{$symbol}->Merge($package, $definition, $definitionType,
                                                                       $object->PrototypeDefinedIn($definition),
                                                                       $object->SummaryDefinedIn($definition) );
                    };
                }; # If type matches
            }; # Each definition
        }; # Each symbol


    # Generate sortable symbols for each IndexElement, sort them internally, and divide them into sections.

    my $sections = [ ];

    foreach my $indexElement (values %indexSymbols)
        {
        $indexElement->Sort();
        $indexElement->MakeSortableSymbol();

        my $sectionNumber;

        if ($indexElement->SortableSymbol() =~ /^([a-z])/i)
            {  $sectionNumber = ord(lc($1)) - ord('a') + 2;  }
        elsif ($indexElement->SortableSymbol() =~ /^[0-9]/)
            {  $sectionNumber = 1;  }
        else
            {  $sectionNumber = 0;  };

        if (!defined $sections->[$sectionNumber])
            {  $sections->[$sectionNumber] = [ ];  };

        push @{$sections->[$sectionNumber]}, $indexElement;
        };


    # Sort each section.

    for (my $i = 0; $i < scalar @$sections; $i++)
        {
        if (defined $sections->[$i])
            {
            @{$sections->[$i]} = sort
                {
                my $result = ::StringCompare($a->SortableSymbol(), $b->SortableSymbol());

                if ($result == 0)
                    {  $result = ::StringCompare($a->IgnoredPrefix(), $b->IgnoredPrefix());  };

                return $result;
                }
            @{$sections->[$i]};
            };
        };

    return $sections;
    };


#
#   Function: SplitSymbolForIndex
#
#   Splits a <SymbolString> into its symbol and package portions for indexing.
#
#   Parameters:
#
#       symbol - The <SymbolString>.
#       type - Its <TopicType>.
#
#   Returns:
#
#       The array ( symbol, package ), which are both <SymbolStrings>.  If the symbol is global, package will be undef.
#
sub SplitSymbolForIndex #(symbol, type)
    {
    my ($self, $symbol, $type) = @_;

    my $scope = NaturalDocs::Topics->TypeInfo($type)->Scope();

    if ($scope == ::SCOPE_START() || $scope == ::SCOPE_ALWAYS_GLOBAL())
        {  return ( $symbol, undef );  }
    else
        {
        my @identifiers = NaturalDocs::SymbolString->IdentifiersOf($symbol);

        $symbol = pop @identifiers;
        my $package = NaturalDocs::SymbolString->Join(@identifiers);

        return ( $symbol, $package );
        };
    };


1;