-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
SimpleCmdLineParser.pas
1505 lines (1295 loc) · 49.5 KB
/
SimpleCmdLineParser.pas
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
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
Simple Command Line Parser
Provides a class (TSimpleCmdLineParser) that can parse and split a command
line string into individual commands, each possibly with arguments, and
other textual parameters.
You can either give the command line string explicitly as a textual
parameter, or you can use parameter-less methods (Create, Parse) that will
obtain and parse command line string of the current process/program.
When getting the command line string from the system, it is necessary to
remember how this works in different operating systems...
In Windows, it is possible to obtain the string directly and unaltered,
so not much problem there.
But in Linux, there is, AFAIK, no way how to obtain the original string.
The command line is processed by the used shell and only already split
and processed (eg. escaping is resolved, quoting is removed, ...)
parameters are given to the program.
This library tries to reconstruct the full command line in Linux by
joining the parameters back together. Each parameter is also scanned and
altered so it can be later correctly parsed again (eg. text containing
white spaces is enclosed in quotes, backslashes are doubled, ...), but
some information might be lost by this point, so full reconstruction is
not always possible.
To mitigate the biggest problems, it is usually enought to observe all
rules of currently configured shell (quoting, escaping, ...) when writing
the line and making sure the shell produces something this library could
work with. Only one thing cannot be corrected this way - if the string
contains a parameter that is indistinguishable from a commnad, but is not
a command (eg. is quoted), then it must be prepared so that it is not
seen as a command when obtained from arguments vector - enclose it in
quotes that guarantee the content is not resolved (usually single quotes
- consult documentation of your shell) and prepend it with a single
backslash.
Now for the parsing...
Special characters:
command introduction character - dash (-)
escape character - backslash (\)
quotation characters - double quotes (") and single quotes (')
Objects (commands, texts) are delimited (separated) by a white space,
unless that white space is enclosed in quotes (both double and single
quotes are allowed, but they cannot be mixed).
Backslash is used as escape character - whatever follows it is preserved
in the final parameter text as is. This way, you can put quotes or escape
character in the parameters.
That being said - if you are giving the string explicitly, it is necessary
to double all backslash (\) characters if they are to be preserved (eg. in
file paths) - use class method CommandLinePreprocess for that purpose.
In current implementation, three basic objects are recognized in the
command line - short command, long command and general object.
Short command
- starts with a single command intro char
- exactly one character long
- only lower and upper case letters (a..z, A..Z)
- case sensitive (a is NOT the same as A)
- cannot be enclosed in quote chars
- can be compounded (several short commands merged into one block)
- can have arguments delimited by a white space
Short command examples:
-v simple short command
-vbT compound command (commands v, b and T)
-f file1.txt "file 2.txt" simple with two arguments
-Tzf "file.dat" compound, last command (f) with one
argument
Long command
- starts with two command intro chars
- length is not explicitly limited
- only lower and upper case letters (a..z, A..Z), numbers (0..9),
underscore (_) and dash (-)
- case insensitive (FOO is the same as Foo)
- cannot start with a dash
- cannot contain escape character
- cannot be enclosed in quote chars
- cannot be compounded
- can have arguments delimited by a white space
Long command examples:
--show_warnings simple long command
--input_file "file1.txt" long command with one argument
--files "file1.dat" "files2.dat" long command with two arguments
General object
- any text that is not a command
- if it contains white spaces, it must be enclosed in quotes (as
objects are delimited by white spaces) - both single (') and double
(") quotes are allowed (but they cannot be mixed)
- backslash is an escape character, meaning anything following it is
preserved as is (including quotes or another escape char), while the
escaping character itself is removed
- any general object appearing after a command is also added as an
argument of that command
- if first parsed object from a command line is a general object, it is
assumed to be the image path
General object examples:
this_is_simple_general_text
"quoted text with \"whitespaces\" and quote chars"
"special characters: - -- \\ \" \'"
Now let's have some example command lines to see how they will be parsed...
First a Windows-style example:
"c:\test.exe" -sab 1 15 9 --test "output file.txt"
c:\test.exe general object (image path)
s short command
a short command
b short command with three arguments:
1
15
9
1 general object
15 general object
9 general object
test long command with one argument:
output file.txt
output file.txt general object
And now something more Linux-like:
.\test --test -u 999 0 \-t 'string'"'"'string'
.\test general object (image path)
test long command
u short command with four arguments:
999
0
-t
string'string
999 general object
0 general object
-t general object
string'string general object
Version 2.0.2 (2024-05-03)
Last change 2024-10-04
©2017-2024 František Milt
Contacts:
František Milt: [email protected]
Support:
If you find this code useful, please consider supporting its author(s) by
making a small donation using the following link(s):
https://www.paypal.me/FMilt
Changelog:
For detailed changelog and history please refer to this git repository:
github.com/TheLazyTomcat/Lib.SimpleCmdLineParser
Dependencies:
AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses
* AuxExceptions - github.com/TheLazyTomcat/Lib.AuxExceptions
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
StrRect - github.com/TheLazyTomcat/Lib.StrRect
Library AuxExceptions is required only when rebasing local exception classes
(see symbol SimpleCmdLineParser_UseAuxExceptions for details).
Library AuxExceptions might also be required as an indirect dependency.
Indirect dependencies:
SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID
UInt64Utils - github.com/TheLazyTomcat/Lib.UInt64Utils
WinFileInfo - github.com/TheLazyTomcat/Lib.WinFileInfo
===============================================================================}
unit SimpleCmdLineParser;
{
SimpleCmdLineParser_UseAuxExceptions
If you want library-specific exceptions to be based on more advanced classes
provided by AuxExceptions library instead of basic Exception class, and don't
want to or cannot change code in this unit, you can define global symbol
SimpleCmdLineParser_UseAuxExceptions to achieve this.
}
{$IF Defined(SimpleCmdLineParser_UseAuxExceptions)}
{$DEFINE UseAuxExceptions}
{$IFEND}
//------------------------------------------------------------------------------
{$IF Defined(WINDOWS) or Defined(MSWINDOWS)}
{$DEFINE Windows}
{$ELSEIF Defined(LINUX) and Defined(FPC)}
{$DEFINE Linux}
{$ELSE}
{$MESSAGE FATAL 'Unsupported operating system.'}
{$IFEND}
{$IFDEF FPC}
{$MODE ObjFPC}
{$MODESWITCH DuplicateLocals+}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
{$H+}
interface
uses
SysUtils,
AuxClasses{$IFDEF UseAuxExceptions}, AuxExceptions{$ENDIF};
{===============================================================================
Library-specific exceptions
===============================================================================}
type
ESCLPException = class({$IFDEF UseAuxExceptions}EAEGeneralException{$ELSE}Exception{$ENDIF});
ESCLPIndexOutOfBounds = class(ESCLPException);
ESCLPInvalidValue = class(ESCLPException);
ESCLPInvalidState = class(ESCLPException);
{===============================================================================
--------------------------------------------------------------------------------
TSimpleCmdLineParser
--------------------------------------------------------------------------------
===============================================================================}
type
// note that ptCommandBoth is only used when returning command data
TSCLPParamType = (ptGeneral,ptCommandShort,ptCommandLong,ptCommandBoth);
TSCLPParameter = record
ParamType: TSCLPParamType;
Str: String;
Arguments: array of String;
end;
{===============================================================================
TSimpleCmdLineParser - class declaration
===============================================================================}
type
TSimpleCmdLineParser = class(TCustomListObject)
protected
// data
fCommandLine: String;
fImagePath: String;
fParameters: array of TSCLPParameter;
fCount: Integer;
fCommandCount: Integer;
Function GetParameter(Index: Integer): TSCLPParameter; virtual;
// list methods
Function GetCapacity: Integer; override;
procedure SetCapacity(Value: Integer); override;
Function GetCount: Integer; override;
procedure SetCount(Value: Integer); override;
// parameter list manipulation
Function AddParam(ParamType: TSCLPParamType; const Str: String): Integer; virtual;
class procedure AddParamArgument(var Param: TSCLPParameter; const Arg: String); overload; virtual;
procedure AddParamArgument(Index: Integer; const Arg: String); overload; virtual;
// init/final
procedure Initialize; virtual;
procedure Finalize; virtual;
public
class Function CommandLinePreprocess(const CommandLine: String): String; virtual;
class Function ArgumentPreprocess(const Argument: String): String; virtual;
class Function GetCommandLine: String; virtual;
constructor CreateEmpty;
constructor Create(const CommandLine: String); overload;
// following overload parses command line of the current program
constructor Create{$IFNDEF FPC}(Dummy: Integer = 0){$ENDIF}; overload;
destructor Destroy; override;
Function LowIndex: Integer; override;
Function HighIndex: Integer; override;
Function First: TSCLPParameter; virtual;
Function Last: TSCLPParameter; virtual;
Function IndexOf(const Str: String; CaseSensitive: Boolean): Integer; virtual;
Function Find(const Str: String; CaseSensitive: Boolean; out Index: Integer): Boolean; virtual;
{
CommandPresentShort
Returns true when given short command is present at least once, false
otherwise.
}
Function CommandPresentShort(ShortForm: Char): Boolean; virtual;
{
CommandPresentLong
Returns true when given long command is present at least once, false
otherwise.
}
Function CommandPresentLong(const LongForm: String): Boolean; virtual;
{
CommandPresent
Returns true when either short or long form of selected command is present
at least once, false otherwise.
}
Function CommandPresent(ShortForm: Char; const LongForm: String): Boolean; virtual;
{
CommandDataShort
Returns true when selected short form command is present, false otherwise.
When successfull, CommandData is set to selected short form string and
type is set to ptCommandShort. It will also contain arguments from all
occurences of selected command, in the order they appear in the command
line.
When not successfull, content of CommandData is undefined.
}
Function CommandDataShort(ShortForm: Char; out CommandData: TSCLPParameter): Boolean; virtual;
{
CommandDataLong
Returns true when selected long form command is present, false otherwise.
When successfull, CommandData is set to selected long form string and
type is set to ptCommandLong. It will also contain arguments from all
occurences of selected command, in the order they appear in the command
line.
When not successfull, content of CommandData is undefined.
}
Function CommandDataLong(const LongForm: String; out CommandData: TSCLPParameter): Boolean; virtual;
{
CommandData
Returns true when either long form or short form of selected command is
present, false otherwise.
When successfull, CommandData will also contain arguments from all
occurences of selected command, in the order they appear in the command
line. Type and string is set to short form when only short form is present,
to long form when only long form is present. When both forms are present,
then the string is set to a long form and type is set to ptCommandBoth.
When not successfull, content of CommandData is undefined.
}
Function CommandData(ShortForm: Char; const LongForm: String; out CommandData: TSCLPParameter): Boolean; virtual;
procedure Clear; virtual;
procedure Parse(const CommandLine: String); overload; virtual;
// following overload parses command line of the current program
procedure Parse; overload; virtual;
property CommandLine: String read fCommandLine;
property ImagePath: String read fImagePath;
property Parameters[Index: Integer]: TSCLPParameter read GetParameter; default;
{
CommandCount
Returns number of commands (both long and short) in parameter list, as
opposed to property Count, which indicates number of all parameters.
DO NOT use this number to iterate trough property Parameters.
}
property CommandCount: Integer read fCommandCount;
end;
{===============================================================================
TSimpleCmdLineParser - class aliases
===============================================================================}
type
TSimpleCommandLineParser = TSimpleCmdLineParser;
TSCLPParser = TSimpleCmdLineParser; // for backward compatibility
TSCLParser = TSimpleCmdLineParser;
implementation
uses
{$IFDEF Windows}Windows,{$ENDIF} Math,
AuxTypes, StrRect;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W5024:={$WARN 5024 OFF}} // Parameter "$1" not used
{$ENDIF}
{===============================================================================
--------------------------------------------------------------------------------
TSCLPLexer
--------------------------------------------------------------------------------
===============================================================================}
type
TSCLPLexerTokenType = (lttGeneral,lttCommandShort,lttCommandLong);
TSCLPLexerToken = record
TokenType: TSCLPLexerTokenType;
OriginalStr: String; // unprocessed string, as it appears in the command line
Position: Integer; // position of the token in command line string
Str: String; // processed text of the token
end;
TSCLPLexerCharType = (lctWhiteSpace,lctCommandIntro,lctQuoteSingle,
lctQuoteDouble,lctEscape,lctOther);
TSCLPLexerState = (lsStart,lsWhiteSpace,lsCommandIntro,lsCommandIntroDouble,
lsCommandShort,lsCommandLong,lsQuotedSingle,lsQuotedDouble,
lsEscape,lsEscapeQuotedSingle,lsEscapeQuotedDouble,lsText);
const
SCLP_CHAR_CMDINTRO = '-';
SCLP_CHAR_QUOTESINGLE = '''';
SCLP_CHAR_QUOTEDOUBLE = '"';
SCLP_CHAR_ESCAPE = '\';
SCLP_CHARS_WHITESPACE = [#0..#32];
SCLP_CHARS_COMMANDSHORT = ['a'..'z','A'..'Z'];
SCLP_CHARS_COMMANDLONG = ['a'..'z','A'..'Z','0'..'9','_','-'];
{===============================================================================
TSCLPLexer - class declaration
===============================================================================}
type
TSCLPLexer = class(TCustomListObject)
protected
// data
fCommandLine: String;
fTokens: array of TSCLPLexerToken;
fCount: Integer;
// lexing variables
fState: TSCLPLexerState;
fPosition: TStrOff;
fTokenStart: TStrOff;
fTokenLength: TStrSize;
// getters, setters
Function GetToken(Index: Integer): TSCLPLexerToken; virtual;
// inherited list methods
Function GetCapacity: Integer; override;
procedure SetCapacity(Value: Integer); override;
Function GetCount: Integer; override;
procedure SetCount(Value: Integer); override;
// lexing
Function CurrCharType: TSCLPLexerCharType; virtual;
procedure ChangeStateAndAdvance(NewState: TSCLPLexerState); virtual;
procedure AddToken(TokenType: TSCLPLexerTokenType); virtual;
procedure Process_Start; virtual;
procedure Process_WhiteSpace; virtual;
procedure Process_CommandIntro; virtual;
procedure Process_CommandIntroDouble; virtual;
procedure Process_CommandShort; virtual;
procedure Process_CommandLong; virtual;
procedure Process_QuotedSingle; virtual;
procedure Process_QuotedDouble; virtual;
procedure Process_Escape; virtual;
procedure Process_EscapeQuotedSingle; virtual;
procedure Process_EscapeQuotedDouble; virtual;
procedure Process_Text; virtual;
// init/final
procedure Initialize; virtual;
procedure Finalize; virtual;
public
constructor Create;
destructor Destroy; override;
Function LowIndex: Integer; override;
Function HighIndex: Integer; override;
procedure Analyze(const CommandLine: String); virtual;
procedure Clear; virtual;
property Tokens[Index: Integer]: TSCLPLexerToken read GetToken; default;
property CommandLine: String read fCommandLine;
end;
{===============================================================================
TSCLPLexer - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TSCLPLexer - protected methods
-------------------------------------------------------------------------------}
Function TSCLPLexer.GetToken(Index: Integer): TSCLPLexerToken;
begin
If CheckIndex(Index) then
Result := fTokens[Index]
else
raise ESCLPIndexOutOfBounds.CreateFmt('TSCLPLexer.GetToken: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
Function TSCLPLexer.GetCapacity: Integer;
begin
Result := Length(fTokens);
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.SetCapacity(Value: Integer);
begin
If Value >= 0 then
begin
If Value <> Length(fTokens) then
begin
SetLength(fTokens,Value);
If Value < fCount then
fCount := Value
end;
end
else raise ESCLPInvalidValue.CreateFmt('TSCLPLexer.SetCapacity: Invalid capacity (%d).',[Value]);
end;
//------------------------------------------------------------------------------
Function TSCLPLexer.GetCount: Integer;
begin
Result := fCount;
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W5024{$ENDIF}
procedure TSCLPLexer.SetCount(Value: Integer);
begin
// do nothing
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//------------------------------------------------------------------------------
Function TSCLPLexer.CurrCharType: TSCLPLexerCharType;
begin
If CharInSet(fCommandLine[fPosition],SCLP_CHARS_WHITESPACE) then
Result := lctWhiteSpace
else If fCommandLine[fPosition] = SCLP_CHAR_CMDINTRO then
Result := lctCommandIntro
else If fCommandLine[fPosition] = SCLP_CHAR_QUOTESINGLE then
Result := lctQuoteSingle
else If fCommandLine[fPosition] = SCLP_CHAR_QUOTEDOUBLE then
Result := lctQuoteDouble
else If fCommandLine[fPosition] = SCLP_CHAR_ESCAPE then
Result := lctEscape
else
Result := lctOther;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.ChangeStateAndAdvance(NewState: TSCLPLexerState);
begin
fState := NewState;
Inc(fTokenLength);
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.AddToken(TokenType: TSCLPLexerTokenType);
Function PostprocessTokenString(const Str: String): String;
type
TQuoteState = (qsNone,qsSingle,qsDouble,qsEscape,qsEscapeSingle,qsEscapeDouble);
var
QuoteState: TQuoteState;
StrPos: TStrOff;
ResPos: TStrOff;
procedure CopyChar(NewQuoteState: TQuoteState);
begin
QuoteState := NewQuoteState;
Result[ResPos] := Str[StrPos];
Inc(StrPos);
Inc(ResPos);
end;
procedure ChageState(NewQuoteState: TQuoteState);
begin
QuoteState := NewQuoteState;
Inc(StrPos);
end;
begin
// note the resulting string will never be longer than the original
Result := '';
SetLength(Result,Length(Str));
QuoteState := qsNone;
StrPos := 1;
ResPos := 1;
while StrPos <= Length(Str) do
begin
case QuoteState of
qsNone: case Str[StrPos] of
SCLP_CHAR_QUOTESINGLE: ChageState(qsSingle);
SCLP_CHAR_QUOTEDOUBLE: ChageState(qsDouble);
SCLP_CHAR_ESCAPE: ChageState(qsEscape);
else
CopyChar(qsNone);
end;
qsSingle: case Str[StrPos] of
SCLP_CHAR_QUOTESINGLE: ChageState(qsNone);
SCLP_CHAR_ESCAPE: ChageState(qsEscapeSingle);
else
CopyChar(qsSingle);
end;
qsDouble: case Str[StrPos] of
SCLP_CHAR_QUOTEDOUBLE: ChageState(qsNone);
SCLP_CHAR_ESCAPE: ChageState(qsEscapeDouble);
else
CopyChar(qsDouble);
end;
qsEscape: CopyChar(qsNone);
qsEscapeSingle: CopyChar(qsSingle);
qsEscapeDouble: CopyChar(qsDouble);
end;
end;
If QuoteState in [qsEscape,qsEscapeSingle,qsEscapeDouble] then
begin
Result[ResPos] := SCLP_CHAR_ESCAPE;
SetLength(Result,ResPos);
end
else SetLength(Result,Pred(ResPos));
end;
var
i: Integer;
begin
If (TokenType = lttCommandShort) and (fTokenLength > 2) then
begin
// split compound short commands (eg. -abc -> -a -b -c)
Grow(Pred(fTokenLength));
For i := 0 to (fTokenLength - 2) do
begin
fTokens[fCount + i].TokenType := lttCommandShort;
If i <= 0 then
begin
fTokens[fCount + i].OriginalStr := Copy(fCommandLine,fTokenStart,2);
fTokens[fCount + i].Str := fCommandLine[fTokenStart + i + 1];
end
else
begin
fTokens[fCount + i].OriginalStr := fCommandLine[fTokenStart + i + 1];
fTokens[fCount + i].Str := fTokens[fCount + i].OriginalStr
end;
fTokens[fCount + i].Position := fTokenStart + i + 1;
end;
Inc(fCount,Pred(fTokenLength));
end
else
begin
Grow;
fTokens[fCount].TokenType := TokenType;
fTokens[fCount].OriginalStr := Copy(fCommandLine,fTokenStart,fTokenLength);
fTokens[fCount].Position := fTokenStart;
case TokenType of
lttGeneral: fTokens[fCount].Str := PostprocessTokenString(fTokens[fCount].OriginalStr);
lttCommandShort: fTokens[fCount].Str := fCommandLine[fTokenStart + 1];
lttCommandLong: fTokens[fCount].Str := Copy(fCommandLine,fTokenStart + 2,fTokenLength - 2);
end;
Inc(fCount);
end;
fTokenLength := 0;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_Start;
begin
fState := lsWhiteSpace;
fPosition := 0;
fTokenStart := 0;
fTokenLength := 0;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_WhiteSpace;
begin
case CurrCharType of
lctWhiteSpace:; // just continue
lctCommandIntro: begin
fState := lsCommandIntro;
fTokenStart := fPosition;
fTokenLength := 1;
end;
lctQuoteSingle: begin
fState := lsQuotedSingle;
fTokenStart := fPosition;
fTokenLength := 1;
end;
lctQuoteDouble: begin
fState := lsQuotedDouble;
fTokenStart := fPosition;
fTokenLength := 1;
end;
lctEscape: begin
fState := lsEscape;
fTokenStart := fPosition;
fTokenLength := 1;
end;
lctOther: begin
fState := lsText;
fTokenStart := fPosition;
fTokenLength := 1;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_CommandIntro;
begin
case CurrCharType of
lctWhiteSpace: begin
AddToken(lttGeneral);
fState := lsWhiteSpace;
end;
lctCommandIntro: ChangeStateAndAdvance(lsCommandIntroDouble);
lctQuoteSingle: ChangeStateAndAdvance(lsQuotedSingle);
lctQuoteDouble: ChangeStateAndAdvance(lsQuotedDouble);
lctEscape: ChangeStateAndAdvance(lsEscape);
lctOther: begin
If CharInSet(fCommandLine[fPosition],SCLP_CHARS_COMMANDSHORT) then
fState := lsCommandShort
else
fState := lsText;
Inc(fTokenLength);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_CommandIntroDouble;
begin
case CurrCharType of
lctWhiteSpace: begin
AddToken(lttGeneral);
fState := lsWhiteSpace;
end;
lctCommandIntro: ChangeStateAndAdvance(lsText);
lctQuoteSingle: ChangeStateAndAdvance(lsQuotedSingle);
lctQuoteDouble: ChangeStateAndAdvance(lsQuotedDouble);
lctEscape: ChangeStateAndAdvance(lsEscape);
lctOther: begin
If CharInSet(fCommandLine[fPosition],SCLP_CHARS_COMMANDLONG) then
fState := lsCommandLong
else
fState := lsText;
Inc(fTokenLength);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_CommandShort;
begin
case CurrCharType of
lctWhiteSpace: begin
AddToken(lttCommandShort);
fState := lsWhiteSpace;
end;
lctCommandIntro: ChangeStateAndAdvance(lsText);
lctQuoteSingle: ChangeStateAndAdvance(lsQuotedSingle);
lctQuoteDouble: ChangeStateAndAdvance(lsQuotedDouble);
lctEscape: ChangeStateAndAdvance(lsEscape);
lctOther: begin
If not CharInSet(fCommandLine[fPosition],SCLP_CHARS_COMMANDSHORT) then
fState := lsText;
Inc(fTokenLength);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_CommandLong;
begin
case CurrCharType of
lctWhiteSpace: begin
AddToken(lttCommandLong);
fState := lsWhiteSpace;
end;
lctQuoteSingle: ChangeStateAndAdvance(lsQuotedSingle);
lctQuoteDouble: ChangeStateAndAdvance(lsQuotedDouble);
lctEscape: ChangeStateAndAdvance(lsEscape);
lctCommandIntro,
lctOther: begin
If not CharInSet(fCommandLine[fPosition],SCLP_CHARS_COMMANDLONG) then
fState := lsText;
Inc(fTokenLength);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_QuotedSingle;
begin
case CurrCharType of
lctQuoteSingle: ChangeStateAndAdvance(lsText);
lctEscape: ChangeStateAndAdvance(lsEscapeQuotedSingle);
else
{lctWhiteSpace,lctCommandIntro,lctQuoteDouble,lctOther}
Inc(fTokenLength);
end;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_QuotedDouble;
begin
case CurrCharType of
lctQuoteDouble: ChangeStateAndAdvance(lsText);
lctEscape: ChangeStateAndAdvance(lsEscapeQuotedDouble);
else
{lctWhiteSpace,lctCommandIntro,lctQuoteSingle,lctOther}
Inc(fTokenLength);
end;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_Escape;
begin
ChangeStateAndAdvance(lsText);
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_EscapeQuotedSingle;
begin
ChangeStateAndAdvance(lsQuotedSingle);
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_EscapeQuotedDouble;
begin
ChangeStateAndAdvance(lsQuotedDouble);
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Process_Text;
begin
case CurrCharType of
lctWhiteSpace: begin
AddToken(lttGeneral);
fState := lsWhiteSpace;
end;
lctQuoteSingle: ChangeStateAndAdvance(lsQuotedSingle);
lctQuoteDouble: ChangeStateAndAdvance(lsQuotedDouble);
lctEscape: ChangeStateAndAdvance(lsEscape)
else
{lctCommandIntro,lctOther}
Inc(fTokenLength);
end;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Initialize;
begin
fCommandLine := '';
SetLength(fTokens,0);
fCount := 0;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Finalize;
begin
Clear;
end;
{-------------------------------------------------------------------------------
TSCLPLexer - public methods
-------------------------------------------------------------------------------}
constructor TSCLPLexer.Create;
begin
inherited;
Initialize;
end;
//------------------------------------------------------------------------------
destructor TSCLPLexer.Destroy;
begin
Finalize;
inherited;
end;
//------------------------------------------------------------------------------
Function TSCLPLexer.LowIndex: Integer;
begin
Result := Low(fTokens);
end;
//------------------------------------------------------------------------------
Function TSCLPLexer.HighIndex: Integer;
begin
Result := Pred(fCount);
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Analyze(const CommandLine: String);
begin
Clear;
fCommandLine := CommandLine;
fState := lsStart;
fPosition := 0;
while fPosition <= Length(fCommandLine) do
begin
case fState of
lsStart: Process_Start;
lsWhiteSpace: Process_WhiteSpace;
lsCommandIntro: Process_CommandIntro;
lsCommandIntroDouble: Process_CommandIntroDouble;
lsCommandShort: Process_CommandShort;
lsCommandLong: Process_CommandLong;
lsQuotedSingle: Process_QuotedSingle;
lsQuotedDouble: Process_QuotedDouble;
lsEscape: Process_Escape;
lsEscapeQuotedSingle: Process_EscapeQuotedSingle;
lsEscapeQuotedDouble: Process_EscapeQuotedDouble;
lsText: Process_Text;
else
raise ESCLPInvalidState.CreateFmt('TSCLPLexer.Analyze: Invalid lexer state (%d).',[Ord(fState)]);
end;
Inc(fPosition);
end;
case fState of
lsCommandShort: AddToken(lttCommandShort);
lsCommandLong: AddToken(lttCommandLong);
lsCommandIntro,
lsCommandIntroDouble,
lsQuotedSingle,
lsQuotedDouble,
lsEscape,
lsEscapeQuotedSingle,
lsEscapeQuotedDouble,
lsText: AddToken(lttGeneral);
end;
end;
//------------------------------------------------------------------------------
procedure TSCLPLexer.Clear;
begin
fCommandLine := '';
SetLength(fTokens,0);
fCount := 0;
end;
{===============================================================================
--------------------------------------------------------------------------------
TSimpleCmdLineParser
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TSimpleCmdLineParser - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TSimpleCmdLineParser - protected methods
-------------------------------------------------------------------------------}
Function TSimpleCmdLineParser.GetParameter(Index: Integer): TSCLPParameter;
begin
If CheckIndex(Index) then
Result := fParameters[Index]
else
raise ESCLPIndexOutOfBounds.CreateFmt('TSimpleCmdLineParser.GetParameter: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
Function TSimpleCmdLineParser.GetCapacity: Integer;
begin
Result := Length(fParameters);
end;
//------------------------------------------------------------------------------
procedure TSimpleCmdLineParser.SetCapacity(Value: Integer);
begin