File: unitdictionary.pas

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (1283 lines) | stat: -rw-r--r-- 38,126 bytes parent folder | download | duplicates (2)
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
{
 ***************************************************************************
 *                                                                         *
 *   This source is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This code is distributed in the hope that it will be useful, but      *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   General Public License for more details.                              *
 *                                                                         *
 *   A copy of the GNU General Public License is available on the World    *
 *   Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also      *
 *   obtain it by writing to the Free Software Foundation,                 *
 *   Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.   *
 *                                                                         *
 ***************************************************************************

  Author: Mattias Gaertner

  Abstract:
    Quick lookup database for identifiers in units.
}
unit UnitDictionary;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Laz_AVL_Tree,
  // LazUtils
  LazFileUtils, AvgLvlTree,
  // Codetools
  BasicCodeTools, FileProcs, CodeToolsStructs, FindDeclarationCache,
  CodeToolManager, CodeCache;

const
  // Version 2: added unit and group use count
  UDFileVersion = 2;
  UDFileHeader = 'UnitDirectory:';
type
  TUDIdentifier = class;
  TUDUnit = class;
  TUnitDictionary = class;

  { TUDItem }

  TUDItem = class
  public
    Name: string;
  end;

  { TUDFileItem }

  TUDFileItem = class(TUDItem)
  public
    Filename: string;
    constructor Create(const aName, aFilename: string);
  end;

  { TUDUnitGroup }

  TUDUnitGroup = class(TUDFileItem)
  public
    Dictionary: TUnitDictionary;
    Units: TMTAVLTree; // tree of TIDUnit sorted with CompareIDItems
    UseCount: int64;
    constructor Create(const aName, aFilename: string);
    destructor Destroy; override;
    function AddUnit(NewUnit: TUDUnit): TUDUnit; overload;
    procedure RemoveUnit(TheUnit: TUDUnit);
  end;

  { TUDUnit }

  TUDUnit = class(TUDFileItem)
  public
    FileAge: longint;
    ToolStamp: integer;
    FirstIdentifier, LastIdentifier: TUDIdentifier;
    Groups: TMTAVLTree; // tree of TUDUnitGroup sorted with CompareIDItems
    UseCount: int64;
    constructor Create(const aName, aFilename: string);
    destructor Destroy; override;
    function AddIdentifier(Item: TUDIdentifier): TUDIdentifier;
    function IsInGroup(Group: TUDUnitGroup): boolean;
    function GetDictionary: TUnitDictionary;
    function HasIdentifier(Item: TUDIdentifier): boolean; // very slow
  end;

  { TUDIdentifier }

  TUDIdentifier = class(TUDItem)
  public
    DUnit: TUDUnit;
    NextInUnit: TUDIdentifier;
    constructor Create(const aName: string); overload;
    constructor Create(aName: PChar); overload;
  end;

  ECTUnitDictionaryLoadError = class(Exception)
  public
  end;

  { TUnitDictionary }

  TUnitDictionary = class
  private
    FChangeStamp: int64;
    FNoGroup: TUDUnitGroup;
    FIdentifiers: TMTAVLTree; // tree of TUDIdentifier sorted with CompareIDItems
    FUnitsByName: TMTAVLTree; // tree of TUDUnit sorted with CompareIDItems
    FUnitsByFilename: TMTAVLTree; // tree of TUDUnit sorted with CompareIDFileItems
    FUnitGroupsByName: TMTAVLTree; // tree of TUDUnitGroup sorted with CompareIDItems
    FUnitGroupsByFilename: TMTAVLTree; // tree of TUDUnitGroup sorted with CompareIDFileItems
    procedure RemoveIdentifier(Item: TUDIdentifier);
    procedure ClearIdentifiersOfUnit(TheUnit: TUDUnit);
  public
    constructor Create;
    destructor Destroy; override;
    procedure Clear(CreateDefaults: boolean = true);
    procedure ConsistencyCheck;
    procedure SaveToFile(const Filename: string);
    procedure SaveToStream(aStream: TStream);
    procedure LoadFromFile(const Filename: string; KeepData: boolean);
    procedure LoadFromStream(aStream: TMemoryStream;
      KeepData: boolean // keep existing data, only new units and groups will be added
      );
    function Equals(Dictionary: TUnitDictionary): boolean; reintroduce;
    property ChangeStamp: int64 read FChangeStamp;
    procedure IncreaseChangeStamp;

    // groups
    function AddUnitGroup(Group: TUDUnitGroup): TUDUnitGroup; overload;
    function AddUnitGroup(aFilename: string; aName: string = ''): TUDUnitGroup; overload;
    procedure DeleteGroup(Group: TUDUnitGroup; DeleteUnitsWithoutGroup: boolean);
    property NoGroup: TUDUnitGroup read FNoGroup;
    property UnitGroupsByName: TMTAVLTree read FUnitGroupsByName;
    property UnitGroupsByFilename: TMTAVLTree read FUnitGroupsByFilename;
    function FindGroupWithFilename(const aFilename: string): TUDUnitGroup;

    // units
    function AddUnit(const aFilename: string; aName: string = ''; Group: TUDUnitGroup = nil): TUDUnit; overload;
    procedure DeleteUnit(TheUnit: TUDUnit; DeleteEmptyGroups: boolean);
    function ParseUnit(UnitFilename: string; Group: TUDUnitGroup = nil): TUDUnit; overload;
    function ParseUnit(Code: TCodeBuffer; Group: TUDUnitGroup = nil): TUDUnit; overload;
    function ParseUnit(Tool: TCodeTool; Group: TUDUnitGroup = nil): TUDUnit; overload;
    function FindUnitWithFilename(const aFilename: string): TUDUnit;
    procedure IncreaseUnitUseCount(TheUnit: TUDUnit);
    property UnitsByName: TMTAVLTree read FUnitsByName;
    property UnitsByFilename: TMTAVLTree read FUnitsByFilename;

    // identifiers
    property Identifiers: TMTAVLTree read FIdentifiers;
  end;

function CompareNameWithIDItem(NamePChar, Item: Pointer): integer;
function CompareIDItems(Item1, Item2: Pointer): integer;
function CompareFileNameWithIDFileItem(NameAnsiString, Item: Pointer): integer;
function CompareIDFileItems(Item1, Item2: Pointer): integer;

procedure IDCheckUnitNameAndFilename(const aName, aFilename: string);

implementation

function CompareNameWithIDItem(NamePChar, Item: Pointer): integer;
var
  i: TUDItem absolute Item;
begin
  Result:=CompareDottedIdentifiers(PChar(NamePChar),PChar(Pointer(i.Name)));
end;

function CompareIDItems(Item1, Item2: Pointer): integer;
var
  i1: TUDItem absolute Item1;
  i2: TUDItem absolute Item2;
begin
  Result:=CompareDottedIdentifiers(PChar(Pointer(i1.Name)),PChar(Pointer(i2.Name)));
end;

function CompareFileNameWithIDFileItem(NameAnsiString, Item: Pointer): integer;
var
  i: TUDFileItem absolute Item;
begin
  Result:=CompareFilenames(AnsiString(NameAnsiString),i.Filename);
end;

function CompareIDFileItems(Item1, Item2: Pointer): integer;
var
  i1: TUDFileItem absolute Item1;
  i2: TUDFileItem absolute Item2;
begin
  Result:=CompareFilenames(i1.Filename,i2.Filename);
end;

procedure IDCheckUnitNameAndFilename(const aName, aFilename: string);

  procedure InvalidName;
  begin
    raise Exception.Create('invalid UnitName="'+aName+'" Filename="'+aFilename+'"');
  end;

var
  ShortName: String;
begin
  ShortName:=ExtractFileNameOnly(aFilename);
  if CompareDottedIdentifiers(PChar(Pointer(aName)),PChar(Pointer(ShortName)))<>0
  then
    InvalidName;
end;

{ TUDIdentifier }

constructor TUDIdentifier.Create(const aName: string);
begin
  Name:=aName;
end;

constructor TUDIdentifier.Create(aName: PChar);
begin
  Name:=GetIdentifier(aName);
end;

constructor TUDUnit.Create(const aName, aFilename: string);
begin
  ToolStamp:=CTInvalidChangeStamp;
  IDCheckUnitNameAndFilename(aName,aFilename);
  inherited Create(aName,aFilename);
  Groups:=TMTAVLTree.Create(@CompareIDItems);
end;

destructor TUDUnit.Destroy;
begin
  // the groups are freed by the TUnitDictionary
  FreeAndNil(Groups);
  inherited Destroy;
end;

function TUDUnit.AddIdentifier(Item: TUDIdentifier): TUDIdentifier;
begin
  if Item.DUnit<>nil then RaiseCatchableException('');
  Result:=Item;
  Result.DUnit:=Self;
  if LastIdentifier<>nil then
    LastIdentifier.NextInUnit:=Result
  else
    FirstIdentifier:=Result;
  Result.NextInUnit:=nil;
  LastIdentifier:=Result;
end;

function TUDUnit.IsInGroup(Group: TUDUnitGroup): boolean;
begin
  Result:=AVLFindPointer(Groups,Group)<>nil;
end;

function TUDUnit.GetDictionary: TUnitDictionary;
begin
  Result:=TUDUnitGroup(Groups.Root.Data).Dictionary;
end;

function TUDUnit.HasIdentifier(Item: TUDIdentifier): boolean;
var
  i: TUDIdentifier;
  j: Integer;
begin
  i:=FirstIdentifier;
  j:=0;
  while i<>nil do begin
    if i=Item then exit(true);
    i:=i.NextInUnit;
    inc(j);
    if j>10000000 then RaiseCatchableException('');
  end;
  Result:=false;
end;

{ TUDUnitGroup }

constructor TUDUnitGroup.Create(const aName, aFilename: string);
begin
  IDCheckUnitNameAndFilename(aName,aFilename);
  inherited Create(aName,aFilename);
  Units:=TMTAVLTree.Create(@CompareIDItems);
end;

destructor TUDUnitGroup.Destroy;
begin
  // the units are freed by the TIdentifierDictionary
  FreeAndNil(Units);
  inherited Destroy;
end;

function TUDUnitGroup.AddUnit(NewUnit: TUDUnit): TUDUnit;
begin
  Result:=NewUnit;
  if AVLFindPointer(Units,NewUnit)<>nil then exit;
  Units.Add(Result);
  Result.Groups.Add(Self);
  if (Dictionary.NoGroup<>Self) then
    Dictionary.NoGroup.RemoveUnit(NewUnit);
  Dictionary.IncreaseChangeStamp;
end;

procedure TUDUnitGroup.RemoveUnit(TheUnit: TUDUnit);
begin
  if AVLFindPointer(Units,TheUnit)=nil then exit;
  AVLRemovePointer(Units,TheUnit);
  AVLRemovePointer(TheUnit.Groups,Self);
  Dictionary.IncreaseChangeStamp;
end;

{ TUDFileItem }

constructor TUDFileItem.Create(const aName, aFilename: string);
begin
  Name:=aName;
  Filename:=aFilename;
end;

{ TUnitDictionary }

procedure TUnitDictionary.RemoveIdentifier(Item: TUDIdentifier);
begin
  AVLRemovePointer(FIdentifiers,Item);
end;

procedure TUnitDictionary.ClearIdentifiersOfUnit(TheUnit: TUDUnit);
var
  Item: TUDIdentifier;
begin
  while TheUnit.FirstIdentifier<>nil do begin
    Item:=TheUnit.FirstIdentifier;
    TheUnit.FirstIdentifier:=Item.NextInUnit;
    Item.NextInUnit:=nil;
    RemoveIdentifier(Item);
    Item.Free;
  end;
  TheUnit.LastIdentifier:=nil;
end;

constructor TUnitDictionary.Create;
begin
  FIdentifiers:=TMTAVLTree.Create(@CompareIDItems);
  FUnitsByName:=TMTAVLTree.Create(@CompareIDItems);
  FUnitsByFilename:=TMTAVLTree.Create(@CompareIDFileItems);
  FUnitGroupsByName:=TMTAVLTree.Create(@CompareIDItems);
  FUnitGroupsByFilename:=TMTAVLTree.Create(@CompareIDFileItems);
  FNoGroup:=AddUnitGroup('');
end;

destructor TUnitDictionary.Destroy;
begin
  Clear(false);
  FreeAndNil(FIdentifiers);
  FreeAndNil(FUnitsByName);
  FreeAndNil(FUnitsByFilename);
  FreeAndNil(FUnitGroupsByName);
  FreeAndNil(FUnitGroupsByFilename);
  inherited Destroy;
end;

procedure TUnitDictionary.Clear(CreateDefaults: boolean);
begin
  FNoGroup:=nil;
  FUnitGroupsByFilename.Clear;
  FUnitGroupsByName.FreeAndClear;
  FUnitsByFilename.Clear;
  FUnitsByName.FreeAndClear;
  FIdentifiers.FreeAndClear;
  if CreateDefaults then
    FNoGroup:=AddUnitGroup('');
end;

procedure TUnitDictionary.ConsistencyCheck;

  procedure e(const Msg: string);
  begin
    raise Exception.Create('ERROR: TUnitDictionary.ConsistencyCheck '+Msg);
  end;

var
  AVLNode: TAVLTreeNode;
  CurUnit: TUDUnit;
  Group: TUDUnitGroup;
  Item: TUDIdentifier;
  SubAVLNode: TAVLTreeNode;
  LastUnit: TUDUnit;
  LastGroup: TUDUnitGroup;
  IdentifiersCount: Integer;
begin
  if NoGroup=nil then
    e('DefaultGroup=nil');

  if UnitGroupsByFilename.Count<>UnitGroupsByName.Count then
    e('UnitGroupsByFilename.Count<>UnitGroupsByName.Count');
  if UnitsByFilename.Count<>UnitsByName.Count then
    e('UnitsByFilename.Count<>UnitsByName.Count');

  UnitGroupsByFilename.ConsistencyCheck;
  UnitGroupsByName.ConsistencyCheck;
  UnitsByName.ConsistencyCheck;
  UnitsByFilename.ConsistencyCheck;
  IdentifiersCount:=0;

  // check UnitsByName
  AVLNode:=UnitsByName.FindLowest;
  LastUnit:=nil;
  while AVLNode<>nil do begin
    CurUnit:=TUDUnit(AVLNode.Data);
    if CurUnit.Name='' then
      e('unit without name');
    if CurUnit.Filename='' then
      e('unit '+CurUnit.Name+' without filename');
    if AVLFindPointer(FUnitsByFilename,CurUnit)=nil then
      e('unit '+CurUnit.Name+' in FUnitsByName not in FUnitsByFilename');
    if CurUnit.Groups.Count=0 then
      e('unit '+CurUnit.Name+' has not group');
    CurUnit.Groups.ConsistencyCheck;
    if (LastUnit<>nil)
    and (CompareFilenames(LastUnit.Filename,CurUnit.Filename)=0) then
      e('unit '+CurUnit.Name+' exists twice: '+CurUnit.Filename);
    SubAVLNode:=CurUnit.Groups.FindLowest;
    LastGroup:=nil;
    while SubAVLNode<>nil do begin
      Group:=TUDUnitGroup(SubAVLNode.Data);
      if AVLFindPointer(Group.Units,CurUnit)=nil then
        e('unit '+CurUnit.Name+' not in group '+Group.Filename);
      if LastGroup=Group then
        e('unit '+CurUnit.Name+' twice in group '+Group.Filename);
      LastGroup:=Group;
      SubAVLNode:=CurUnit.Groups.FindSuccessor(SubAVLNode);
    end;
    Item:=CurUnit.FirstIdentifier;
    while Item<>nil do begin
      if Item.Name='' then
        e('identifier without name');
      if Item.DUnit=nil then
        e('identifier '+Item.Name+' without unit');
      if Item.DUnit<>CurUnit then
        e('identifier '+Item.Name+' not in unit '+CurUnit.Name);
      if FIdentifiers.Find(Item)=nil then
        e('identifier '+Item.Name+' in unit, but not in global tree');
      inc(IdentifiersCount);
      Item:=Item.NextInUnit;
    end;
    LastUnit:=CurUnit;
    AVLNode:=UnitsByName.FindSuccessor(AVLNode);
  end;

  if IdentifiersCount<>FIdentifiers.Count then
    e('IdentifiersCount='+IntToStr(IdentifiersCount)+'<>FIdentifiers.Count='+IntToStr(FIdentifiers.Count));

  // UnitsByFilename
  AVLNode:=UnitsByFilename.FindLowest;
  LastUnit:=nil;
  while AVLNode<>nil do begin
    CurUnit:=TUDUnit(AVLNode.Data);
    if AVLFindPointer(FUnitsByName,CurUnit)=nil then
      e('unit '+CurUnit.Name+' in FUnitsByFilename not in FUnitsByName');
    if (LastUnit<>nil)
    and (CompareFilenames(LastUnit.Filename,CurUnit.Filename)=0) then
      e('unit '+CurUnit.Name+' exists twice: '+CurUnit.Filename);
    LastUnit:=CurUnit;
    AVLNode:=UnitsByFilename.FindSuccessor(AVLNode);
  end;

  // check UnitGroupsByName
  AVLNode:=UnitGroupsByName.FindLowest;
  LastGroup:=nil;
  while AVLNode<>nil do begin
    Group:=TUDUnitGroup(AVLNode.Data);
    if (Group.Name='') and (Group<>NoGroup) then
      e('group without name');
    if (Group.Filename='') and (Group<>NoGroup) then
      e('group '+Group.Name+' without filename');
    if AVLFindPointer(FUnitGroupsByFilename,Group)=nil then
      e('group '+Group.Name+' in FUnitGroupsByName not in FUnitGroupsByFilename');
    Group.Units.ConsistencyCheck;
    if (LastGroup<>nil)
    and (CompareFilenames(LastGroup.Filename,Group.Filename)=0) then
      e('group '+Group.Name+' exists twice: '+Group.Filename);
    SubAVLNode:=Group.Units.FindLowest;
    LastUnit:=nil;
    while SubAVLNode<>nil do begin
      CurUnit:=TUDUnit(SubAVLNode.Data);
      if AVLFindPointer(CurUnit.Groups,Group)=nil then
        e('group '+Group.Name+' has not the unit '+CurUnit.Name);
      if LastUnit=CurUnit then
        e('group '+Group.Name+' has unit twice '+CurUnit.Filename);
      LastUnit:=CurUnit;
      SubAVLNode:=Group.Units.FindSuccessor(SubAVLNode);
    end;
    LastGroup:=Group;
    AVLNode:=UnitGroupsByName.FindSuccessor(AVLNode);
  end;

  // UnitGroupsByFilename
  AVLNode:=UnitGroupsByFilename.FindLowest;
  LastGroup:=nil;
  while AVLNode<>nil do begin
    Group:=TUDUnitGroup(AVLNode.Data);
    if AVLFindPointer(FUnitGroupsByName,Group)=nil then
      e('group '+Group.Name+' in FUnitGroupsByFilename not in FUnitGroupsByName');
    if (LastGroup<>nil)
    and (CompareFilenames(LastGroup.Filename,Group.Filename)=0) then
      e('group '+Group.Name+' exists twice: '+Group.Filename);
    LastGroup:=Group;
    AVLNode:=UnitGroupsByFilename.FindSuccessor(AVLNode);
  end;

  // Identifiers
  AVLNode:=Identifiers.FindLowest;
  while AVLNode<>nil do begin
    Item:=TUDIdentifier(AVLNode.Data);
    if Item.Name='' then
      e('identifier without name');
    if Item.DUnit=nil then
      e('identifier '+Item.Name+' without unit');
    AVLNode:=Identifiers.FindSuccessor(AVLNode);
  end;
  debugln(['TUnitDictionary.ConsistencyCheck GOOD']);
end;

procedure TUnitDictionary.SaveToFile(const Filename: string);
var
  UncompressedMS: TMemoryStream;
  TempFilename: String;
begin
  UncompressedMS:=TMemoryStream.Create;
  try
    SaveToStream(UncompressedMS);
    UncompressedMS.Position:=0;
    // reduce the risk of file corruption due to crashes while saving:
    // save to a temporary file and then rename
    TempFilename:=FileProcs.GetTempFilename(Filename,'unitdictionary');
    UncompressedMS.SaveToFile(TempFilename);
    RenameFileUTF8(TempFilename,Filename);
  finally
    UncompressedMS.Free;
  end;
end;

procedure TUnitDictionary.SaveToStream(aStream: TStream);

  procedure w(const s: string);
  begin
    if s='' then exit;
    aStream.Write(s[1],length(s));
  end;

  function GetBase32(i: integer): string;
  const
    l: shortstring = '0123456789ABCDEFGHIJKLMNOPQRSTUV';
  begin
    Result:='';
    if i=0 then exit('0');
    while i>0 do begin
      Result:=Result+l[(i mod 32)+1];
      i:=i div 32;
    end;
  end;

  { Not used, because gzip is good enough:
  procedure WriteDiff(var Last: string; Cur: string);
  // write n^diff, where n is the base32 number of same bytes of last value
  // and diff the remaining string that differs
  var
    p1: PChar;
    p2: PChar;
    l: PtrUInt;
  begin
    if (Cur<>'') and (Last<>'') then begin
      p1:=PChar(Cur);
      p2:=PChar(Last);
      while (p1^=p2^) and (p1^<>#0) do begin
        inc(p1);
        inc(p2);
      end;
      l:=length(Cur)-(PChar(Cur)-p1);
      w(GetBase32(l));
      w('^');
      if l>0 then
        aStream.Write(p1^,l);
    end else begin
      w('^');
      w(Cur);
    end;
    Last:=Cur;
  end;}

var
  AVLNode: TAVLTreeNode;
  CurUnit: TUDUnit;
  Item: TUDIdentifier;
  Group: TUDUnitGroup;
  SubAVLNode: TAVLTreeNode;
  UnitID: TFilenameToStringTree;
  i: Integer;
  ID: String;
begin
  // write format version
  w(UDFileHeader);
  w(IntToStr(UDFileVersion));
  w(LineEnding);

  UnitID:=TFilenameToStringTree.Create(false);
  try
    // write units
    w('//BeginUnits'+LineEnding);
    AVLNode:=FUnitsByFilename.FindLowest;
    i:=0;
    while AVLNode<>nil do begin
      CurUnit:=TUDUnit(AVLNode.Data);
      inc(i);
      UnitID.Add(CurUnit.Filename,GetBase32(i));
      // write unit number ; usecount ; unit name ; unit file name
      w(UnitID[CurUnit.Filename]);
      w(';');
      w(IntToStr(CurUnit.UseCount));
      w(';');
      w(CurUnit.Name);
      w(';');
      w(CurUnit.Filename);
      w(LineEnding);
      // write identifiers
      Item:=CurUnit.FirstIdentifier;
      while Item<>nil do begin
        if Item.Name<>'' then begin
          w(Item.Name);
          w(LineEnding);
        end;
        Item:=Item.NextInUnit;
      end;
      w(LineEnding); // empty line as end of unit
      AVLNode:=FUnitsByFilename.FindSuccessor(AVLNode);
    end;
    w('//EndUnits'+LineEnding);

    // write groups
    w('//BeginGroups'+LineEnding);
    AVLNode:=FUnitGroupsByFilename.FindLowest;
    while AVLNode<>nil do begin
      Group:=TUDUnitGroup(AVLNode.Data);
      // write group name ; usecount ; group file name
      w(Group.Name);
      w(';');
      w(IntToStr(Group.UseCount));
      w(';');
      w(Group.Filename);
      w(LineEnding);
      // write IDs of units
      SubAVLNode:=Group.Units.FindLowest;
      while SubAVLNode<>nil do begin
        CurUnit:=TUDUnit(SubAVLNode.Data);
        ID:=UnitID[CurUnit.Filename];
        if ID<>'' then begin
          w(UnitID[CurUnit.Filename]);
          w(LineEnding);
        end;
        SubAVLNode:=Group.Units.FindSuccessor(SubAVLNode);
      end;
      w(LineEnding); // empty line as end of group
      AVLNode:=FUnitGroupsByFilename.FindSuccessor(AVLNode);
    end;
    w('//EndGroups'+LineEnding);
  finally
    UnitID.Free;
  end;
end;

procedure TUnitDictionary.LoadFromFile(const Filename: string; KeepData: boolean
  );
var
  UncompressedMS: TMemoryStream;
begin
  UncompressedMS:=TMemoryStream.Create;
  try
    UncompressedMS.LoadFromFile(Filename);
    UncompressedMS.Position:=0;
    LoadFromStream(UncompressedMS,KeepData);
  finally
    UncompressedMS.Free;
  end;
end;

procedure TUnitDictionary.LoadFromStream(aStream: TMemoryStream;
  KeepData: boolean);
var
  Y: integer;
  LineStart: PChar;
  p: PChar;
  EndP: PChar;
  Version: Integer;
  IDToUnit: TStringToPointerTree;

  procedure E(Msg: string; Col: PtrInt = -1);
  var
    s: String;
  begin
    s:='Error in line '+IntToStr(Y);
    if Col=-1 then
      Col:=p-LineStart+1;
    if Col>0 then
      s:=s+', column '+IntToStr(Col);
    s:=s+': '+Msg;
    raise ECTUnitDictionaryLoadError.Create(s);
  end;

  function ReadDecimal: integer;
  var
    s: PChar;
  begin
    Result:=0;
    s:=p;
    while (p<EndP) and (p^ in ['0'..'9']) do begin
      Result:=Result*10+ord(p^)-ord('0');
      inc(p);
    end;
    if s=p then
      e('number expected, but '+dbgstr(p^)+' found.');
  end;

  procedure ReadConstant(const Expected, ErrMsg: string);
  var
    i: Integer;
  begin
    i:=1;
    while (i<=length(Expected)) do begin
      if (p=EndP) or (p^<>Expected[i]) then
        e(ErrMsg);
      inc(p);
      inc(i);
    end;
  end;

  procedure ReadLineEnding;
  var
    c: Char;
  begin
    if (p=EndP) or (not (p^ in [#10,#13])) then
      e('line ending missing');
    c:=p^;
    inc(p);
    if (p<EndP) and (p^ in [#10,#13]) and (c<>p^) then
      inc(p);
    inc(y);
    LineStart:=p;
  end;

  function ReadFileFormat: integer;
  begin
    ReadConstant(UDFileHeader,'invalid file header');
    Result:=ReadDecimal;
    ReadLineEnding;
  end;

  procedure ReadUnits;
  var
    StartP: PChar;
    UnitID, s, CurUnitName, UnitFilename, Identifier: string;
    CurUnit: TUDUnit;
    Item: TUDIdentifier;
    Skip: boolean;
    UseCount: Integer;
  begin
    ReadConstant('//BeginUnits','missing //BeginUnits header');
    ReadLineEnding;

    repeat
      // read unit id
      StartP:=p;
      while (p<EndP) and (p^ in ['0'..'9','A'..'Z']) do inc(p);
      if (StartP=p) or (p^<>';') then
        e('unit id expected, but found "'+dbgstr(p^)+'"');
      SetLength(UnitID,p-StartP);
      Move(StartP^,UnitID[1],length(UnitID));
      inc(p); // skip semicolon

      // read usecount
      UseCount:=0;
      if Version>=2 then begin
        StartP:=p;
        while (p<EndP) and (p^ in ['0'..'9']) do inc(p);
        if (StartP=p) or (p^<>';') then
          e('unit use count expected, but found "'+dbgstr(p^)+'"');
        SetLength(s,p-StartP);
        Move(StartP^,s[1],length(s));
        UseCount:=StrToInt64Def(s,0);
        inc(p); // skip semicolon
      end;

      // read unit name
      StartP:=p;
      while (p<EndP) and (p^ in ['0'..'9','A'..'Z','a'..'z','_','.']) do inc(p);
      if (StartP=p) or (p^<>';') then
        e('unit name expected, but found "'+dbgstr(p^)+'"');
      SetLength(CurUnitName,p-StartP);
      Move(StartP^,CurUnitName[1],length(CurUnitName));
      inc(p); // skip semicolon

      // read file name
      StartP:=p;
      while (p<EndP) and (not (p^ in [#10,#13])) do inc(p);
      if (StartP=p) or (not (p^ in [#10,#13])) then
        e('file name expected, but found "'+dbgstr(p^)+'"');
      SetLength(UnitFilename,p-StartP);
      Move(StartP^,UnitFilename[1],length(UnitFilename));
      ReadLineEnding;

      CurUnit:=FindUnitWithFilename(UnitFilename);
      Skip:=false;
      if CurUnit=nil then begin
        // new unit
        CurUnit:=AddUnit(UnitFilename,CurUnitName);
        CurUnit.UseCount:=UseCount;
      end else
        Skip:=KeepData; // old unit
      IDToUnit[UnitID]:=CurUnit;

      // read identifiers until empty line
      repeat
        StartP:=p;
        while (p<EndP) and (p^ in ['0'..'9','A'..'Z','a'..'z','_']) do inc(p);
        if (not (p^ in [#10,#13])) then
          e('identifier expected, but found "'+dbgstr(p^)+'"');
        if p=StartP then break;
        SetLength(Identifier,p-StartP);
        Move(StartP^,Identifier[1],length(Identifier));
        ReadLineEnding;
        if not Skip then begin
          Item:=TUDIdentifier.Create(Identifier);
          FIdentifiers.Add(Item);
          CurUnit.AddIdentifier(Item);
          //if not CurUnit.HasIdentifier(Item) then RaiseCatchableException('');
        end;
      until false;
      ReadLineEnding;

    until (p=EndP) or (p^='/');

    ReadConstant('//EndUnits','missing //EndUnits footer');
    ReadLineEnding;
  end;

  procedure ReadGroups;
  var
    s, GroupName, GroupFilename, UnitID: string;
    StartP: PChar;
    Group: TUDUnitGroup;
    CurUnit: TUDUnit;
    UseCount: Integer;
  begin
    ReadConstant('//BeginGroups','missing //BeginGroups header');
    ReadLineEnding;

    repeat
      // read group name
      StartP:=p;
      while (p<EndP) and (p^ in ['0'..'9','A'..'Z','a'..'z','_','.']) do inc(p);
      if (p^<>';') then
        e('group name expected, but found "'+dbgstr(p^)+'"');
      SetLength(GroupName,p-StartP);
      if GroupName<>'' then
        Move(StartP^,GroupName[1],length(GroupName));
      inc(p); // skip semicolon

      // read usecount
      UseCount:=0;
      if Version>=2 then begin
        StartP:=p;
        while (p<EndP) and (p^ in ['0'..'9']) do inc(p);
        if (StartP=p) or (p^<>';') then
          e('group use count expected, but found "'+dbgstr(p^)+'"');
        SetLength(s,p-StartP);
        Move(StartP^,s[1],length(s));
        UseCount:=StrToInt64Def(s,0);
        inc(p); // skip semicolon
      end;

      // read file name
      StartP:=p;
      while (p<EndP) and (not (p^ in [#10,#13])) do inc(p);
      if (not (p^ in [#10,#13])) then
        e('file name expected, but found "'+dbgstr(p^)+'"');
      SetLength(GroupFilename,p-StartP);
      if GroupFilename<>'' then
        Move(StartP^,GroupFilename[1],length(GroupFilename));
      ReadLineEnding;

      Group:=FindGroupWithFilename(GroupFilename);
      if Group=nil then
        Group:=AddUnitGroup(GroupFilename,GroupName);
      Group.UseCount:=UseCount;

      // read units of group until empty line
      repeat
        StartP:=p;
        while (p<EndP) and (p^ in ['0'..'9','A'..'Z','a'..'z','_']) do inc(p);
        if (not (p^ in [#10,#13])) then
          e('unit identifier expected, but found "'+dbgstr(p^)+'"');
        if p=StartP then break;
        SetLength(UnitID,p-StartP);
        Move(StartP^,UnitID[1],length(UnitID));
        ReadLineEnding;

        CurUnit:=TUDUnit(IDToUnit[UnitID]);
        if CurUnit<>nil then begin
          Group.AddUnit(CurUnit);
        end else begin
          debugln(['Warning: TUnitDictionary.LoadFromStream.ReadGroups unit id is not defined: ',UnitID]);
        end;
      until false;
      ReadLineEnding;

    until (p=EndP) or (p^='/');

    ReadConstant('//EndGroups','missing //EndGroups footer');
    ReadLineEnding;
  end;

begin
  if not KeepData then
    Clear;
  if aStream.Size<=aStream.Position then
    raise Exception.Create('This is not a UnitDictionary. Header missing.');
  p:=PChar(aStream.Memory);
  EndP:=p+aStream.Size;
  LineStart:=p;
  Y:=1;
  Version:=ReadFileFormat;
  if Version>UDFileVersion then
    E('invalid version '+IntToStr(Version));
  //debugln(['TUnitDictionary.LoadFromStream Version=',Version]);
  IDToUnit:=TStringToPointerTree.Create(true);
  try
    ReadUnits;
    ReadGroups;
  finally
    IDToUnit.Free;
  end;
end;

function TUnitDictionary.Equals(Dictionary: TUnitDictionary): boolean;
var
  Node1, Node2: TAVLTreeNode;
  Group1: TUDUnitGroup;
  Group2: TUDUnitGroup;
  Unit1: TUDUnit;
  Unit2: TUDUnit;
  Item1: TUDIdentifier;
  Item2: TUDIdentifier;
begin
  Result:=false;
  if Dictionary=nil then exit;
  if Dictionary=Self then exit(true);
  if UnitGroupsByFilename.Count<>Dictionary.UnitGroupsByFilename.Count then exit;
  if UnitGroupsByName.Count<>Dictionary.UnitGroupsByName.Count then exit;
  if UnitsByFilename.Count<>Dictionary.UnitsByFilename.Count then exit;
  if UnitsByName.Count<>Dictionary.UnitsByName.Count then exit;
  if Identifiers.Count<>Dictionary.Identifiers.Count then exit;

  Node1:=UnitGroupsByFilename.FindLowest;
  Node2:=Dictionary.UnitGroupsByFilename.FindLowest;
  while Node1<>nil do begin
    Group1:=TUDUnitGroup(Node1.Data);
    Group2:=TUDUnitGroup(Node2.Data);
    if Group1.Name<>Group2.Name then exit;
    if Group1.Filename<>Group2.Filename then exit;
    Node1:=UnitGroupsByFilename.FindSuccessor(Node1);
    Node2:=UnitGroupsByFilename.FindSuccessor(Node2);
  end;

  Node1:=UnitsByFilename.FindLowest;
  Node2:=Dictionary.UnitsByFilename.FindLowest;
  while Node1<>nil do begin
    Unit1:=TUDUnit(Node1.Data);
    Unit2:=TUDUnit(Node2.Data);
    if Unit1.Name<>Unit2.Name then exit;
    if Unit1.Filename<>Unit2.Filename then exit;

    Item1:=Unit1.FirstIdentifier;
    Item2:=Unit2.FirstIdentifier;
    while (Item1<>nil) and (Item2<>nil) do begin
      if Item1.Name<>Item2.Name then begin
        //debugln(['TUnitDictionary.Equals Item1.Name=',Item1.Name,'<>Item2.Name=',Item2.Name]);
        exit;
      end;
      Item1:=Item1.NextInUnit;
      Item2:=Item2.NextInUnit;
    end;
    if (Item1<>nil) then exit;
    if (Item2<>nil) then exit;
    Node1:=UnitGroupsByFilename.FindSuccessor(Node1);
    Node2:=UnitGroupsByFilename.FindSuccessor(Node2);
  end;

  Result:=true
end;

procedure TUnitDictionary.IncreaseChangeStamp;
begin
  CTIncreaseChangeStamp64(FChangeStamp);
end;

function TUnitDictionary.AddUnitGroup(Group: TUDUnitGroup): TUDUnitGroup;
begin
  if Group.Dictionary<>nil then
    raise Exception.Create('TIdentifierDictionary.AddUnitGroup Group.Dictionary<>nil');
  Result:=Group;
  Result.Dictionary:=Self;
  FUnitGroupsByName.Add(Result);
  FUnitGroupsByFilename.Add(Result);
  IncreaseChangeStamp;
end;

function TUnitDictionary.AddUnitGroup(aFilename: string; aName: string
  ): TUDUnitGroup;
begin
  aFilename:=TrimFilename(aFilename);
  if aName='' then aName:=ExtractFileNameOnly(aFilename);
  Result:=FindGroupWithFilename(aFilename);
  if Result<>nil then begin
    // group already exists
    // => improve name
    if (Result.Name<>aName)
    and ((Result.Name=lowercase(Result.Name))
      or (Result.Name=UpperCase(Result.Name)))
    then begin
      // old had the default name => use newer name
      Result.Name:=aName;
      IncreaseChangeStamp;
    end;
  end else begin
    // create new group
    Result:=AddUnitGroup(TUDUnitGroup.Create(aName,aFilename));
  end;
end;

procedure TUnitDictionary.DeleteGroup(Group: TUDUnitGroup;
  DeleteUnitsWithoutGroup: boolean);
var
  Node: TAVLTreeNode;
  CurUnit: TUDUnit;
begin
  if Group=NoGroup then
    raise Exception.Create('The default group can not be deleted');
  // remove units
  Node:=Group.Units.FindLowest;
  while Node<>nil do begin
    CurUnit:=TUDUnit(Node.Data);
    AVLRemovePointer(CurUnit.Groups,Group);
    if CurUnit.Groups.Count=0 then begin
      if DeleteUnitsWithoutGroup then
        DeleteUnit(CurUnit,false)
      else
        NoGroup.AddUnit(CurUnit);
    end;
    Node:=Group.Units.FindSuccessor(Node);
  end;
  Group.Units.Clear;
  // remove group from trees
  AVLRemovePointer(UnitGroupsByFilename,Group);
  AVLRemovePointer(UnitGroupsByName,Group);
  // free group
  Group.Free;
  IncreaseChangeStamp;
end;

function TUnitDictionary.FindGroupWithFilename(const aFilename: string
  ): TUDUnitGroup;
var
  AVLNode: TAVLTreeNode;
begin
  AVLNode:=FUnitGroupsByFilename.FindKey(Pointer(aFilename),@CompareFileNameWithIDFileItem);
  if AVLNode<>nil then
    Result:=TUDUnitGroup(AVLNode.Data)
  else
    Result:=nil;
end;

function TUnitDictionary.AddUnit(const aFilename: string; aName: string;
  Group: TUDUnitGroup): TUDUnit;
begin
  if Group=nil then
    Group:=NoGroup;
  Result:=FindUnitWithFilename(aFilename);
  if Result=nil then begin
    Result:=TUDUnit.Create(aName,aFilename);
    FUnitsByFilename.Add(Result);
    FUnitsByName.Add(Result);
    IncreaseChangeStamp;
  end;
  Group.AddUnit(Result);
end;

procedure TUnitDictionary.DeleteUnit(TheUnit: TUDUnit;
  DeleteEmptyGroups: boolean);
var
  Node: TAVLTreeNode;
  Group: TUDUnitGroup;
begin
  Node:=TheUnit.Groups.FindLowest;
  // remove unit from groups
  while Node<>nil do begin
    Group:=TUDUnitGroup(Node.Data);
    Node:=TheUnit.Groups.FindSuccessor(Node);
    AVLRemovePointer(Group.Units,TheUnit);
    if DeleteEmptyGroups and (Group.Units.Count=0)
    and (Group<>NoGroup) then
      DeleteGroup(Group,false);
  end;
  TheUnit.Groups.Clear;
  // free identifiers
  ClearIdentifiersOfUnit(TheUnit);
  // remove unit from dictionary
  AVLRemovePointer(UnitsByFilename,TheUnit);
  AVLRemovePointer(UnitsByName,TheUnit);
  // free unit
  TheUnit.Free;
  IncreaseChangeStamp;
end;

function TUnitDictionary.ParseUnit(UnitFilename: string; Group: TUDUnitGroup): TUDUnit;
var
  Code: TCodeBuffer;
begin
  Result:=nil;
  UnitFilename:=TrimFilename(UnitFilename);
  if UnitFilename='' then exit;
  Code:=CodeToolBoss.LoadFile(UnitFilename,true,false);
  if Code=nil then
    raise Exception.Create('unable to load file '+UnitFilename);
  Result:=ParseUnit(Code,Group);
end;

function TUnitDictionary.ParseUnit(Code: TCodeBuffer; Group: TUDUnitGroup): TUDUnit;
begin
  Result:=nil;
  if Code=nil then exit;
  if not CodeToolBoss.InitCurCodeTool(Code) then
    raise Exception.Create('unable to init unit parser for file '+Code.Filename);
  Result:=ParseUnit(CodeToolBoss.CurCodeTool,Group);
end;

function TUnitDictionary.ParseUnit(Tool: TCodeTool; Group: TUDUnitGroup): TUDUnit;
var
  SrcTree: TAVLTree;
  AVLNode: TAVLTreeNode;
  SrcItem: PInterfaceIdentCacheEntry;
  UnitFilename: String;
  NiceName: String;
  SrcName: String;
  NewItem, PrevItem, CurItem, NextItem: TUDIdentifier;
  Changed: Boolean;
begin
  Result:=nil;
  if Tool=nil then exit;
  if Group=nil then
    Group:=NoGroup;
  // parse unit
  Tool.BuildInterfaceIdentifierCache(true);

  // get unit name from source
  UnitFilename:=Tool.MainFilename;
  NiceName:=ExtractFileNameOnly(UnitFilename);
  if (LowerCase(NiceName)=NiceName)
  or (UpperCase(NiceName)=NiceName) then begin
    SrcName:=Tool.GetSourceName(false);
    if CompareDottedIdentifiers(PChar(SrcName),PChar(NiceName))=0 then
      NiceName:=SrcName;
  end;

  // find/create unit
  Result:=FindUnitWithFilename(UnitFilename);
  if Result<>nil then begin
    // old unit
    if (Group<>NoGroup) then begin
      Group.AddUnit(Result);
    end;
    // update name
    if Result.Name<>NiceName then
      Result.Name:=NiceName;
    if Result.ToolStamp=Tool.TreeChangeStep then begin
      // nothing changed since last parsing
      exit;
    end;
    Result.ToolStamp:=Tool.TreeChangeStep;
  end else begin
    // new unit
    Result:=AddUnit(UnitFilename,NiceName,Group);
  end;

  // update list of identifiers
  Changed:=false;
  SrcTree:=Tool.InterfaceIdentifierCache.Items;
  if SrcTree<>nil then begin
    AVLNode:=SrcTree.FindLowest;
    PrevItem:=nil;
    CurItem:=Result.FirstIdentifier;
    //debugln(['TUnitDictionary.ParseUnit ',SrcTree.Count]);
    while AVLNode<>nil do begin
      SrcItem:=PInterfaceIdentCacheEntry(AVLNode.Data);
      //debugln(['TUnitDictionary.ParseUnit ',GetIdentifier(SrcItem^.Identifier)]);
      if (SrcItem^.Node<>nil) and (SrcItem^.Identifier<>nil) then begin
        while (CurItem<>nil)
        and (CompareDottedIdentifiers(PChar(Pointer(CurItem.Name)),SrcItem^.Identifier)<0)
        do begin
          // delete old item
          //debugln(['TUnitDictionary.ParseUnit delete old item '+CurItem.Name+' in '+Result.Name]);
          Changed:=true;
          NextItem:=CurItem.NextInUnit;
          if PrevItem<>nil then
            PrevItem.NextInUnit:=NextItem
          else
            Result.FirstIdentifier:=NextItem;
          if Result.LastIdentifier=CurItem then
            Result.LastIdentifier:=PrevItem;
          AVLRemovePointer(Identifiers,CurItem);
          CurItem.Free;
          CurItem:=NextItem;
        end;
        if (CurItem=nil)
        or (CompareDottedIdentifiers(PChar(Pointer(CurItem.Name)),SrcItem^.Identifier)>0)
        then begin
          // new item
          //debugln(['TUnitDictionary.ParseUnit inserting new item '+GetIdentifier(SrcItem^.Identifier)+' in '+Result.Name]);
          Changed:=true;
          NewItem:=TUDIdentifier.Create(SrcItem^.Identifier);
          NewItem.DUnit:=Result;
          NewItem.NextInUnit:=CurItem;
          if PrevItem<>nil then
            PrevItem.NextInUnit:=NewItem
          else
            Result.FirstIdentifier:=NewItem;
          if CurItem=nil then begin
            // at end of list
            PrevItem:=NewItem;
            Result.LastIdentifier:=NewItem;
          end;
          FIdentifiers.Add(NewItem);
        end else begin
          // already in list, skip
          //debugln(['TUnitDictionary.ParseUnit keep '+CurItem.Name]);
          PrevItem:=CurItem;
          CurItem:=CurItem.NextInUnit;
        end;
      end;
      AVLNode:=SrcTree.FindSuccessor(AVLNode);
    end;
  end;

  if Changed then
    IncreaseChangeStamp;
end;

function TUnitDictionary.FindUnitWithFilename(const aFilename: string): TUDUnit;
var
  AVLNode: TAVLTreeNode;
begin
  AVLNode:=FUnitsByFilename.FindKey(Pointer(aFilename),@CompareFileNameWithIDFileItem);
  if AVLNode<>nil then
    Result:=TUDUnit(AVLNode.Data)
  else
    Result:=nil;
end;

procedure TUnitDictionary.IncreaseUnitUseCount(TheUnit: TUDUnit);
var
  Cnt: Int64;
begin
  Cnt:=TheUnit.UseCount;
  if Cnt<High(Cnt) then inc(Cnt);
  if TheUnit.UseCount=Cnt then exit;
  TheUnit.UseCount:=Cnt;
  IncreaseChangeStamp;
end;

end.