File: Converter.pas

package info (click to toggle)
lazarus 4.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 275,760 kB
  • sloc: pascal: 2,341,904; xml: 509,420; makefile: 348,726; cpp: 93,608; sh: 3,387; java: 609; perl: 297; sql: 222; ansic: 137
file content (592 lines) | stat: -rw-r--r-- 18,641 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
{(*}
(*------------------------------------------------------------------------------
 Delphi Code formatter source code

The Original Code is Converter.pas, released April 2000.
The Initial Developer of the Original Code is Anthony Steele. 
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.

The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.

Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL") 
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}

unit Converter;

{
  5 July 2004
  Rewrote as a simpler sting->string converter.
  For file or ide, there will be wrapper classes not subclasses.
  Wrappers will also support the interface IConvert
}

{$mode delphi}

interface

uses
  SysUtils, strutils, LazFileUtils,
  // local
  ConvertTypes, ParseTreeNode, BuildTokenList, BuildParseTree, BaseVisitor;

type

  TOnIncludeFile=procedure(Sender:TObject;AIncludeFileName:string;var AFileContentOrErrorMessage:string;var AFileReaded:boolean) of object;

  TConverter = class(TObject)
  private
    { the strings for the in and out code }
    fsInputCode, fsOutputCode: String;
    fsFileName: String;
    fiFirstLineNumber: integer;  //used by ConvertUsingFakeUnit

    { classes to lex and parse the source }
    fcTokeniser:      TBuildTokenList;
    fcBuildParseTree: TBuildParseTree;

    { used for testing - just run 1 process }
    fcSingleProcess: TTreeNodeVisitorType;

    { state }
    fiTokenCount:     Integer;
    fbConvertError:   Boolean;
    fOnStatusMessage: TStatusMessageProc;

    { false for commandline UI - don't put up a parse fail dialog
      This could be in  batch file on a server }
    fbGuiMessages: Boolean;
    fbShowParseTree: Boolean;

    fOnIncludeFile:TOnIncludeFile;
    function GetOnStatusMessage: TStatusMessageProc;
    procedure SetOnStatusMessage(const Value: TStatusMessageProc);

    procedure SendExceptionMessage(const pe: Exception);
    procedure ShowParseTree;
    function GetRoot: TParseTreeNode;

    { this does the reformatting. Virtual method so can be overriden for testing }
    procedure ApplyProcesses;
    procedure ApplySingleProcess;

  public
    constructor Create;
    destructor Destroy; override;

    procedure Clear;
    procedure Convert;
    procedure ConvertPart(const piStartIndex, piEndIndex: Integer;
                          aOnlyOutputSelection: boolean=false);
    procedure ConvertUsingFakeUnit(AFirstLineNumber:integer = 1);

    procedure CollectOutput(const pcRoot: TParseTreeNode);
    { call this to report the current state of the proceedings }
    procedure SendStatusMessage(const psUnit, psMessage: String; const peMessageType: TStatusMessageType; const piY, piX: Integer);
    property InputCode: String Read fsInputCode Write fsInputCode;
    property OutputCode: String Read fsOutputCode Write fsOutputCode;
    property FileName: String Read fsFileName Write fsFileName;

    property TokenCount: Integer Read fiTokenCount;
    property ConvertError: Boolean Read fbConvertError;
    property GuiMessages: Boolean Read fbGuiMessages Write fbGuiMessages;

    property Root: TParseTreeNode Read GetRoot;

    property OnStatusMessage: TStatusMessageProc Read GetOnStatusMessage Write SetOnStatusMessage;
    property SingleProcess: TTreeNodeVisitorType Read fcSingleProcess Write fcSingleProcess;
    property ShowTree: boolean Read fbShowParseTree Write fbShowParseTree;
    property OnIncludeFile: TOnIncludeFile Read fOnIncludeFile Write fOnIncludeFile;
  end;

const
  FORMAT_START = '{<JCF_!*$>}';
  FORMAT_END   = '{</JCF_!*$>}';

implementation

uses
  AllProcesses,
  JcfRegistrySettings,
  JcfSettings, JcfStringUtils, ParseError, PreProcessorParseTree,
  SourceToken, SourceTokenList, TreeWalker, VisitSetNesting, VisitSetXY, JcfUiTools, jcfbaseConsts;

function StrInsert(const psSub, psMain: String; const piPos: Integer): String;
begin
  Result := StrLeft(psMain, piPos - 1) + psSub + StrRestOf(psMain, piPos);
end;


constructor TConverter.Create;
begin
  inherited;

  { owned objects }
  fcTokeniser      := TBuildTokenList.Create;
  fcTokeniser.FileName := FileName;
  fcBuildParseTree := TBuildParseTree.Create;
  fcSingleProcess  := nil;
  fbGuiMessages    := True; // use Ui to show parse errors by default
  fiFirstLineNumber := 1;
end;

destructor TConverter.Destroy;
begin
  FreeAndNil(fcTokeniser);
  FreeAndNil(fcBuildParseTree);

  inherited;
end;

procedure TConverter.Clear;
begin
  fsInputCode     := '';
  fsOutputCode    := '';
  fcSingleProcess := nil;
end;

procedure TConverter.Convert;
var
  lcTokenList: TSourceTokenList;
begin
  fbConvertError := False;
  try { finally normal cursor }
    // this can take a long time for large files
    GetUI.SetWaitCursorUI;


    // turn text into tokens
    fcTokeniser.SourceCode := InputCode;
    fcTokeniser.FileName   := FileName;
    lcTokenList := TSourceTokenList.Create;
    try
      fcTokeniser.BuildTokenList(lcTokenList);
    except
      on ETW: EBuildTokenListWarning do
      begin
        SendStatusMessage('', Format(lisMsgWarningClassMsg, ['', ETW.Message]), mtCodeWarning, -1, -1);
      end;
      on EPR:TEParseError do
      begin
        fbConvertError := True;
        SendStatusMessage('', Format(lisMsgExceptionClassMsg, ['', EPR.Message]), mtException, EPR.YPosition, EPR.XPosition);
        Exit;
      end;
      on E: Exception do
      begin
        fbConvertError := True;
        SendStatusMessage('', Format(lisMsgExceptionClassMsg, ['', E.Message]), mtException, -1, -1);
        Exit;
      end;
    end;
    try   { finally free the list  }
      try { show exceptions }
        fiTokenCount := lcTokenList.Count;
        lcTokenList.SetXYPositions;

        // remove conditional compilation stuph
        if FormattingSettings.PreProcessor.Enabled then
          RemoveConditionalCompilation(Self,lcTokenList, fOnIncludeFile);

        // make a parse tree from it
        fcBuildParseTree.TokenList := lcTokenList;
        fcBuildParseTree.IsIncFile := FilenameExtIs(FileName, 'inc');
        fcBuildParseTree.BuildParseTree;
        if fbShowParseTree then
           ShowParseTree;
      except
        on E: Exception do
        begin
          fbConvertError := True;
          SendExceptionMessage(E);
          if GuiMessages and (GetRegSettings.ShowParseTreeOption = eShowOnError) then
            ShowParseTree;
        end;
      end;

      if fbConvertError then
      begin
        { if there was a parse error, the rest of the unit was not parsed
         there may still be tokens in the list
         Free them or face a small but annoying memory leak. }
        lcTokenList.OwnsObjects := True;
        lcTokenList.Clear;
      end;

      // should not be any tokens left
      Assert(lcTokenList.Count = 0, 'Surplus tokens');
    finally
      FreeAndNil(lcTokenList);
    end;

    try
      if not fbConvertError then
      begin
        if (GetRegSettings.ShowParseTreeOption = eShowAlways) then
          ShowParseTree;

        // do the processes
        if Assigned(fcSingleProcess) then
          ApplySingleProcess
        else
          ApplyProcesses;

        // assemble the output string
        fsOutputCode := '';
        CollectOutput(fcBuildParseTree.Root);
      end;
      fcBuildParseTree.Clear;
    except
      on E: Exception do
      begin
        fbConvertError := True;
        SendExceptionMessage(E);
      end;
    end;
  finally
    if lcTokenList<>nil then
    begin
      lcTokenList.OwnsObjects := True;
      lcTokenList.Clear;
      FreeAndNil(lcTokenList);
    end;
    GetUI.RestoreCursorUI;
  end;
end;

{ this is what alters the code (in parse tree form) from source to output }
procedure TConverter.ApplyProcesses;
var
  lcProcess: TAllProcesses;
begin
  lcProcess := TAllProcesses.Create;
  try
    lcProcess.OnMessage := SendStatusMessage;

    lcProcess.Execute(fcBuildParseTree.Root);
  finally
    lcProcess.Free;
  end;
end;

procedure TConverter.ApplySingleProcess;
var
  lcProcess:    TBaseTreeNodeVisitor;
  lcTreeWalker: TTreeWalker;
begin
  lcTreeWalker := TTreeWalker.Create;
  try

    // apply a visit setXY first
    lcProcess := TVisitSetXY.Create;
    try
      lcTreeWalker.Visit(GetRoot, lcProcess);
    finally
      lcProcess.Free;
    end;

    // and set up nesting levels
    lcProcess := TVisitSetNestings.Create;
    try
      lcTreeWalker.Visit(GetRoot, lcProcess);
    finally
      lcProcess.Free;
    end;

    // then apply the process
    lcProcess := SingleProcess.Create;
    try
      lcTreeWalker.Visit(GetRoot, lcProcess);
    finally
      lcProcess.Free;
    end;

  finally
    lcTreeWalker.Free;
  end;
end;


function TConverter.GetRoot: TParseTreeNode;
begin
  Result := fcBuildParseTree.Root;
end;

procedure TConverter.CollectOutput(const pcRoot: TParseTreeNode);
var
  liLoop: Integer;
begin
  Assert(pcRoot <> nil);

  // is it a leaf with source?
  if (pcRoot is TSourceToken) then
    fsOutputCode := fsOutputCode + TSourceToken(pcRoot).SourceCode
  else  // recurse, write out all child nodes
    for liLoop := 0 to pcRoot.ChildNodeCount - 1 do
      CollectOutput(pcRoot.ChildNodes[liLoop]);
end;

function TConverter.GetOnStatusMessage: TStatusMessageProc;
begin
  Result := fOnStatusMessage;
end;

procedure TConverter.SetOnStatusMessage(const Value: TStatusMessageProc);
begin
  fOnStatusMessage := Value;
end;

procedure TConverter.SendExceptionMessage(const pe: Exception);
var
  lsMessage:     String;
  liX, liY:      Integer;
  leParseError:  TEParseError;
  leMessageType: TStatusMessageType;
begin
  lsMessage := Format(lisMsgExceptionClassMsg, [pe.ClassName, pe.Message]);

  if pe is TEParseError then
  begin
    leParseError := TEParseError(pe);
    lsMessage := lsMessage + NativeLineBreak + Format(lisMsgNear2,[leParseError.TokenMessage]);
    liX := leParseError.XPosition;
    liY := leParseError.YPosition;
    leMessageType := mtParseError;
  end
  else
  begin
    liX := -1;
    liY := -1;
    leMessageType := mtException;
  end;

  SendStatusMessage('', lsMessage, leMessageType, liY, liX);
end;

procedure TConverter.SendStatusMessage(const psUnit, psMessage: String; const peMessageType: TStatusMessageType; const piY, piX: Integer);
var
  lsUnit: string;
begin
  if Assigned(fOnStatusMessage) then
  begin
    lsUnit := psUnit;
    if lsUnit = '' then
      lsUnit := fsFileName;
    fOnStatusMessage(lsUnit, psMessage, peMessageType, piY + fiFirstLineNumber - 1, piX);
  end;
end;

procedure TConverter.ShowParseTree;
begin
  // This is always called from a Cursor:=crHourGlass block. Restore old cursor.
  GetUI.RestoreCursorUI;
  if fcBuildParseTree.Root <> nil then
    GetUI.ShowParseTreeUI(fcBuildParseTree.Root);
end;

procedure TConverter.ConvertPart(const piStartIndex, piEndIndex: Integer;
                                 aOnlyOutputSelection: boolean);
var
  liRealInputStart, liRealInputEnd: Integer;
  liOutputStart, liOutputEnd: Integer;
  lsNewOutput: String;
begin
  Assert(piStartIndex >= 0);
  Assert(piEndIndex >= piStartIndex);
  Assert(piEndIndex <= Length(InputCode));

  { round to nearest end of line }
  liRealInputStart := piStartIndex;
  liRealInputEnd   := piEndIndex;

  { get to the start of the line }
  while (liRealInputStart > 1) and (not CharIsReturn(InputCode[liRealInputStart - 1])) do
    Dec(liRealInputStart);

  { get to the start of the next line }
  while (liRealInputEnd < Length(InputCode)) and (not CharIsReturn(InputCode[liRealInputEnd])) do
    Inc(liRealInputEnd);
  while (liRealInputEnd < Length(InputCode)) and (CharIsReturn(InputCode[liRealInputEnd])) do
    Inc(liRealInputEnd);

  { put markers into the input }
  fsInputCode := StrInsert(FORMAT_END, fsInputCode, liRealInputEnd);
  { add a new line after FORMAT_START, prevents bad formating of first selected line. }
  fsInputCode := StrInsert(FORMAT_START+#10, fsInputCode, liRealInputStart);
  Convert;
  { locate the markers in the output, and replace before and after }
  liOutputStart := Pos(FORMAT_START, fsOutputCode) + Length(FORMAT_START);
  {remode new line added after FORMAT_START }
  if (liOutputStart<length(fsOutputCode)) and (fsOutputCode[liOutputStart]=#13) then
    inc(liOutputStart);
  if (liOutputStart<length(fsOutputCode)) and (fsOutputCode[liOutputStart]=#10) then
    inc(liOutputStart);
  liOutputEnd   := PosEx(FORMAT_END, fsOutputCode,liOutputStart);
  { splice }
  if aOnlyOutputSelection then
    lsNewOutput := Copy(fsOutputCode, liOutputStart, (liOutputEnd - liOutputStart))
  else begin
    lsNewOutput := StrLeft(fsInputCode, liRealInputStart - 1);
    lsNewOutput := lsNewOutput + Copy(fsOutputCode, liOutputStart, (liOutputEnd - liOutputStart));
    lsNewOutput := lsNewOutput + StrRestOf(fsInputCode, liRealInputEnd + Length(FORMAT_START) + Length(FORMAT_END));
  end;
  fsOutputCode := lsNewOutput;
end;

{ position on we insert selected CODE depending if the CODE contains interface
  and/or implementation

hasIterface     F      F      T      T
hasImplemen.    F      T      F      T
-----------------------------------------
              +unit  +unit  +unit  +unit
              +intf  +intf  CODE   CODE
              +impl  CODE   +impl  +end.
              CODE   +end.  +end.
              +end.
}

// convert only formats complete units
// so we wrap the selected code in a fake unit.
// Only works if the inputCode include the full procedure,function,class or record declaration.
// Needed for formating include files or part of a file with tokens not supported by
// the jedi code format parser.
// {$I %DATE%} for example.
procedure TConverter.ConvertUsingFakeUnit(AFirstLineNumber:integer);
const
  END_MARK_INTERFACE = 'tfaketjcf_intfc_end_mark;';        //<lower case required
  END_MARK_IMPLEMENTATION = 'tfaketjcf_implm_end_mark;'; //<lower case required
  FAKE_UNIT_NAME = 'fakeunitjcf;'; //<lower case required
var
  sourceCode: string;
  sourceCodeLowerCase: string;
  lcStartIndex, lcEndIndex: integer;
  hasInterface, hasImplementation: boolean;
  liInterfacePos,liImplementationPos:integer;

  procedure AddFakeUnit;
  begin
    sourceCode := sourceCode + 'unit ' + FAKE_UNIT_NAME + #10;
    Dec(fiFirstLineNumber);
  end;

  procedure AddFakeInterface;
  var
    liUsesPos:integer;
  begin
    sourceCode := sourceCode + 'interface{:*_*:}' + #10;
    Dec(fiFirstLineNumber);
    liUsesPos:=PosEx('uses',sourceCodeLowerCase,1);
    if (liUsesPos>0) and (liImplementationPos>0) and (liUsesPos<liImplementationPos)
      and (length(sourceCodeLowerCase)>=liUsesPos+4) and CharIsWhiteSpace(sourceCodeLowerCase[liUsesPos+4]) then
    begin
      sourceCode := sourceCode + '// ' + END_MARK_INTERFACE + #10;
      Dec(fiFirstLineNumber);
    end
    else
    begin
      sourceCode := sourceCode + 'type' + #10;        // if there is only a class selected this is required
      sourceCode := sourceCode + 'faketjcfifc=' + END_MARK_INTERFACE + #10;
      Dec(fiFirstLineNumber, 2);
    end;
  end;

  procedure AddFakeImplementation(AAdjustFirstLineNumber: boolean);
  var
    liUsesPos:integer;
  begin
    sourceCode := sourceCode + 'implementation{:*_*:}' + #10;
    if AAdjustFirstLineNumber then
      Dec(fiFirstLineNumber);
    liUsesPos:=PosEx('uses',sourceCodeLowerCase,1);
    if ((not hasInterface) and (not hasImplementation)) and (liUsesPos>0)
      and (length(sourceCodeLowerCase)>=liUsesPos+4) and CharIsWhiteSpace(sourceCodeLowerCase[liUsesPos+4]) then
    begin
      sourceCode := sourceCode + '// ' + END_MARK_IMPLEMENTATION + #10;
      if AAdjustFirstLineNumber then
        Dec(fiFirstLineNumber);
    end
    else
    begin
      sourceCode := sourceCode + 'type' + #10;
      sourceCode := sourceCode + 'faketjcfimpl=' + END_MARK_IMPLEMENTATION + #10;
      if AAdjustFirstLineNumber then
        Dec(fiFirstLineNumber, 2);
    end;
  end;

  procedure AddFakeEnd;
  begin
    sourceCode := sourceCode + #10 + 'end{:*_*:}.' + #10;
  end;

begin
  //WRAPPING the inputCode in a fake unit
  fiFirstLineNumber := AFirstLineNumber;
  sourceCodeLowerCase := LowerCase(fsInputCode);
  {$push}{$warn 5057 off}
  hasInterface := HasStringAtLineStart(sourceCodeLowerCase, 'interface', liInterfacePos);
  hasImplementation := HasStringAtLineStart(sourceCodeLowerCase, 'implementation', liImplementationPos);
  {$pop}
  sourceCode := '';
  AddFakeUnit;
  if hasInterface = False then
  begin
    AddFakeInterface;
    if hasImplementation = False then
      AddFakeImplementation(True);
  end;
  sourceCode := sourceCode + fsInputCode;
  if (hasInterface = True) and (hasImplementation = False) then
    AddFakeImplementation(False);
  AddFakeEnd;
  fsInputCode:=sourceCode;
  Convert;
  if ConvertError = False then
  begin
    sourceCodeLowerCase := LowerCase(OutputCode);
    //DELETE FAKE lines from output
    if hasInterface then
      lcStartIndex := Pos(FAKE_UNIT_NAME, sourceCodeLowerCase) + length(FAKE_UNIT_NAME)
    else
    begin
      if hasImplementation then
        lcStartIndex := Pos(END_MARK_INTERFACE, sourceCodeLowerCase) + length(END_MARK_INTERFACE)
      else
        lcStartIndex := Pos(END_MARK_IMPLEMENTATION, sourceCodeLowerCase) + length(END_MARK_IMPLEMENTATION);
    end;
    //lcStartIndex := SkipToNextLine(sourceCodeLowerCase, lcStartIndex-1);
    //formated code:    tfaketjcf_implm_end_mark;#10#13#10     on windows
    if sourceCodeLowerCase[lcStartIndex]=#10 then
    begin
      Inc(lcStartIndex);
      if sourceCodeLowerCase[lcStartIndex]=#13 then
      begin
        Inc(lcStartIndex);
        if sourceCodeLowerCase[lcStartIndex]=#10 then
          Inc(lcStartIndex);
      end
      else if sourceCodeLowerCase[lcStartIndex]=#10 then
        Inc(lcStartIndex);
    end;
    if hasInterface and not hasImplementation then
      lcEndIndex := RPos('implementation{:*_*:}', sourceCodeLowerCase)
    else
      lcEndIndex := RPos('end{:*_*:}', sourceCodeLowerCase);
    lcEndIndex := SkipLeftSpaces(sourceCodeLowerCase, lcEndIndex);
    fsOutputCode:=Copy(OutputCode, lcStartIndex, lcEndIndex - lcStartIndex);
  end;
end;

end.