File: compiler.pp

package info (click to toggle)
lazarus 2.0.10%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 219,188 kB
  • sloc: pascal: 1,867,962; xml: 265,716; cpp: 56,595; sh: 3,005; java: 609; makefile: 568; perl: 297; sql: 222; ansic: 137
file content (1469 lines) | stat: -rw-r--r-- 46,584 bytes parent folder | download
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
{
 /***************************************************************************
                        compiler.pp  -  Lazarus IDE unit
                        -------------------------------------
               TCompiler is responsible for configuration and running
               the Free Pascal Compiler.


                   Initial Revision  : Sun Mar 28 23:15:32 CST 1999


 ***************************************************************************/

 ***************************************************************************
 *                                                                         *
 *   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.   *
 *                                                                         *
 ***************************************************************************
}
unit Compiler;

{$mode objfpc}
{$H+}

interface

uses
  Classes, SysUtils, contnrs, strutils,
  // LazUtils
  LazUTF8, LazFileUtils, LazUtilities, LazLoggerBase,
  // LCL
  Forms, Controls,
  // Codetools
  DefineTemplates, LinkScanner, CodeToolManager, TransferMacros,
  // IdeIntf
  IDEExternToolIntf, IDEMsgIntf, LazIDEIntf,
  // IDE
  IDECmdLine, LazarusIDEStrConsts, CompilerOptions, Project, EnvironmentOpts;

type
  TOnCmdLineCreate = procedure(var CmdLine: string; var Abort:boolean) of object;

  { TCompiler }

  TCompiler = class(TObject)
  private
    FOnCmdLineCreate : TOnCmdLineCreate;
  public
    constructor Create;
    destructor Destroy; override;
    function Compile(AProject: TProject;
                     const WorkingDir, CompilerFilename, CompilerParams: string;
                     BuildAll, SkipLinking, SkipAssembler, CurrentDirectoryIsTestDir: boolean;
                     const aCompileHint: string): TModalResult;
    procedure WriteError(const Msg: string);
  end;

  // Following classes are for compiler options parsed from "fpc -h" and "fpc -i".

  TCompilerOptEditKind = (
    oeGroup,      // A header for a group
    oeSet,        // A header for a set
    oeSetElem,    // One char element of a set, use CheckBox
    oeSetNumber,  // Number element of a set, use Edit
    oeBoolean,    // True/False, typically use CheckBox
    oeText,       // Textual value
    oeNumber,     // Numeric value
    oeList        // Pre-defined list of choices
  );

  TCompilerOptGroup = class;

  { TCompilerOpt }

  TCompilerOpt = class
  private
    fOwnerGroup: TCompilerOptGroup;
    fId: integer;                       // Identification.
    fOption: string;                    // Option with the leading '-'.
    fSuffix: string;                    // <x> or similar suffix of option.
    fValue: string;                     // Data entered by user, 'True' for Boolean.
    fOrigLine: integer;                 // Original line in the input data.
    fEditKind: TCompilerOptEditKind;
    fDescription: string;
    fIndentation: integer;              // Indentation level in "fpc -h" output.
    fVisible: Boolean;                  // Used for filtering.
    fIgnored: Boolean;                  // Pretend this option does not exist.
    fChoices: TStrings;                 // Choices got from "fpc -i"
    procedure AddChoicesByOptOld;
    function Comment: string;
    procedure Filter(aFilter: string; aOnlySelected: Boolean);
    function GenerateOptValue(aUseComments: Boolean): string;
    procedure SetValue(aValue: string; aOrigLine: integer);
  protected
    procedure ParseEditKind; virtual;
    procedure ParseOption(aDescr: string; aIndent: integer); virtual;
  public
    constructor Create(aOwnerGroup: TCompilerOptGroup);
    destructor Destroy; override;
    function CalcLeft(aDefaultLeft, aLimit: integer): integer;
  public
    property Id: integer read fId;
    property Option: string read fOption;
    property Suffix: string read fSuffix;
    property Value: string read fValue write fValue;
    property EditKind: TCompilerOptEditKind read fEditKind;
    property Description: string read fDescription;
    property Indentation: integer read fIndentation;
    property Visible: Boolean read fVisible write fVisible;
    property Ignored: Boolean read fIgnored write fIgnored;
    property Choices: TStrings read fChoices;
  end;

  TCompilerOptList = TObjectList;
  TCompilerOptReader = class;         // Forward reference

  { TCompilerOptGroup }

  // Group with explanation header. Actual options are not defined here.
  TCompilerOptGroup = class(TCompilerOpt)
  private
    fOwnerReader: TCompilerOptReader;
    // List of options belonging to this group.
    fCompilerOpts: TCompilerOptList;
    fIncludeNegativeOpt: Boolean; // Each option has a variation with "NO" appended.
    function OneCharOptions(aOptAndValue: string): TCompilerOpt;
  protected
    procedure ParseEditKind; override;
    procedure ParseOption(aDescr: string; aIndent: integer); override;
  public
    constructor Create(aOwnerReader: TCompilerOptReader; aOwnerGroup: TCompilerOptGroup);
    destructor Destroy; override;
    procedure Clear;
    function FindOption(aOptStr: string): TCompilerOpt;
    function FindOptionById(aId: integer): TCompilerOpt;
    function SelectOption(aOptAndValue: string): Boolean;
    procedure DeselectAll;
  public
    property CompilerOpts: TCompilerOptList read fCompilerOpts;
  end;

  { TCompilerOptSet }

  // A set of options. A combination of chars or numbers following the option char.
  TCompilerOptSet = class(TCompilerOptGroup)
  private
    fCommonIndent: integer; // Common indentation for this group fixed during parse.
    function SetNumberOpt(aValue: string): Boolean;
    function SetBooleanOpt(aValue: string): Boolean;
  protected
    procedure AddOptions(aDescr: string; aIndent: integer);
    procedure ParseEditKind; override;
  public
    constructor Create(aOwnerReader: TCompilerOptReader;
      aOwnerGroup: TCompilerOptGroup; aCommonIndent: integer);
    destructor Destroy; override;
    function CollectSelectedOptions(aUseComments: Boolean): string;
    procedure SelectOptions(aOptStr: string);
    property CommonIndent: integer read fCommonIndent write fCommonIndent;
  end;

  { TCompilerOptReader }

  TCompilerOptReader = class
  private
    fCurOrigLine: integer;        // Current line num when parsing original data.
    // Defines (-d...) are separated from custom options and stored here.
    fDefines: TStringList;
    // Options not accepted by parser. They may still be valid (a macro maybe)
    fInvalidOptions: TStringList;        // and will be included in output.
    // List of categories parsed from "fpc -i". Contains category names,
    //  Objects[] contains another StringList for the selection list.
    fSupportedCategories: TStringList;
    // Hierarchy of options parsed from "fpc -h".
    fRootOptGroup: TCompilerOptGroup;
    fCompilerExecutable: string;  // Compiler path must be set by caller.
    fFpcVersion: string;          // Parsed from "fpc -h".
    fIsNewFpc: Boolean;
    fParsedTarget: String;
    fErrorMsg: String;
    fGeneratedOptions: TStringList; // Options generated from GUI.
    fUseComments: Boolean;        // Add option's description into generated data.
    function AddChoicesNew(aOpt: string): TStrings;
    function AddNewCategory(aCategoryName: String): TStringList;
    function AddOptInLowestOrigLine(OutStrings: TStrings): Boolean;
    procedure CopyOptions(aRoot: TCompilerOpt);
    function FindLowestOrigLine(aStrings: TStrings; out aOrigLine: Integer): integer;
    function IsGroup(aOpt: string; var aCategoryList: TStrings): Boolean;
    function ReadCategorySelections(aChar: Char): TStringList;
    function ReadVersion(s: string): Boolean;
    procedure CreateNewGroupItem(aGroup: TCompilerOptGroup; aTxt: string);
    procedure AddGroupItems(aGroup: TCompilerOptGroup; aItems: TStrings);
    function ParseI(aLines: TStringList): TModalResult;
    function ParseH(aLines: TStringList): TModalResult;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Clear;
    function UpdateTargetParam: Boolean;
    function ReadAndParseOptions: TModalResult;
    function FilterOptions(aFilter: string; aOnlySelected: Boolean): Boolean;
    function FindOptionById(aId: integer): TCompilerOpt;
    function FromCustomOptions(aStrings: TStrings): TModalResult;
    function ToCustomOptions(aStrings: TStrings; aUseComments: Boolean): TModalResult;
  public
    property Defines: TStringList read fDefines;
    //property SupportedCategories: TStringList read fSupportedCategories;
    property RootOptGroup: TCompilerOptGroup read fRootOptGroup;
    property CompilerExecutable: string read fCompilerExecutable write fCompilerExecutable;
    property ParsedTarget: String read fParsedTarget write fParsedTarget;
    property ErrorMsg: String read fErrorMsg write fErrorMsg;
  end;

  { TCompilerOptThread - thread for reading 'fpc -h' output }

  TCompilerOptThread = class(TThread)
  private
    fReader: TCompilerOptReader;
    fReadTime: TDateTime;
    fStartedOnce: boolean;
    function GetErrorMsg: string;
    procedure Clear; // (main thread)
  protected
    procedure Execute; override;
  public
    constructor Create(aReader: TCompilerOptReader);
    destructor Destroy; override;
    procedure StartParsing; // (main thread)
    procedure EndParsing; // (main thread)
  public
    property ReadTime: TDateTime read fReadTime;
    property ErrorMsg: string read GetErrorMsg;
  end;

implementation

{ TCompiler }

{------------------------------------------------------------------------------
  TCompiler Constructor
------------------------------------------------------------------------------}

constructor TCompiler.Create;
begin
  inherited Create;
end;

{------------------------------------------------------------------------------
  TCompiler Destructor
------------------------------------------------------------------------------}
destructor TCompiler.Destroy;
begin
  inherited Destroy;
end;

{------------------------------------------------------------------------------
  TCompiler Compile
------------------------------------------------------------------------------}
function TCompiler.Compile(AProject: TProject; const WorkingDir,
  CompilerFilename, CompilerParams: string; BuildAll, SkipLinking,
  SkipAssembler, CurrentDirectoryIsTestDir: boolean; const aCompileHint: string
  ): TModalResult;
var
  CmdLine : String;
  Abort : Boolean;
  Tool: TAbstractExternalTool;
  FPCParser: TFPCParser;
  Title: String;
  TargetOS: String;
  TargetCPU: String;
  TargetFilename, SubTool: String;
  CompilerKind: TPascalCompiler;
begin
  Result:=mrCancel;
  if ConsoleVerbosity>=1 then
    DebugLn('TCompiler.Compile WorkingDir="',WorkingDir,'" CompilerFilename="',CompilerFilename,'" CompilerParams="',CompilerParams,'"');

  try
    CheckIfFileIsExecutable(CompilerFilename);
  except
    on E: Exception do begin
      WriteError(Format(lisCompilerErrorInvalidCompiler, [E.Message]));
      if CompilerFilename='' then begin
        WriteError(lisCompilerHintYouCanSetTheCompilerPath);
      end;
      exit;
    end;
  end;
  CmdLine := '';
  if BuildAll then
    CmdLine := CmdLine+' -B';
  if SkipLinking and SkipAssembler then
    CmdLine := CmdLine+' -s'
  else if SkipLinking then
    CmdLine := CmdLine+' -Cn';

  if CompilerParams<>'' then
    CmdLine := CmdLine+' '+CompilerParams;
  if Assigned(FOnCmdLineCreate) then begin
    Abort:=false;
    FOnCmdLineCreate(CmdLine,Abort);
    if Abort then begin
      Result:=mrAbort;
      exit;
    end;
  end;
  if ConsoleVerbosity>=0 then
    DebugLn('[TCompiler.Compile] CmdLine="',CompilerFilename+CmdLine,'"');

  Title:=lisCompileProject;
  if AProject.BuildModes.Count>1 then
    Title+=Format(lisMode, [AProject.ActiveBuildMode.Identifier]);
  TargetOS:=AProject.CompilerOptions.GetEffectiveTargetOS;
  if TargetOS<>GetCompiledTargetOS then
    Title+=Format(lisOS, [TargetOS]);
  TargetCPU:=AProject.CompilerOptions.GetEffectiveTargetCPU;
  if TargetCPU<>GetCompiledTargetCPU then
    Title+=Format(lisCPU, [TargetCPU]);
  TargetFilename:=AProject.GetShortFilename(
          AProject.CompilerOptions.CreateTargetFilename,false);
  if TargetFilename<>'' then
    Title+=Format(lisTarget2, [TargetFilename]);

  Tool:=ExternalToolList.Add(Title);
  Tool.Reference(Self,ClassName);
  try
    Tool.Data:=TIDEExternalToolData.Create(IDEToolCompileProject,'',AProject.ProjectInfoFile);
    Tool.FreeData:=true;
    Tool.Hint:=aCompileHint;
    Tool.Process.Executable:=CompilerFilename;
    Tool.CmdLineParams:=CmdLine;
    Tool.Process.CurrentDirectory:=WorkingDir;
    Tool.CurrentDirectoryIsTestDir:=CurrentDirectoryIsTestDir;
    SubTool:=SubToolFPC;
    CompilerKind:=CodeToolBoss.GetPascalCompilerForDirectory(WorkingDir);
    if CompilerKind=pcPas2js then
      SubTool:=SubToolPas2js;
    FPCParser:=TFPCParser(Tool.AddParsers(SubTool));
    FPCParser.ShowLinesCompiled:=EnvironmentOptions.MsgViewShowFPCMsgLinesCompiled;
    FPCParser.HideHintsSenderNotUsed:=not AProject.CompilerOptions.ShowHintsForSenderNotUsed;
    FPCParser.HideHintsUnitNotUsedInMainSource:=not AProject.CompilerOptions.ShowHintsForUnusedUnitsInMainSrc;
    if (not AProject.CompilerOptions.ShowHintsForUnusedUnitsInMainSrc)
    and (AProject.MainFilename<>'') then
      FPCParser.FilesToIgnoreUnitNotUsed.Add(AProject.MainFilename);
    Tool.AddParsers(SubToolMake);
    Tool.Execute;
    Tool.WaitForExit;
    if Tool.ErrorMessage='' then
      Result:=mrOK;
  finally
    Tool.Release(Self);
  end;
  if ConsoleVerbosity>=0 then
    DebugLn('[TCompiler.Compile] end');
end;

procedure TCompiler.WriteError(const Msg: string);
begin
  DebugLn('TCompiler.WriteError ',Msg);
  if IDEMessagesWindow<>nil then
    IDEMessagesWindow.AddCustomMessage(mluError,Msg);
end;

// Compiler options parsed from "fpc -h" and "fpc -i".

var
  OptionIdCounter: integer;


function NextOptionId: integer;
begin
  Result := OptionIdCounter;
  Inc(OptionIdCounter);
end;

function CalcIndentation(s: string): integer;
begin
  Result := 0;
  while (Result < Length(s)) and (s[Result+1] = ' ') do
    Inc(Result);
end;

function IsIgnoredOption(aOpt: string): Boolean;
begin
  if Length(aOpt) < 2 then Exit(False);
  // Ignore : * information
  //          * all file names and paths
  //          * executable path
  //          * change name of produced executable
  //          * define and undefine
  //          * set language mode
  //          * target operating system
  Result := aOpt[2] in ['i', 'F', 'e', 'o', 'd', 'u', 'M', 'T'];
end;


{ TCompilerOpt }

constructor TCompilerOpt.Create(aOwnerGroup: TCompilerOptGroup);
begin
  inherited Create;
  fOwnerGroup := aOwnerGroup;
  if Assigned(aOwnerGroup) then
    aOwnerGroup.fCompilerOpts.Add(Self);
  fId := NextOptionId;
  fOrigLine := -1;
end;

destructor TCompilerOpt.Destroy;
begin
  inherited Destroy;
end;

procedure TCompilerOpt.AddChoicesByOptOld;
// From FPC 2.6.x output

  procedure AddChoices(aCategory: string);
  // Add selection choices for this option. Data originates from "fpc -i".
  var
    i: Integer;
  begin
    with fOwnerGroup.fOwnerReader do
      if fSupportedCategories.Find(aCategory, i) then
        fChoices := fSupportedCategories.Objects[i] as TStrings
      else
        raise Exception.CreateFmt('No selection list for "%s" found.', [aCategory]);
  end;

begin
  if Pos('fpc -i', fDescription) = 0 then Exit;
  fEditKind := oeList;                 // Values will be got later.
  case fOption of
    '-Ca': AddChoices('ABI targets:');
    '-Cf': AddChoices('FPU instruction sets:');
    '-Cp': AddChoices('CPU instruction sets:');
//      '-Oo', '-Oo[NO]': AddChoices('Optimizations:');
    '-Op': AddChoices('CPU instruction sets:');
//      '-OW': AddChoices('Whole Program Optimizations:');
//      '-Ow': AddChoices('Whole Program Optimizations:');
    else
      raise Exception.Create('Don''t know where to get selection list for option '+fOption);
  end;
end;

procedure TCompilerOpt.ParseEditKind;
begin
  // Guess whether this option can be edited and what is the EditKind
  fEditKind := oeBoolean;                  // Default kind
  if (Length(fSuffix) = 3) and (fSuffix[1] = '<') and (fSuffix[3] = '>') then
    case fSuffix[2] of
      'x': fEditKind:=oeText;              // <x>
      'n': fEditKind:=oeNumber;            // <n>
    end;
  if fOwnerGroup.fOwnerReader.fIsNewFpc then begin
    fChoices := fOwnerGroup.fOwnerReader.AddChoicesNew(fDescription);
    if Assigned(fChoices) then
      fEditKind := oeList;
  end
  else
    AddChoicesByOptOld;
end;

procedure TCompilerOpt.ParseOption(aDescr: string; aIndent: integer);
var
  i: Integer;
begin
  fIndentation := aIndent;
  // Separate the actual option and description from each other
  if aDescr[1] <> '-' then
    raise Exception.CreateFmt('Option "%s" does not start with "-"', [aDescr]);
  i := 1;
  while (i <= Length(aDescr)) and (aDescr[i] <> ' ') do
    Inc(i);
  fOption := Copy(aDescr, 1, i-1);
  while (i <= Length(aDescr)) and (aDescr[i] = ' ') do
    Inc(i);
  fDescription := Copy(aDescr, i, Length(aDescr));
  i := Length(fOption);
  if (i > 3) and (fOption[i-2] = '<') and (fOption[i] = '>') then
  begin
    // Move <x> in the end to Suffix. We need the pure option later.
    fSuffix := Copy(fOption, i-2, i);
    fOption := Copy(fOption, 1, i-3);
  end;
  if fOwnerGroup.fIgnored or IsIgnoredOption(fOption) then
    fIgnored := True;
  ParseEditKind;
end;

procedure TCompilerOpt.Filter(aFilter: string; aOnlySelected: Boolean);
var
  //iOpt, iDes: SizeInt;
  HideNonSelected: Boolean;
begin
  HideNonSelected := (fValue='') and aOnlySelected;
  Visible := not (fIgnored or HideNonSelected)
    and ( (aFilter='') or (Pos(aFilter,UTF8LowerCase(fOption))>0)
                       or (Pos(aFilter,UTF8LowerCase(fDescription))>0) );
{
  if aFilter = '' then
    Visible := not (fIgnored or HideNonSelected)
  else begin
    iOpt := Pos(aFilter,UTF8LowerCase(fOption));
    iDes := Pos(aFilter,UTF8LowerCase(fDescription));
    Visible := not (fIgnored or HideNonSelected) and ( (iOpt>0) or (iDes>0) );
    if Visible then
      DebugLn(['TCompilerOpt.Filter match "', aFilter, '": iOpt=', iOpt,
        ', iDes=', iDes, ', Ignore=', fIgnored, ', aOnlySelected=', aOnlySelected,
        ', Opt'=fOption, ', Descr=', fDescription]);
  end;
}
end;

const
  CommentId = '-dLazIdeComment_';

function TCompilerOpt.Comment: string;
begin
  Result := '  ' + CommentId + StringReplace(fDescription,' ','_',[rfReplaceAll]);
end;

function TCompilerOpt.GenerateOptValue(aUseComments: Boolean): string;
begin
  if fValue = '' then Exit('');
  if fValue = 'True' then                  // Boolean
    Result := fOption
  else                                     // or value of other kind
    Result := fOption + StrToCmdLineParam(Value);
  // ToDo: Show "//" comment in editor and change to a define when storing.
  //   Result := '    // ' + aOpt.Description
  if aUseComments then  // Replace illegal characters with '_' in comment
    Result := Result + Comment;
end;

procedure TCompilerOpt.SetValue(aValue: string; aOrigLine: integer);
begin
  fValue := aValue;
  fOrigLine := aOrigLine;
end;

function TCompilerOpt.CalcLeft(aDefaultLeft, aLimit: integer): integer;
var
  Len: Integer;
begin
  Len := (fIndentation div 2) + Length(fOption);      // Approximation
  if Len > aLimit then
    Result := aDefaultLeft + (Len-aLimit)*8
  else
    Result := aDefaultLeft;
end;

{ TCompilerOptGroup }

constructor TCompilerOptGroup.Create(aOwnerReader: TCompilerOptReader; aOwnerGroup: TCompilerOptGroup);
begin
  inherited Create(aOwnerGroup);
  fOwnerReader := aOwnerReader;
  fCompilerOpts := TCompilerOptList.Create;
end;

destructor TCompilerOptGroup.Destroy;
begin
  fCompilerOpts.Free;
  inherited Destroy;
end;

procedure TCompilerOptGroup.Clear;
begin
  fCompilerOpts.Clear;
end;

function TCompilerOptGroup.FindOption(aOptStr: string): TCompilerOpt;

  function FindOptionSub(aRoot: TCompilerOpt): TCompilerOpt;
  var
    Children: TCompilerOptList;
    i: Integer;
  begin
    Result := Nil;
    if aRoot is TCompilerOptGroup then
    begin
      Children := TCompilerOptGroup(aRoot).CompilerOpts;
      if aRoot is TCompilerOptSet then
      begin                  // TCompilerOptSet
        if AnsiStartsStr(aRoot.Option, aOptStr) then
        begin
          with TCompilerOptSet(aRoot) do
            SelectOptions(Copy(aOptStr, Length(aRoot.Option)+1, Length(aOptStr)));
          Result := aRoot;
        end;
      end
      else begin             // TCompilerOptGroup
        for i := 0 to Children.Count-1 do         // Recursive call for children.
        begin
          Result := FindOptionSub(TCompilerOpt(Children[i]));
          if Assigned(Result) then Break;
        end;
      end;
    end
    else begin               // TCompilerOpt
      if aRoot.Option = aOptStr then
        Result := aRoot
      else if (aRoot.EditKind = oeText) and AnsiStartsStr(aRoot.Option, aOptStr) then
      begin
        aRoot.SetValue(Copy(aOptStr, Length(aRoot.Option)+1, Length(aOptStr)),
                       fOwnerReader.fCurOrigLine);
        Result := aRoot;
      end;
    end;
  end;

begin
  Result := FindOptionSub(Self);
end;

function TCompilerOptGroup.FindOptionById(aId: integer): TCompilerOpt;

  function FindOptionSub(aRoot: TCompilerOpt): TCompilerOpt;
  var
    Children: TCompilerOptList;
    i: Integer;
  begin
    Result := Nil;
    if aRoot is TCompilerOptGroup then
    begin
      Children := TCompilerOptGroup(aRoot).CompilerOpts;
      for i := 0 to Children.Count-1 do         // Recursive call for children.
      begin
        Result := FindOptionSub(TCompilerOpt(Children[i]));
        if Assigned(Result) then Break;
      end;
    end
    else begin               // TCompilerOpt
      if aRoot.fId = aId then
        Result := aRoot;
    end;
  end;

begin
  Result := FindOptionSub(Self);
end;

function TCompilerOptGroup.OneCharOptions(aOptAndValue: string): TCompilerOpt;
// Split and select option characters like in -Criot.
// Returns reference to the last option object if all characters were valid opts.
var
  i: Integer;
  OptBase: String;
  List: TList;
begin
  List := TList.Create;
  try
    OptBase := Copy(aOptAndValue, 1, 2);
    // First check if all options are valid. Change them only if they are valid.
    for i := 3 to Length(aOptAndValue) do
    begin
      Result := FindOption(OptBase + aOptAndValue[i]);
      if Assigned(Result) then
        List.Add(Result)
      else
        Break;
    end;
    // Set boolean options but only if they all are valid.
    if Assigned(Result) then
      for i := 0 to List.Count-1 do
        TCompilerOpt(List[i]).SetValue('True', fOwnerReader.fCurOrigLine);
  finally
    List.Free;
  end;
end;

function TCompilerOptGroup.SelectOption(aOptAndValue: string): Boolean;
var
  Opt: TCompilerOpt;
  Param: string;
  OptLen, ParamLen: integer;
begin
  Opt := FindOption(aOptAndValue);
  if Assigned(Opt) then
  begin
    // Found. Set boolean option, other type of options are already set.
    if Opt.EditKind = oeBoolean then
      Opt.SetValue('True', fOwnerReader.fCurOrigLine);
  end
  else begin
    // Option was not found, try separating the parameter.
    // ToDo: figure out the length in a more clever way.
    if (Length(aOptAndValue) < 3) or (aOptAndValue[1] <> '-') then
      Exit(False);
    if aOptAndValue[2] in ['e', 'u', 'I', 'k', 'o'] then
      OptLen := 2
    else
      OptLen := 3;
    ParamLen := Length(aOptAndValue) - OptLen;
    Opt := Nil;
    if (ParamLen > 1)
    and (aOptAndValue[OptLen+1] in ['''', '"'])
    and (aOptAndValue[Length(aOptAndValue)] in ['''', '"']) then
      Param := Copy(aOptAndValue, OptLen+2, ParamLen-2) // Strip quotes
    else begin
      Param := Copy(aOptAndValue, OptLen+1, ParamLen);
      if OptLen = 3 then // Can contain one char options like -Criot. Can be combined.
        Opt := OneCharOptions(aOptAndValue);
    end;
    if Opt = Nil then
    begin
      Opt := FindOption(Copy(aOptAndValue, 1, OptLen));
      if Assigned(Opt) then
      begin
        Assert(Opt.Value='', 'TCompilerOptGroup.SelectOption: Opt.Value is already set.');
        Opt.SetValue(Param, fOwnerReader.fCurOrigLine)
      end;
    end;
  end;
  Result := Assigned(Opt);
end;

procedure TCompilerOptGroup.DeselectAll;

  procedure DeselectSub(aRoot: TCompilerOpt);
  var
    Children: TCompilerOptList;
    i: Integer;
  begin
    if aRoot is TCompilerOptGroup then
    begin
      Children := TCompilerOptGroup(aRoot).CompilerOpts;
      for i := 0 to Children.Count-1 do         // Recursive call for children.
        DeselectSub(TCompilerOpt(Children[i]));
    end
    else
      aRoot.SetValue('', -1);       // TCompilerOpt
  end;

begin
  DeselectSub(Self);
end;

procedure TCompilerOptGroup.ParseEditKind;
begin
  fEditKind := oeGroup;
end;

procedure TCompilerOptGroup.ParseOption(aDescr: string; aIndent: integer);
var
  i: Integer;
begin
  inherited ParseOption(aDescr, aIndent);
  i := Length(fOption);
  fIncludeNegativeOpt := Copy(fOption, i-3, 4) = '[NO]';
  if fIncludeNegativeOpt then
    SetLength(fOption, i-4);
end;

{ TCompilerOptSet }

constructor TCompilerOptSet.Create(aOwnerReader: TCompilerOptReader;
  aOwnerGroup: TCompilerOptGroup; aCommonIndent: integer);
begin
  inherited Create(aOwnerReader, aOwnerGroup);
  fCommonIndent := aCommonIndent;
end;

destructor TCompilerOptSet.Destroy;
begin
  inherited Destroy;
end;

function TCompilerOptSet.CollectSelectedOptions(aUseComments: Boolean): string;
// Collect subitems of a set to one option.
var
  Opt: TCompilerOpt;
  i: Integer;
  s: string;
begin
  s := '';
  for i := 0 to fCompilerOpts.Count-1 do
  begin
    Opt := TCompilerOpt(fCompilerOpts[i]);
    if Opt.Value <> '' then
      case Opt.EditKind of
        oeSetElem  : s := s + Opt.Option;
        oeSetNumber: s := s + Opt.Value;
      end;
  end;
  if s <> '' then begin
    Result := Option + s;
    if aUseComments then
      Result := Result + Comment;
  end
  else
    Result := '';
end;

function TCompilerOptSet.SetNumberOpt(aValue: string): Boolean;
// Find a numeric value in the set and update its value. Return True on success.
var
  i: Integer;
  Opt: TCompilerOpt;
begin
  for i := 0 to fCompilerOpts.Count-1 do
  begin
    Opt := TCompilerOpt(fCompilerOpts[i]);
    if Opt.EditKind = oeSetNumber then
    begin
      Opt.SetValue(aValue, fOwnerReader.fCurOrigLine);
      Exit(True);           // Found and updated.
    end;
  end;
  Result := False;          // Not found.
end;

function TCompilerOptSet.SetBooleanOpt(aValue: string): Boolean;
// Find a single letter value in the set and update its value. Return True on success.
var
  i: Integer;
  Opt: TCompilerOpt;
begin
  for i := 0 to fCompilerOpts.Count-1 do
  begin
    Opt := TCompilerOpt(fCompilerOpts[i]);
    if (Opt.EditKind = oeSetElem) and (Opt.Option = aValue) then
    begin
      Opt.SetValue('True', fOwnerReader.fCurOrigLine);
      Exit(True);           // Found and updated.
    end;
  end;
  Result := False;          // Not found.
end;

procedure TCompilerOptSet.SelectOptions(aOptStr: string);
// Select options in this set based on the given characters.
var
  i, Start: Integer;
  OneOpt: string;
  OptOk: Boolean;
begin
  i := 1;
  while i <= Length(aOptStr) do
  begin
    Start := i;
    if aOptStr[i] in ['0'..'9'] then
      while (i <= Length(aOptStr)) and (aOptStr[i] in ['0'..'9']) do
        Inc(i)
    else
      Inc(i);
    OneOpt := Copy(aOptStr, Start, i-Start);
    if OneOpt[1] in ['0'..'9'] then
      OptOk := SetNumberOpt(OneOpt)
    else
      OptOk := False;
    if not (OptOk or SetBooleanOpt(OneOpt)) then
      raise Exception.CreateFmt('Option %s is not found in set %s.', [OneOpt, fOption]);
  end;
end;

procedure TCompilerOptSet.AddOptions(aDescr: string; aIndent: integer);
// Set can have one letter options and <n> for numbers

  procedure NewSetNumber(aDescr: string);
  var
    OptSet: TCompilerOpt;
  begin
    OptSet := TCompilerOpt.Create(Self);          // Add it under a group
    OptSet.fIndentation := aIndent;
    OptSet.fOption := 'Number';
    OptSet.fDescription := aDescr;
    OptSet.fEditKind := oeSetNumber;
  end;

  procedure NewSetElem(aDescr: string);
  var
    OptSet: TCompilerOpt;
  begin
    // Ignore -vl and -vs
    if (fOption = '-v') and (aDescr[1] in ['l', 's']) then Exit;
    OptSet := TCompilerOpt.Create(Self);          // Add it under a group
    OptSet.fIndentation := aIndent;
    OptSet.fOption := aDescr[1];
    OptSet.fDescription := Copy(aDescr, 2, Length(aDescr));
    OptSet.fEditKind := oeSetElem;
  end;

var
  Opt1, Opt2: string;
  i: Integer;
begin
  if AnsiStartsStr('<n>', aDescr) then
    NewSetNumber(aDescr)
  else begin
    i := PosEx(':', aDescr, 4);
    if (i > 0) and (aDescr[i-1]=' ') and (aDescr[i-2]<>' ') and (aDescr[i-3]=' ') then
    begin
      // Found another option on the same line, like ' a :'
      Opt2 := Copy(aDescr, i-2, Length(aDescr));
      if aDescr[3] = ':' then
        Opt1 := TrimRight(Copy(aDescr, 1, i-3))
      else
        Opt1 := '';
    end
    else begin
      Opt2 := '';
      Opt1 := aDescr;
    end;
    if Opt1 <> '' then         // Can be empty when line in help output is split.
      NewSetElem(Opt1)
    else if fCompilerOpts.Count > 0 then
      aIndent := TCompilerOpt(fCompilerOpts[0]).Indentation;
    if Opt2 <> '' then
      NewSetElem(Opt2);
  end;
end;

procedure TCompilerOptSet.ParseEditKind;
begin
  fEditKind := oeSet;
end;


{ TCompilerOptReader }

constructor TCompilerOptReader.Create;
begin
  inherited Create;
  fDefines := TStringList.Create;
  fInvalidOptions := TStringList.Create;
  fSupportedCategories := TStringList.Create;
  fSupportedCategories.Sorted := True;
  fGeneratedOptions := TStringList.Create;
  fRootOptGroup := TCompilerOptGroup.Create(Self, Nil);
end;

destructor TCompilerOptReader.Destroy;
begin
  Clear;
  fRootOptGroup.Free;
  fGeneratedOptions.Free;
  fSupportedCategories.Free;
  fInvalidOptions.Free;
  fDefines.Free;
  inherited Destroy;
end;

procedure TCompilerOptReader.Clear;
var
  i: Integer;
begin
  fRootOptGroup.Clear;
  for i := 0 to fSupportedCategories.Count-1 do
    fSupportedCategories.Objects[i].Free;
  fSupportedCategories.Clear;
end;

function TCompilerOptReader.AddChoicesNew(aOpt: string): TStrings;
// From FPC 2.7.1+ output
const
  FpcIStart = 'see fpc -i or fpc -i';
var
  ch: Char;
  i: integer;
begin
  Result := Nil;
  i := Pos(FpcIStart, aOpt);
  if i = 0 then Exit;
  Assert(Length(aOpt) >= i+Length(FpcIStart));
  ch := aOpt[i+Length(FpcIStart)]; // Pick the next char from description.
  if fSupportedCategories.Find(ch, i) then
    Result := fSupportedCategories.Objects[i] as TStrings
  else begin
    Result := ReadCategorySelections(ch);
    Result.Insert(0, ''); // First an empty string. Allows removing selection.
    fSupportedCategories.AddObject(ch, Result);
  end;
end;

function TCompilerOptReader.IsGroup(aOpt: string; var aCategoryList: TStrings): Boolean;
// This option should be a group instead of a selection list.
// The information is not available in fpc -h output.
var
  i: Integer;
  CategoryName: string;
begin
  Result := False;
  if fIsNewFpc then
  begin
    // FPC 2.7.1+
    if AnsiStartsStr('-Oo', aOpt)
    or AnsiStartsStr('-OW', aOpt)
    or AnsiStartsStr('-Ow', aOpt) then
    begin
      aCategoryList := AddChoicesNew(aOpt);
      Result := Assigned(aCategoryList);
    end;
  end
  else begin
    // FPC 2.6.x
    CategoryName := '';
    if AnsiStartsStr('-Oo', aOpt) then
      CategoryName := 'Optimizations:'
    else if AnsiStartsStr('-OW', aOpt) or AnsiStartsStr('-Ow', aOpt) then
      CategoryName := 'Whole Program Optimizations:';
    Result := CategoryName <> '';
    if Result then
      if fSupportedCategories.Find(CategoryName, i) then
        aCategoryList := fSupportedCategories.Objects[i] as TStrings
      else
        raise Exception.CreateFmt('No list of options found for "%s".', [CategoryName]);
  end;
end;

function TCompilerOptReader.AddNewCategory(aCategoryName: String): TStringList;
begin
  Result := TStringList.Create;
  Result.Add('');      // First an empty string. Allows removing selection.
  fSupportedCategories.AddObject(aCategoryName, Result);
end;

function TCompilerOptReader.ParseI(aLines: TStringList): TModalResult;
const
  Supported = 'Supported ';
var
  i, j: Integer;
  Line, TrimmedLine: String;
  Category, sl: TStringList;
begin
  Result := mrOK;
  Category := Nil;
  sl := TStringList.Create;
  try
    sl.StrictDelimiter := True;
    sl.Delimiter := ',';
    for i := 0 to aLines.Count-1 do
    begin
      Line := aLines[i];
      TrimmedLine := Trim(Line);
      if Assigned(Category) then
      begin
        if TrimmedLine = '' then
          Category := Nil             // End of category.
        else begin
          if Line[1] <> ' ' then
            raise Exception.Create('TCompilerReader.ParseI: Line should start with a space.');
          sl.Clear;
          // Some old FPC versions had a comma separated list.
          sl.DelimitedText := Trim(Line);
          for j := 0 to sl.Count-1 do
            Category.Add(sl[j]);
        end;
      end
      else if AnsiStartsStr(Supported, Line) then
        Category := AddNewCategory(Copy(Line, Length(Supported)+1, Length(Line)));
    end;
  finally
    sl.Free;
  end;
end;

function TCompilerOptReader.ReadVersion(s: string): Boolean;
const
  VersBegin = 'Free Pascal Compiler version ';
var
  Start, V1, V2: Integer;
  OutputI: TStringList;      // fpc -Fr$(FPCMsgFile) -i
begin
  Result := AnsiStartsStr(VersBegin, s);
  if Result then
  begin
    fIsNewFpc := False;
    Start := Length(VersBegin)+1;
    V1 := PosEx(' ', s, Start);
    if V1 > 0 then
    begin
      fFpcVersion := Copy(s, Start, V1-Start);
      if (Length(fFpcVersion)>2) then begin
        V1 := StrToIntDef(fFpcVersion[1], 0);
        V2 := StrToIntDef(fFpcVersion[3], 0);
        fIsNewFpc := ((V1=2) and (V2>=7)) or (V1>2);
      end;
      // The rest 2 fields are date and target CPU.
    end;
    if not fIsNewFpc then
    begin
      // Get categories with FPC -i, once we know the version is old (2.6.x).
      OutputI := RunTool(fCompilerExecutable, fParsedTarget + ' -i');
      if OutputI = Nil then Exit(False);
      try
        Result := ParseI(OutputI) = mrOK;
      finally
        OutputI.Free;
      end;
    end;
  end;
end;

procedure TCompilerOptReader.CreateNewGroupItem(aGroup: TCompilerOptGroup; aTxt: string);
var
  Opt: TCompilerOpt;
begin
  Opt := TCompilerOpt.Create(aGroup);  // Add it under a group
  Opt.fOption := aGroup.Option + aTxt;
  Opt.fIndentation := aGroup.Indentation+4;
  Opt.fEditKind := oeBoolean;
end;

procedure TCompilerOptReader.AddGroupItems(aGroup: TCompilerOptGroup; aItems: TStrings);
var
  i: Integer;
begin
  for i := 1 to aItems.Count-1 do        // Skip the first empty item.
  begin
    CreateNewGroupItem(aGroup, aItems[i]);
    if aGroup.fIncludeNegativeOpt then
      CreateNewGroupItem(aGroup, 'NO'+aItems[i]);
  end;
end;

function TCompilerOptReader.ParseH(aLines: TStringList): TModalResult;
const
  OptSetId = 'a combination of';
var
  i, ThisInd, NextInd, OptSetInd: Integer;
  ThisLine: String;
  Opt: TCompilerOpt;
  LastGroup, SubGroup: TCompilerOptGroup;
  GroupItems: TStrings;
begin
  Result := mrOK;
  LastGroup := fRootOptGroup;
  GroupItems:=nil;
  for i := 0 to aLines.Count-1 do
  begin
    ThisLine := StringReplace(aLines[i],'-Agas-darwinAssemble','-Agas-darwin Assemble',[]);
    ThisInd := CalcIndentation(ThisLine);
    ThisLine := Trim(ThisLine);
    if LastGroup is TCompilerOptSet then
    begin                  // Fix strangely split line indents in options groups.
      OptSetInd := TCompilerOptSet(LastGroup).CommonIndent;
      if (ThisLine[1] <> '-') and (ThisInd > OptSetInd) then
        ThisInd := OptSetInd;
    end;
    // Top header line for compiler version, check only once.
    if (fFpcVersion = '') and ReadVersion(ThisLine) then Continue;
    if ThisInd < 2 then Continue;
    if (ThisLine = '') or (ThisInd > 30)
    or (ThisLine[1] = '@')
    or (Pos('-? ', ThisLine) > 0)
    or (Pos('-h ', ThisLine) > 0) then Continue;
    if i < aLines.Count-1 then
      NextInd := CalcIndentation(aLines[i+1])
    else
      NextInd := -1;
    if NextInd > ThisInd then
    begin
      if LastGroup is TCompilerOptSet then
        NextInd := TCompilerOptSet(LastGroup).CommonIndent
      else begin
        if Pos(OptSetId, ThisLine) > 0 then       // Header for sets
          // Hard-code indent to NextInd, for strangely split lines later in help output.
          LastGroup := TCompilerOptSet.Create(Self, LastGroup, NextInd)
        else                                      // Group header for options
          LastGroup := TCompilerOptGroup.Create(Self, LastGroup);
        LastGroup.ParseOption(ThisLine, ThisInd);
      end;
    end;
    if NextInd <= ThisInd then
    begin
      // This is an option
      if LastGroup is TCompilerOptSet then      // Add it to a set (may add many)
        TCompilerOptSet(LastGroup).AddOptions(ThisLine, ThisInd)
      else begin
        if IsGroup(ThisLine, GroupItems) then
        begin
          SubGroup := TCompilerOptGroup.Create(Self, LastGroup);
          SubGroup.ParseOption(ThisLine, ThisInd);
          AddGroupItems(SubGroup, GroupItems);
        end
        else begin
          Opt := TCompilerOpt.Create(LastGroup);  // Add it under a group
          Opt.ParseOption(ThisLine, ThisInd);
        end;
      end;
      if (NextInd <> -1) and (NextInd < ThisInd) then
        LastGroup := LastGroup.fOwnerGroup;       // Return to a previous group
    end;
  end;
end;

function TCompilerOptReader.UpdateTargetParam: Boolean;
// Updates target OS and CPU parameter using global macros.
// Returns true if the value has changed since last time.
var
  NewTarget: string;
begin
  NewTarget := '-T$(TargetOS) -P$(TargetCPU)';
  if not GlobalMacroList.SubstituteStr(NewTarget) then
    raise Exception.CreateFmt('UpdateTargetParam: Cannot substitute macros "%s".',
                              [NewTarget]);
  Result := fParsedTarget <> NewTarget;
  if Result then
    fParsedTarget := NewTarget;      // fParsedTarget is used as a param for FPC.
end;

function TCompilerOptReader.ReadCategorySelections(aChar: Char): TStringList;
// Get the selection list for a category using "fpc -i+char", for new FPC versions.
begin
  Result:=RunTool(fCompilerExecutable, fParsedTarget + ' -i' + aChar);
  Result.Sort;
end;

function TCompilerOptReader.ReadAndParseOptions: TModalResult;
// fpc -Fr$(FPCMsgFile) -h
var
  OutputH: TStringList;
begin
  if fCompilerExecutable = '' then
    fCompilerExecutable := 'fpc';        // Let's hope "fpc" is found in PATH.
  OptionIdCounter := 0;
  fErrorMsg := '';
  try
    // FPC with option -h
    OutputH := RunTool(fCompilerExecutable, fParsedTarget + ' -h');
    if OutputH = Nil then Exit(mrCancel);
    Result := ParseH(OutputH);
  finally
    OutputH.Free;
  end;
end;

function TCompilerOptReader.FilterOptions(aFilter: string; aOnlySelected: Boolean): Boolean;
// Filter all options recursively, setting their Visible flag as needed.
// Returns True if Option(group) or child options have visible items.

  function FilterOptionsSub(aRoot: TCompilerOpt): Boolean;
  var
    Children: TCompilerOptList;
    i: Integer;
  begin
    // Filter the root item
    aRoot.Filter(aFilter, aOnlySelected);         // Sets Visible flag
    // Filter children in a group
    if aRoot is TCompilerOptGroup then
    begin
      Children := TCompilerOptGroup(aRoot).CompilerOpts;
      for i := 0 to Children.Count-1 do           // Recursive call for children.
        aRoot.Visible := FilterOptionsSub(TCompilerOpt(Children[i])) or aRoot.Visible;
    end;
    Result := aRoot.Visible;
  end;

begin
  Result := FilterOptionsSub(fRootOptGroup);
end;

function TCompilerOptReader.FindOptionById(aId: integer): TCompilerOpt;
begin
  Result := fRootOptGroup.FindOptionById(aId);
end;

function TCompilerOptReader.FromCustomOptions(aStrings: TStrings): TModalResult;
// Example:  $(IDEBuildOptions) -dCR -dgc -Criot
var
  i, j: Integer;
  s: String;
  sl: TStringList;
begin
  Result := mrOK;
  fCurOrigLine := 0;
  fRootOptGroup.DeselectAll;
  fDefines.Clear;
  fInvalidOptions.Clear;
  sl := TStringList.Create;
  try
    // Separate options that are on one line.
    for i := 0 to aStrings.Count-1 do
    begin
      s := Trim(aStrings[i]);
      if s = '' then Continue;
      sl.Clear;
      SplitCmdLineParams(s, sl);
      for j := 0 to sl.Count-1 do begin
        s := sl[j];
        // Put the option into fDefines or fInvalidOptions, or set in options collection.
        if AnsiStartsStr('-d', s) and (Length(s) > 2) then
        begin
          if not AnsiStartsStr(CommentId, s) then    // Skip a generated comment.
            fDefines.Add(s)
        end
        else
          if not fRootOptGroup.SelectOption(s) then
            fInvalidOptions.AddObject(s, TObject({%H-}Pointer(PtrUInt(i))));
        Inc(fCurOrigLine);
      end;
    end;
  finally
    sl.Free;
  end;
end;

procedure TCompilerOptReader.CopyOptions(aRoot: TCompilerOpt);
// Collect non-default options from GUI to fGeneratedOptions
var
  Children: TCompilerOptList;
  i: Integer;
  s: string;
begin
  if aRoot is TCompilerOptGroup then
  begin
    Children := TCompilerOptGroup(aRoot).CompilerOpts;
    if aRoot is TCompilerOptSet then
    begin                                       // TCompilerOptSet
      s := TCompilerOptSet(aRoot).CollectSelectedOptions(fUseComments);
      if s <> '' then
        fGeneratedOptions.AddObject(s, TObject({%H-}Pointer(PtrUInt(aRoot.fOrigLine))));
    end
    else begin                                  // TCompilerOptGroup
      for i := 0 to Children.Count-1 do
        CopyOptions(TCompilerOpt(Children[i])); // Recursive call for children.
    end;
  end
  else if aRoot.Value <> '' then                // TCompilerOpt
    fGeneratedOptions.AddObject(aRoot.GenerateOptValue(fUseComments),
                                TObject({%H-}Pointer(PtrUINt(aRoot.fOrigLine))));
end;

function TCompilerOptReader.FindLowestOrigLine(aStrings: TStrings;
                                               out aOrigLine: Integer): integer;
// Return index in aStrings for an option that has the lowest original line number.
// aOrigLine returns the original line number.
var
  i, OriLine, MinOrigLine: Integer;
begin
  Result := -1;
  aOrigLine := -1;
  MinOrigLine := MaxInt;
  for i := 0 to aStrings.Count-1 do
  begin
    OriLine := Integer({%H-}PtrUInt(aStrings.Objects[i]));
    if (OriLine > -1) and (OriLine < MinOrigLine) then
    begin
      MinOrigLine := OriLine;
      aOrigLine := OriLine;
      Result := i;
    end;
  end;
end;

function TCompilerOptReader.AddOptInLowestOrigLine(OutStrings: TStrings): Boolean;
// Copy an option that had the lowest original line number.
// Returns True if options from original data was found.
var
  iGen, iInv: Integer;
  iGenOrig, iInvOrig: Integer;
begin
  // Find lowest lines from both generated and invalid options
  iGen := FindLowestOrigLine(fGeneratedOptions, iGenOrig);
  iInv := FindLowestOrigLine(fInvalidOptions, iInvOrig);
  // then add the one that is lower.
  if (iGenOrig = -1) and (iInvOrig = -1) then Exit(False);
  Result := True;
  if ( (iGenOrig > -1) and (iInvOrig > -1) and (iGenOrig <= iInvOrig) )
  or ( (iGenOrig > -1) and (iInvOrig = -1) ) then
  begin
    OutStrings.Add(fGeneratedOptions[iGen]);
    fGeneratedOptions[iGen] := '';
    fGeneratedOptions.Objects[iGen] := TObject(Pointer(-1)); // Mark as processed.
  end
  else begin
    OutStrings.Add(fInvalidOptions[iInv]);
    fInvalidOptions[iInv] := '';
    fInvalidOptions.Objects[iInv] := TObject(Pointer(-1));
  end;
end;

function TCompilerOptReader.ToCustomOptions(aStrings: TStrings;
  aUseComments: Boolean): TModalResult;
// Copy options to a list if they have a non-default value (True for boolean).
var
  i: Integer;
begin
  Result := mrOK;
  fUseComments := aUseComments;
  fGeneratedOptions.Clear;
  CopyOptions(fRootOptGroup);
  // Options are now in fGeneratedOptions. Move them to aStrings in a right order.
  aStrings.Clear;
  // First collect options that were in the original list.
  while AddOptInLowestOrigLine(aStrings) do ;
  // Then add all the rest.
  for i := 0 to fGeneratedOptions.Count-1 do
    if fGeneratedOptions[i] <> '' then
      aStrings.Add(fGeneratedOptions[i]);
  // Then defines
  aStrings.AddStrings(fDefines);
end;

{ TCompilerOptThread }

constructor TCompilerOptThread.Create(aReader: TCompilerOptReader);
begin
  inherited Create(True);
  //FreeOnTerminate:=True;
  fStartedOnce:=false;
  fReader:=aReader;
end;

destructor TCompilerOptThread.Destroy;
begin
  if fStartedOnce then
    WaitFor;
  Clear;
  inherited Destroy;
end;

function TCompilerOptThread.GetErrorMsg: string;
begin
  Result := fReader.ErrorMsg;
end;

procedure TCompilerOptThread.Clear;
begin
  ;
end;

procedure TCompilerOptThread.StartParsing;
begin
  if fStartedOnce then
    WaitFor;
  fReader.CompilerExecutable:=LazarusIDE.GetCompilerFilename;
  fReader.UpdateTargetParam;
  Start;
  fStartedOnce:=true;
end;

procedure TCompilerOptThread.EndParsing;
begin
  if fStartedOnce then
    WaitFor;
end;

procedure TCompilerOptThread.Execute;
var
  StartTime: TDateTime;
begin
  StartTime := Now;
  try
    fReader.ReadAndParseOptions;
  except
    on E: Exception do
      fReader.ErrorMsg := 'Error reading compiler: '+E.Message;
  end;
  fReadTime := Now-StartTime;
end;


end.