aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/TntUnicodeControls/TntFormatStrUtils.pas
blob: 80aefd4a5fa10a9248c766221d8883bad11b70e0 (plain) (blame)
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
{*****************************************************************************}
{                                                                             }
{    Tnt Delphi Unicode Controls                                              }
{      http://www.tntware.com/delphicontrols/unicode/                         }
{        Version: 2.3.0                                                       }
{                                                                             }
{    Copyright (c) 2002-2007, Troy Wolbrink (troy.wolbrink@tntware.com)       }
{                                                                             }
{*****************************************************************************}

unit TntFormatStrUtils;

{$IFDEF FPC}
  {$MODE Delphi}
{$ENDIF}

{$INCLUDE TntCompilers.inc}

interface

// this unit provides functions to work with format strings

uses
  TntSysUtils;

function GetCanonicalFormatStr(const _FormatString: WideString): WideString;

{$IFNDEF FPC}
{$IFNDEF COMPILER_9_UP}
function ReplaceFloatingArgumentsInFormatString(const _FormatString: WideString;
  const Args: array of const
    {$IFDEF COMPILER_7_UP}; FormatSettings: PFormatSettings{$ENDIF}): WideString;
{$ENDIF}
{$ENDIF}
procedure CompareFormatStrings(FormatStr1, FormatStr2: WideString);
function FormatStringsAreCompatible(FormatStr1, FormatStr2: WideString): Boolean;

type
  EFormatSpecError = class(ETntGeneralError);

implementation

uses
  SysUtils, Math, TntClasses;

resourcestring
  SInvalidFormatSpecifier = 'Invalid Format Specifier: %s';
  SMismatchedArgumentTypes = 'Argument types for index %d do not match. (%s <> %s)';
  SMismatchedArgumentCounts = 'Number of format specifiers do not match.';

type
  TFormatSpecifierType = (fstInteger, fstFloating, fstPointer, fstString);

function GetFormatSpecifierType(const FormatSpecifier: WideString): TFormatSpecifierType;
var
  LastChar: WideChar;
begin
  LastChar := TntWideLastChar(FormatSpecifier);
  case LastChar of
    'd', 'D', 'u', 'U', 'x', 'X':
      result := fstInteger;
    'e', 'E', 'f', 'F', 'g', 'G', 'n', 'N', 'm', 'M':
      result := fstFloating;
    'p', 'P':
      result := fstPointer;
    's', 'S':
      result := fstString
    else
      raise ETntInternalError.CreateFmt('Internal Error: Unexpected format type (%s)', [LastChar]);
  end;
end;

type
  TFormatStrParser = class(TObject)
  private
    ParsedString: TBufferedWideString;
    PFormatString: PWideChar;
    LastIndex: Integer;
    ExplicitCount: Integer;
    ImplicitCount: Integer;
    procedure RaiseInvalidFormatSpecifier;
    function ParseChar(c: WideChar): Boolean;
    procedure ForceParseChar(c: WideChar);
    function ParseDigit: Boolean;
    function ParseInteger: Boolean;
    procedure ForceParseType;
    function PeekDigit: Boolean;
    function PeekIndexSpecifier(out Index: Integer): Boolean;
  public
    constructor Create(const _FormatString: WideString);
    destructor Destroy; override;
    function ParseFormatSpecifier: Boolean;
  end;

constructor TFormatStrParser.Create(const _FormatString: WideString);
begin
  inherited Create;
  PFormatString := PWideChar(_FormatString);
  ExplicitCount := 0;
  ImplicitCount := 0;
  LastIndex := -1;
  ParsedString := TBufferedWideString.Create;
end;

destructor TFormatStrParser.Destroy;
begin
  FreeAndNil(ParsedString);
  inherited;
end;

procedure TFormatStrParser.RaiseInvalidFormatSpecifier;
begin
  raise EFormatSpecError.CreateFmt(SInvalidFormatSpecifier, [ParsedString.Value + PFormatString]);
end;

function TFormatStrParser.ParseChar(c: WideChar): Boolean;
begin
  result := False;
  if PFormatString^ = c then begin
    result := True;
    ParsedString.AddChar(c);
    Inc(PFormatString);
  end;
end;

procedure TFormatStrParser.ForceParseChar(c: WideChar);
begin
  if not ParseChar(c) then
    RaiseInvalidFormatSpecifier;
end;

function TFormatStrParser.PeekDigit: Boolean;
begin
  result := False;
  if  (PFormatString^ <> #0)
  and (PFormatString^ >= '0')
  and (PFormatString^ <= '9') then
    result := True;
end;

function TFormatStrParser.ParseDigit: Boolean;
begin
  result := False;
  if PeekDigit then begin
    result := True;
    ForceParseChar(PFormatString^);
  end;
end;

function TFormatStrParser.ParseInteger: Boolean;
const
  MAX_INT_DIGITS = 6;
var
  digitcount: integer;
begin
  digitcount := 0;
  While ParseDigit do begin
    inc(digitcount);
  end;
  result := (digitcount > 0);
  if digitcount > MAX_INT_DIGITS then
    RaiseInvalidFormatSpecifier;
end;

procedure TFormatStrParser.ForceParseType;
begin
  if PFormatString^ = #0 then
    RaiseInvalidFormatSpecifier;

  case PFormatString^ of
    'd', 'u', 'x', 'e', 'f', 'g', 'n', 'm', 'p', 's',
    'D', 'U', 'X', 'E', 'F', 'G', 'N', 'M', 'P', 'S':
  begin
    // do nothing
  end
  else
    RaiseInvalidFormatSpecifier;
  end;
  ForceParseChar(PFormatString^);
end;

function TFormatStrParser.PeekIndexSpecifier(out Index: Integer): Boolean;
var
  SaveParsedString: WideString;
  SaveFormatString: PWideChar;
begin
  SaveParsedString := ParsedString.Value;
  SaveFormatString := PFormatString;
  try
    ParsedString.Clear;
    Result := False;
    Index := -1;
    if ParseInteger then begin
      Index := StrToInt(ParsedString.Value);
      if ParseChar(':') then
        Result := True;
    end;
  finally
    ParsedString.Clear;
    ParsedString.AddString(SaveParsedString);
    PFormatString := SaveFormatString;
  end;
end;

function TFormatStrParser.ParseFormatSpecifier: Boolean;
var
  ExplicitIndex: Integer;
begin
  Result := False;
  // Parse entire format specifier
  ForceParseChar('%');
  if (PFormatString^ <> #0)
  and (not ParseChar(' '))
  and (not ParseChar('%')) then begin
    if PeekIndexSpecifier(ExplicitIndex) then begin
      Inc(ExplicitCount);
      LastIndex := Max(LastIndex, ExplicitIndex);
    end else begin
      Inc(ImplicitCount);
      Inc(LastIndex);
      ParsedString.AddString(IntToStr(LastIndex));
      ParsedString.AddChar(':');
    end;
    if ParseChar('*') then
    begin
      Inc(ImplicitCount);
      Inc(LastIndex);
      ParseChar(':');
    end else if ParseInteger then
      ParseChar(':');
    ParseChar('-');
    if ParseChar('*') then begin
      Inc(ImplicitCount);
      Inc(LastIndex);
    end else
      ParseInteger;
    if ParseChar('.') then begin
      if not ParseChar('*') then
        ParseInteger;
    end;
    ForceParseType;
    Result := True;
  end;
end;

//-----------------------------------

function GetCanonicalFormatStr(const _FormatString: WideString): WideString;
var
  PosSpec: Integer;
begin
  with TFormatStrParser.Create(_FormatString) do
  try
    // loop until no more '%'
    PosSpec := Pos(WideString('%'), PFormatString);
    While PosSpec <> 0 do begin
      try
        // delete everything up until '%'
        ParsedString.AddBuffer(PFormatString, PosSpec - 1);
        Inc(PFormatString, PosSpec - 1);
        // parse format specifier
        ParseFormatSpecifier;
      finally
        PosSpec := Pos(WideString('%'), PFormatString);
      end;
    end;
    if ((ExplicitCount = 0) and (ImplicitCount = 1)) {simple expression}
    or ((ExplicitCount > 0) and (ImplicitCount = 0)) {nothing converted} then
      result := _FormatString {original}
    else
      result := ParsedString.Value + PFormatString;
  finally
    Free;
  end;
end;

{$IFNDEF FPC}
{$IFNDEF COMPILER_9_UP}
function ReplaceFloatingArgumentsInFormatString(const _FormatString: WideString;
  const Args: array of const
    {$IFDEF COMPILER_7_UP}; FormatSettings: PFormatSettings{$ENDIF}): WideString;
{ This function replaces floating point format specifiers with their actual formatted values.
  It also adds index specifiers so that the other format specifiers don't lose their place.
  The reason for this is that WideFormat doesn't correctly format floating point specifiers.
  See QC#4254. }
var
  Parser: TFormatStrParser;
  PosSpec: Integer;
  Output: TBufferedWideString;
begin
  Output := TBufferedWideString.Create;
  try
    Parser := TFormatStrParser.Create(_FormatString);
    with Parser do
    try
      // loop until no more '%'
      PosSpec := Pos('%', PFormatString);
      While PosSpec <> 0 do begin
        try
          // delete everything up until '%'
          Output.AddBuffer(PFormatString, PosSpec - 1);
          Inc(PFormatString, PosSpec - 1);
          // parse format specifier
          ParsedString.Clear;
          if (not ParseFormatSpecifier)
          or (GetFormatSpecifierType(ParsedString.Value) <> fstFloating) then
            Output.AddBuffer(ParsedString.BuffPtr, MaxInt)
          {$IFDEF COMPILER_7_UP}
          else if Assigned(FormatSettings) then
            Output.AddString(Format{TNT-ALLOW Format}(ParsedString.Value, Args, FormatSettings^))
          {$ENDIF}
          else
            Output.AddString(Format{TNT-ALLOW Format}(ParsedString.Value, Args));
        finally
          PosSpec := Pos('%', PFormatString);
        end;
      end;
      Output.AddString(PFormatString);
    finally
      Free;
    end;
    Result := Output.Value;
  finally
    Output.Free;
  end;
end;
{$ENDIF}
{$ENDIF}

procedure GetFormatArgs(const _FormatString: WideString; FormatArgs: TTntStrings);
var
  PosSpec: Integer;
begin
  with TFormatStrParser.Create(_FormatString) do
  try
    FormatArgs.Clear;
    // loop until no more '%'
    PosSpec := Pos(WideString('%'), PFormatString);
    While PosSpec <> 0 do begin
      try
        // delete everything up until '%'
        Inc(PFormatString, PosSpec - 1);
        // add format specifier to list
        ParsedString.Clear;
        if ParseFormatSpecifier then
          FormatArgs.Add(ParsedString.Value);
      finally
        PosSpec := Pos(WideString('%'), PFormatString);
      end;
    end;
  finally
    Free;
  end;
end;

function GetExplicitIndex(const FormatSpecifier: WideString): Integer;
var
  IndexStr: WideString;
  PosColon: Integer;
begin
  result := -1;
  PosColon := Pos(':', FormatSpecifier);
  if PosColon <> 0 then begin
    IndexStr := Copy(FormatSpecifier, 2, PosColon - 2);
    result := StrToInt(IndexStr);
  end;
end;

function GetMaxIndex(FormatArgs: TTntStrings): Integer;
var
  i: integer;
  RunningIndex: Integer;
  ExplicitIndex: Integer;
begin
  result := -1;
  RunningIndex := -1;
  for i := 0 to FormatArgs.Count - 1 do begin
    ExplicitIndex := GetExplicitIndex(FormatArgs[i]);
    if ExplicitIndex <> -1 then
      RunningIndex := ExplicitIndex
    else
      inc(RunningIndex);
    result := Max(result, RunningIndex);
  end;
end;

function FormatSpecToObject(SpecType: TFormatSpecifierType): TObject;
begin
  {$IFNDEF FPC}
  Result := TObject(SpecType);
  {$ELSE}
  Result := Pointer(SpecType);
  {$ENDIF}
end;

procedure UpdateTypeList(FormatArgs, TypeList: TTntStrings);
var
  i: integer;
  f: WideString;
  SpecType: TFormatSpecifierType;
  ExplicitIndex: Integer;
  MaxIndex: Integer;
  RunningIndex: Integer;
begin
  // set count of TypeList to accomodate maximum index
  MaxIndex := GetMaxIndex(FormatArgs);
  TypeList.Clear;
  for i := 0 to MaxIndex do
    TypeList.Add('');

  // for each arg...
  RunningIndex := -1;
  for i := 0 to FormatArgs.Count - 1 do begin
    f := FormatArgs[i];
    ExplicitIndex := GetExplicitIndex(f);
    SpecType := GetFormatSpecifierType(f);

    // determine running arg index
    if ExplicitIndex <> -1 then
      RunningIndex := ExplicitIndex
    else
      inc(RunningIndex);

    if TypeList[RunningIndex] <> '' then begin
      // already exists in list, check for compatibility
      if TypeList.Objects[RunningIndex] <> FormatSpecToObject(SpecType) then
        raise EFormatSpecError.CreateFmt(SMismatchedArgumentTypes,
          [RunningIndex, TypeList[RunningIndex], f]);
    end else begin
      // not in list so update it
      TypeList[RunningIndex] := f;
      TypeList.Objects[RunningIndex] := FormatSpecToObject(SpecType);
    end;
  end;
end;

procedure CompareFormatStrings(FormatStr1, FormatStr2: WideString);
var
  ArgList1: TTntStringList;
  ArgList2: TTntStringList;
  TypeList1: TTntStringList;
  TypeList2: TTntStringList;
  i: integer;
begin
  ArgList1 := nil;
  ArgList2 := nil;
  TypeList1 := nil;
  TypeList2 := nil;
  try
    ArgList1 := TTntStringList.Create;
    ArgList2 := TTntStringList.Create;
    TypeList1 := TTntStringList.Create;
    TypeList2 := TTntStringList.Create;

    GetFormatArgs(FormatStr1, ArgList1);
    UpdateTypeList(ArgList1, TypeList1);

    GetFormatArgs(FormatStr2, ArgList2);
    UpdateTypeList(ArgList2, TypeList2);

    if TypeList1.Count <> TypeList2.Count then
      raise EFormatSpecError.Create(SMismatchedArgumentCounts + CRLF + CRLF + '> ' + FormatStr1 + CRLF + '> ' + FormatStr2);

    for i := 0 to TypeList1.Count - 1 do begin
      if TypeList1.Objects[i] <> TypeList2.Objects[i] then begin
        raise EFormatSpecError.CreateFmt(SMismatchedArgumentTypes,
          [i, TypeList1[i], TypeList2[i]]);
      end;
    end;

  finally
    ArgList1.Free;
    ArgList2.Free;
    TypeList1.Free;
    TypeList2.Free;
  end;
end;

function FormatStringsAreCompatible(FormatStr1, FormatStr2: WideString): Boolean;
var
  ArgList1: TTntStringList;
  ArgList2: TTntStringList;
  TypeList1: TTntStringList;
  TypeList2: TTntStringList;
  i: integer;
begin
  ArgList1 := nil;
  ArgList2 := nil;
  TypeList1 := nil;
  TypeList2 := nil;
  try
    ArgList1 := TTntStringList.Create;
    ArgList2 := TTntStringList.Create;
    TypeList1 := TTntStringList.Create;
    TypeList2 := TTntStringList.Create;

    GetFormatArgs(FormatStr1, ArgList1);
    UpdateTypeList(ArgList1, TypeList1);

    GetFormatArgs(FormatStr2, ArgList2);
    UpdateTypeList(ArgList2, TypeList2);

    Result := (TypeList1.Count = TypeList2.Count);
    if Result then begin
      for i := 0 to TypeList1.Count - 1 do begin
        if TypeList1.Objects[i] <> TypeList2.Objects[i] then begin
          Result := False;
          break;
        end;
      end;
    end;
  finally
    ArgList1.Free;
    ArgList2.Free;
    TypeList1.Free;
    TypeList2.Free;
  end;
end;

end.