File: ctunitgraph.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 (700 lines) | stat: -rw-r--r-- 20,764 bytes parent folder | download | duplicates (5)
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
{
 ***************************************************************************
 *                                                                         *
 *   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:
    Functions and classes to build dependency graphs for pascal units.
}
unit CTUnitGraph;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Laz_AVL_Tree,
  // LazUtils
  LazFileUtils, LazStringUtils,
  // Codetools
  FileProcs, FindDeclarationTool, CodeBeautifier, CodeCache, StdCodeTools,
  DirectoryCacher, LinkScanner, CustomCodeTool, CodeTree, CodeToolsStructs;

type

  { TFindIdentifierReferenceCache }

  TFindIdentifierReferenceCache = class
  public
    IdentifierCode: TCodeBuffer;
    X, Y: integer;

    SourcesChangeStep: int64;
    FilesChangeStep: int64;
    InitValuesChangeStep: integer;
    NewTool: TFindDeclarationTool;
    NewNode: TCodeTreeNode;
    NewPos: TCodeXYPosition;
    IsPrivate: boolean;
    procedure Clear;
  end;

type
  TUGUnitFlag = (
    ugufReached,
    ugufLoadError,
    ugufIsIncludeFile,
    ugufHasSyntaxErrors
    );
  TUGUnitFlags = set of TUGUnitFlag;

  { TUGUnit }

  TUGUnit = class
  public
    Flags: TUGUnitFlags;
    TheUnitName: string;
    Filename: string;
    Code: TCodeBuffer;
    Tool: TStandardCodeTool;
    UsesUnits: TFPList; // list of TUGUses, can be nil
    UsedByUnits: TFPList; // list of TUGUses, can be nil
    constructor Create(const aFilename: string);
    destructor Destroy; override;
    procedure Clear;
    function IndexOfUses(const aFilename: string): integer; // slow linear search
  end;
  TUGUnitClass = class of TUGUnit;

  { TUGUses }

  TUGUses = class
  public
    Owner: TUGUnit;
    UsesUnit: TUGUnit;
    InImplementation: boolean;
    constructor Create(TheOwner, TheUses: TUGUnit);
    destructor Destroy; override;
  end;
  TUGUsesClass = class of TUGUses;

  { TUsesGraph }

  TUsesGraph = class
  private
    FFiles: TAVLTree; // tree of TUGUnit sorted for Filename
    FIgnoreFiles: TAVLTree; // tree of TUGUnit sorted for Filename
    FQueuedFiles: TAVLTree; // tree of TUGUnit sorted for Filename
    FTargetAll: boolean;
    FTargetFiles: TAVLTree; // tree of TUGUnit sorted for Filename
    FTargetDirsValid: boolean;
    FTargetDirs: string;
    FTargetInFPCSrc: boolean;
    FUnitClass: TUGUnitClass;
    FUsesClass: TUGUsesClass;
  public
    DirectoryCachePool: TCTDirectoryCachePool;
    OnGetCodeToolForBuffer: TOnGetCodeToolForBuffer;
    OnLoadFile: TOnLoadCTFile;

    constructor Create;
    destructor Destroy; override;
    procedure Clear;
    procedure ConsistencyCheck;
    function GetUnit(const ExpFilename: string; CreateIfNotExists: boolean): TUGUnit;
    function FindUnit(const AnUnitName: string): TUGUnit; // slow

    procedure AddStartUnit(ExpFilename: string);
    procedure AddTargetUnit(ExpFilename: string);
    procedure AddIgnoreUnit(ExpFilename: string);
    procedure AddSystemUnitAsTarget;
    function Parse(IgnoreErrors: boolean; out Completed: boolean;
                   StopAfterMs: integer = -1): boolean;
    function GetUnitsTreeUsingTargets: TAVLTree; // tree of TUGUnit sorted for filename
    function GetCodeTreeUsingTargets: TAVLTree; // tree of TCodeBuffer sorted for filename
    function UnitCanFindTarget(ExpFilename: string): boolean;
    function IsTargetDir(ExpDir: string): boolean;

    function FindShortestPath(StartUnit, EndUnit: TUGUnit): TFPList; // list of TUGUnit, nil if no path exists
    function InsertMissingLinks(UGUnitList: TFPList): boolean;

    property FilesTree: TAVLTree read FFiles; // tree of TUGUnit sorted for Filename (all parsed)
    property IgnoreFilesTree: TAVLTree read FIgnoreFiles; // tree of TUGUnit sorted for Filename
    property QueuedFilesTree: TAVLTree read FQueuedFiles; // tree of TUGUnit sorted for Filename
    property TargetFilesTree: TAVLTree read FTargetFiles; // tree of TUGUnit sorted for Filename
    property TargetAll: boolean read FTargetAll write FTargetAll;

    property UnitClass: TUGUnitClass read FUnitClass write FUnitClass;
    property UsesClass: TUGUsesClass read FUsesClass write FUsesClass;
  end;

function CompareUGUnitFilenames(UGUnit1, UGUnit2: Pointer): integer;
function CompareFilenameAndUGUnit(FileAnsistring, UGUnit: Pointer): integer;

implementation

function CompareUGUnitFilenames(UGUnit1, UGUnit2: Pointer): integer;
var
  Unit1: TUGUnit absolute UGUnit1;
  Unit2: TUGUnit absolute UGUnit2;
begin
  Result:=CompareFilenames(Unit1.Filename,Unit2.Filename);
end;

function CompareFilenameAndUGUnit(FileAnsistring, UGUnit: Pointer): integer;
var
  AnUnit: TUGUnit absolute UGUnit;
  Filename: String;
begin
  Filename:=AnsiString(FileAnsistring);
  Result:=CompareFilenames(Filename,AnUnit.Filename);
end;

{ TFindIdentifierReferenceCache }

procedure TFindIdentifierReferenceCache.Clear;
begin
  SourcesChangeStep:=CTInvalidChangeStamp64;
  FilesChangeStep:=CTInvalidChangeStamp64;
  InitValuesChangeStep:=CTInvalidChangeStamp;
  NewTool:=nil;
  NewNode:=nil;
  NewPos:=CleanCodeXYPosition;
  IsPrivate:=false;
end;

{ TUGUses }

constructor TUGUses.Create(TheOwner, TheUses: TUGUnit);
begin
  Owner:=TheOwner;
  UsesUnit:=TheUses;
end;

destructor TUGUses.Destroy;
begin
  if Owner<>nil then begin
    Owner.UsesUnits.Remove(Self);
    Owner:=nil;
  end;
  if UsesUnit<>nil then begin
    UsesUnit.UsedByUnits.Remove(Self);
    UsesUnit:=nil;
  end;
  inherited Destroy;
end;

{ TUGUnit }

constructor TUGUnit.Create(const aFilename: string);
begin
  Filename:=aFilename;
  TheUnitName:=ExtractFileNameOnly(Filename);
end;

destructor TUGUnit.Destroy;
begin
  Clear;
  FreeAndNil(UsesUnits);
  FreeAndNil(UsedByUnits);
  inherited Destroy;
end;

procedure TUGUnit.Clear;

  procedure FreeUsesList(var List: TFPList);
  begin
    if List=nil then exit;
    while List.Count>0 do TObject(List[0]).Free;
    FreeAndNil(List);
  end;

begin
  FreeUsesList(UsesUnits);
  FreeUsesList(UsedByUnits);
  Flags:=Flags-[ugufHasSyntaxErrors,ugufReached];
end;

function TUGUnit.IndexOfUses(const aFilename: string): integer;
begin
  if UsesUnits=nil then exit(-1);
  Result:=UsesUnits.Count-1;
  while (Result>=0)
  and (CompareFilenames(aFilename,TUGUses(UsesUnits[Result]).UsesUnit.Filename)<>0) do
    dec(Result);
end;

{ TUsesGraph }

constructor TUsesGraph.Create;
begin
  FUnitClass:=TUGUnit;
  FUsesClass:=TUGUses;
  FFiles:=TAVLTree.Create(@CompareUGUnitFilenames);
  FIgnoreFiles:=TAVLTree.Create(@CompareUGUnitFilenames);
  FQueuedFiles:=TAVLTree.Create(@CompareUGUnitFilenames);
  FTargetFiles:=TAVLTree.Create(@CompareUGUnitFilenames);
end;

destructor TUsesGraph.Destroy;
begin
  Clear;
  FreeAndNil(FIgnoreFiles);
  FreeAndNil(FQueuedFiles);
  FreeAndNil(FTargetFiles);
  FreeAndNil(FFiles);
  inherited Destroy;
end;

procedure TUsesGraph.Clear;
begin
  FQueuedFiles.Clear; // all files of StartFiles are in Files too
  FTargetFiles.Clear; // all files of TargetFiles are in Files too
  FFiles.FreeAndClear;
end;

procedure TUsesGraph.ConsistencyCheck;
var
  AVLNode: TAVLTreeNode;
  AnUnit: TUGUnit;
begin
  FFiles.ConsistencyCheck;
  FQueuedFiles.ConsistencyCheck;

  AVLNode:=FQueuedFiles.FindLowest;
  while AVLNode<>nil do begin
    AnUnit:=TUGUnit(AVLNode.Data);
    if AnUnit.Filename='' then
      raise Exception.Create('AnUnit without filename');
    if FFiles.FindKey(PChar(AnUnit.Filename),@CompareFilenameAndUGUnit)=nil then
      raise Exception.Create('startfile not in files: '+AnUnit.Filename);
    AVLNode:=FQueuedFiles.FindSuccessor(AVLNode);
  end;
end;

function TUsesGraph.GetUnit(const ExpFilename: string;
  CreateIfNotExists: boolean): TUGUnit;
var
  AVLNode: TAVLTreeNode;
begin
  if ExpFilename='' then begin
    Result:=nil;
    if CreateIfNotExists then
      raise Exception.Create('TUsesGraph.GetUnit missing filename');
    exit;
  end;
  AVLNode:=FFiles.FindKey(PChar(ExpFilename),@CompareFilenameAndUGUnit);
  if AVLNode<>nil then begin
    Result:=TUGUnit(AVLNode.Data);
  end else if CreateIfNotExists then begin
    Result:=UnitClass.Create(ExpFilename);
    FFiles.Add(Result);
  end else
    Result:=nil;
end;

function TUsesGraph.FindUnit(const AnUnitName: string): TUGUnit;
var
  AVLNode: TAVLTreeNode;
begin
  AVLNode:=FFiles.FindLowest;
  while AVLNode<>nil do begin
    Result:=TUGUnit(AVLNode.Data);
    if CompareText(ExtractFileNameOnly(Result.Filename),AnUnitName)=0 then
      exit;
    AVLNode:=FFiles.FindSuccessor(AVLNode);
  end;
end;

procedure TUsesGraph.AddStartUnit(ExpFilename: string);
var
  NewUnit: TUGUnit;
begin
  if ExpFilename='' then exit;
  if FQueuedFiles.FindKey(PChar(ExpFilename),@CompareFilenameAndUGUnit)<>nil then
    exit; // already a start file
  NewUnit:=GetUnit(ExpFilename,true);
  if ugufReached in NewUnit.Flags then exit; // already parsed
  // add to FFiles and FQueuedFiles
  //debugln(['TUsesGraph.AddStartUnit ',ExpFilename]);
  FQueuedFiles.Add(NewUnit);
end;

procedure TUsesGraph.AddTargetUnit(ExpFilename: string);
var
  NewUnit: TUGUnit;
begin
  if ExpFilename='' then exit;
  if FTargetFiles.FindKey(PChar(ExpFilename),@CompareFilenameAndUGUnit)<>nil then
    exit; // already a start file
  // add to FFiles and FTargetFiles
  //debugln(['TUsesGraph.AddTargetUnit ',ExpFilename]);
  NewUnit:=GetUnit(ExpFilename,true);
  if FTargetFiles.Find(NewUnit)=nil then
    FTargetFiles.Add(NewUnit);
  FTargetDirsValid:=false;
end;

procedure TUsesGraph.AddIgnoreUnit(ExpFilename: string);
var
  NewUnit: TUGUnit;
begin
  NewUnit:=GetUnit(ExpFilename,true);
  if FIgnoreFiles.Find(NewUnit)=nil then
    FIgnoreFiles.Add(NewUnit);
end;

procedure TUsesGraph.AddSystemUnitAsTarget;
begin
  AddTargetUnit(DirectoryCachePool.FindUnitInUnitSet('','system'));
end;

function TUsesGraph.Parse(IgnoreErrors: boolean; out Completed: boolean;
  StopAfterMs: integer): boolean;

  procedure AddUses(CurUnit: TUGUnit; UsedFiles: TStrings;
    InImplementation: boolean);
  var
    i: Integer;
    Filename: string;
    NewUnit: TUGUnit;
    NewUses: TUGUses;
  begin
    if UsedFiles=nil then exit;
    for i:=0 to UsedFiles.Count-1 do begin
      Filename:=UsedFiles[i];
      if not FilenameIsPascalUnit(Filename) then continue;
      // check if already used
      if CurUnit.IndexOfUses(Filename)>=0 then continue;
      if not UnitCanFindTarget(Filename) then continue;
      // add connection
      NewUnit:=GetUnit(Filename,true);
      if CurUnit.UsesUnits=nil then
        CurUnit.UsesUnits:=TFPList.Create;
      NewUses:=UsesClass.Create(CurUnit,NewUnit);
      NewUses.InImplementation:=InImplementation;
      CurUnit.UsesUnits.Add(NewUses);
      if NewUnit.UsedByUnits=nil then
        NewUnit.UsedByUnits:=TFPList.Create;
      NewUnit.UsedByUnits.Add(NewUses);
      // put new file on queue
      AddStartUnit(Filename);
    end;
  end;

  function ParseUnit(CurUnit: TUGUnit): boolean;
  // returns true to continue
  var
    Abort: boolean;
    MainUsesSection: TStrings;
    ImplementationUsesSection: TStrings;
  begin
    Result:=false;
    //debugln(['ParseUnit ',CurUnit.Filename,' ',Pos('tcfiler',CurUnit.Filename)]);
    Include(CurUnit.Flags,ugufLoadError);
    // load file
    Abort:=false;
    OnLoadFile(Self,CurUnit.Filename,CurUnit.Code,Abort);
    if Abort then exit;
    if CurUnit.Code=nil then begin
      debugln(['TUsesGraph.Parse failed loading file ',CurUnit.Filename]);
      Result:=IgnoreErrors;
      exit;
    end;
    try
      MainUsesSection:=nil;
      ImplementationUsesSection:=nil;
      try
        // create tool
        CurUnit.Tool:=OnGetCodeToolForBuffer(Self,CurUnit.Code,true) as TStandardCodeTool;
        if CurUnit.Tool=nil then begin
          debugln(['TUsesGraph.Parse failed getting tool for file ',CurUnit.Code.Filename]);
          Result:=IgnoreErrors;
          exit;
        end;
        // check if include file
        if CompareFilenames(CurUnit.Tool.MainFilename,CurUnit.Code.Filename)<>0 then
        begin
          Include(CurUnit.Flags,ugufIsIncludeFile);
          exit(true);
        end;
        Exclude(CurUnit.Flags,ugufLoadError);
        // parse both uses sections
        Include(CurUnit.Flags,ugufHasSyntaxErrors);
        CurUnit.Tool.BuildTree(lsrImplementationUsesSectionEnd);
        Exclude(CurUnit.Flags,ugufHasSyntaxErrors);
        // locate used units
        if not CurUnit.Tool.FindUsedUnitFiles(MainUsesSection,
                                              ImplementationUsesSection)
        then begin
          Result:=IgnoreErrors;
          exit;
        end;
        AddUses(CurUnit,MainUsesSection,false);
        AddUses(CurUnit,ImplementationUsesSection,true);
        Result:=true;
      finally
        MainUsesSection.Free;
        ImplementationUsesSection.Free;
      end;
    except
      on E: ECodeToolError do begin
        if not IgnoreErrors then raise;
      end;
      on E: ELinkScannerError do begin
        if not IgnoreErrors then raise;
      end;
    end;
  end;

var
  StartTime: TDateTime;
  AVLNode: TAVLTreeNode;
  CurUnit: TUGUnit;
begin
  Result:=false;
  Completed:=false;
  if StopAfterMs>=0 then
    StartTime:=Now
  else
    StartTime:=0;
  while FQueuedFiles.Count>0 do begin
    AVLNode:=FQueuedFiles.FindLowest;
    CurUnit:=TUGUnit(AVLNode.Data);
    FQueuedFiles.Delete(AVLNode);
    Include(CurUnit.Flags,ugufReached);
    if FIgnoreFiles.Find(CurUnit)<>nil then continue;
    //debugln(['TUsesGraph.Parse Unit=',CurUnit.Filename,' UnitCanFindTarget=',UnitCanFindTarget(CurUnit.Filename)]);
    if UnitCanFindTarget(CurUnit.Filename) then begin
      ParseUnit(CurUnit);
    end;

    if (StopAfterMs>=0) and (Abs(Now-StartTime)*86400000>=StopAfterMs) then
      exit(true);
  end;

  Completed:=true;
  Result:=true;
end;

function TUsesGraph.GetUnitsTreeUsingTargets: TAVLTree;

  procedure Add(Units: TAVLTree; NewUnit: TUGUnit);
  var
    i: Integer;
    CurUses: TUGUses;
  begin
    if NewUnit=nil then exit;
    if not (ugufReached in NewUnit.Flags) then exit; // this unit was not reached
    if ugufIsIncludeFile in NewUnit.Flags then exit;
    if Units.Find(NewUnit)<>nil then exit; // already added
    Units.Add(NewUnit);
    if NewUnit.UsedByUnits=nil then exit;
    for i:=0 to NewUnit.UsedByUnits.Count-1 do begin
      CurUses:=TUGUses(NewUnit.UsedByUnits[i]);
      Add(Units,CurUses.Owner);
    end;
  end;

var
  AVLNode: TAVLTreeNode;
begin
  Result:=TAVLTree.Create(@CompareUGUnitFilenames);
  AVLNode:=FTargetFiles.FindLowest;
  while AVLNode<>nil do begin
    Add(Result,TUGUnit(AVLNode.Data));
    AVLNode:=FTargetFiles.FindSuccessor(AVLNode);
  end;
end;

function TUsesGraph.GetCodeTreeUsingTargets: TAVLTree;
var
  Units: TAVLTree;
  AVLNode: TAVLTreeNode;
  CurUnit: TUGUnit;
begin
  Result:=TAVLTree.Create(@CompareCodeBuffers);
  Units:=GetUnitsTreeUsingTargets;
  try
    AVLNode:=Units.FindLowest;
    while AVLNode<>nil do begin
      CurUnit:=TUGUnit(AVLNode.Data);
      if not (ugufIsIncludeFile in CurUnit.Flags)
      and (Result.Find(CurUnit.Code)=nil) then
        Result.Add(CurUnit.Code);
      AVLNode:=Units.FindSuccessor(AVLNode);
    end;
  finally
    Units.Free;
  end;
end;

function TUsesGraph.UnitCanFindTarget(ExpFilename: string): boolean;
// returns true if ExpFilename can find one of the targets via the search paths
var
  BaseDir: String;
  SrcPath: String;
  p: integer;
  ReachableDir: String;
begin
  Result:=true;
  if FTargetInFPCSrc or TargetAll then exit; // standard units can always be found

  BaseDir:=ExtractFilePath(ExpFilename);
  if IsTargetDir(BaseDir) then exit;

  // check complete search path, including SrcPath, UnitPath
  // and resolved compiled unit paths
  SrcPath:=DirectoryCachePool.GetString(BaseDir,ctdcsCompleteSrcPath);
  p:=1;
  repeat
    ReachableDir:=GetNextDelimitedItem(SrcPath,';',p);
    if ReachableDir<>'' then begin
      if not FilenameIsAbsolute(ReachableDir) then
        ReachableDir:=BaseDir+ReachableDir;
      if IsTargetDir(ReachableDir) then exit;
    end;
  until p>length(SrcPath);

  Result:=false;
end;

function TUsesGraph.IsTargetDir(ExpDir: string): boolean;
var
  AVLNode: TAVLTreeNode;
  CurUnit: TUGUnit;
  Dir: String;
begin
  if FTargetFiles.Count=0 then exit(TargetAll);

  if not FTargetDirsValid then begin
    FTargetDirsValid:=true;
    FTargetInFPCSrc:=TargetAll;
    // build list of target directories for quick lookup
    AVLNode:=FTargetFiles.FindLowest;
    while AVLNode<>nil do begin
      CurUnit:=TUGUnit(AVLNode.Data);
      Dir:=ExtractFilePath(CurUnit.Filename);
      if FilenameIsAbsolute(Dir)
      and (CompareFilenames(DirectoryCachePool.FindUnitInUnitSet(Dir,CurUnit.TheUnitName),
             CurUnit.Filename)=0)
      then begin
        // this is a standard unit (e.g. in FPC sources)
        // they are not reachable via search paths, but via the UnitSet
        FTargetInFPCSrc:=true;
      end else if Dir='' then begin
        // in virtual directory
        if (FTargetDirs='') or (FTargetDirs[1]<>';') then
          FTargetDirs:=';'+FTargetDirs;
      end else if FindPathInSearchPath(Dir,FTargetDirs)<1 then begin
        // normal source directory
        if FTargetDirs='' then
          FTargetDirs:=Dir
        else
          FTargetDirs:=FTargetDirs+';'+Dir;
      end;
      AVLNode:=FTargetFiles.FindSuccessor(AVLNode);
    end;
  end;

  Result:=true;
  if TargetAll then exit;
  if (ExpDir='') and (FTargetDirs[1]=';') then
    exit; // virtual directory
  Result:=FindPathInSearchPath(ExpDir,FTargetDirs)>0;
end;

function TUsesGraph.FindShortestPath(StartUnit, EndUnit: TUGUnit): TFPList;
// broad search first
var
  Queue: TFPList;
  NodeToPrevNode: TPointerToPointerTree;
  CurUnit: TUGUnit;
  i: Integer;
  CurUses: TUGUses;
  UsesUnit: TUGUnit;
  PrevUnit: TUGUnit;
begin
  Result:=nil;
  if (StartUnit=nil) or (EndUnit=nil) then exit;
  Queue:=TFPList.Create;
  NodeToPrevNode:=TPointerToPointerTree.Create;
  try
    Queue.Add(EndUnit);
    NodeToPrevNode[EndUnit]:=EndUnit; // set end marker
    while Queue.Count>0 do begin
      CurUnit:=TUGUnit(Queue[0]);
      Queue.Delete(0);
      if CurUnit.UsedByUnits=nil then continue;
      for i:=0 to CurUnit.UsedByUnits.Count-1 do begin
        CurUses:=TUGUses(CurUnit.UsedByUnits[i]);
        if CurUses.InImplementation then continue;
        UsesUnit:=CurUses.Owner;
        if NodeToPrevNode.Contains(UsesUnit) then
          continue; // already visited
        NodeToPrevNode[UsesUnit]:=CurUnit;
        if UsesUnit=StartUnit then begin
          // found StartUnit
          // => create list from StartUnit to EndUnit
          Result:=TFPList.Create;
          CurUnit:=StartUnit;
          repeat
            Result.Add(CurUnit);
            PrevUnit:=TUGUnit(NodeToPrevNode[CurUnit]);
            if PrevUnit=CurUnit then exit; // end marker found
            CurUnit:=PrevUnit;
          until false;
          exit;
        end;
        Queue.Add(UsesUnit);
      end;
    end;
  finally
    NodeToPrevNode.Free;
    Queue.Free;
  end;
end;

function TUsesGraph.InsertMissingLinks(UGUnitList: TFPList): boolean;
var
  i,j: Integer;
  StartUnit: TUGUnit;
  EndUnit: TUGUnit;
  CurList: TFPList;
begin
  Result:=true;
  for i:=UGUnitList.Count-2 downto 0 do begin
    StartUnit:=TUGUnit(UGUnitList[i]);
    EndUnit:=TUGUnit(UGUnitList[i+1]);
    CurList:=FindShortestPath(StartUnit,EndUnit);
    if (CurList=nil) then begin
      Result:=false;
      continue;
    end;
    if CurList.Count>2 then begin
      for j:=1 to CurList.Count-2 do
        UGUnitList.Insert(i+j,CurList[j]);
    end;
    CurList.Free;
  end;
end;

end.