summaryrefslogtreecommitdiff
path: root/packages/fcl-base/src/pascodegen.pp
blob: d491d0e1e66122be6b13ca4a5b9ddc598d29e483 (plain)
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
unit pascodegen;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils;

Type
  TCodegenLogType = (cltInfo);
  TCodegenLogTypes = Set of TCodegenLogType;
  TCodeGeneratorLogEvent = Procedure (Sender : TObject; LogType : TCodegenLogType; Const Msg : String) of object;
  TCodesection = (csUnknown, csConst, csType, csVar, csResourcestring, csDeclaration);

  { TPascalCodeGenerator }

  TPascalCodeGenerator = Class(TComponent)
  Private
    FAddTimeStamp: Boolean;
    FExtraUnits: String;
    FKeywordPrefix: String;
    FKeywordSuffix: String;
    FLicenseText: TStrings;
    FOnLog: TCodeGeneratorLogEvent;
    FOutputUnitName: String;
    FSource : TStrings;
    Findent : String;
    FSections : Array of TCodeSection;
    FSectionCount : Integer;
    FSwitches: TStrings;
    function GetSection: TCodeSection;
    procedure SetLicenseText(AValue: TStrings);
    procedure SetSection(AValue: TCodeSection);
    procedure SetSwitches(AValue: TStrings);
  Protected
    // Source manipulation
    Procedure DoLog(Const Msg : String; AType : TCodegenLogType = cltInfo);
    Procedure DoLog(Const Fmt : String; Args : Array of const; AType : TCodegenLogType = cltInfo);
    Function BaseUnits : String; virtual;
  Public
  Public
    Constructor Create(AOwner : TComponent); override;
    Destructor Destroy; override;
    // Emit section type word
    Procedure EnsureSection(aSection : TCodeSection);
    Procedure PushSection(ASection : TCodeSection = csUnknown);
    Function PopSection : TCodeSection;
    Procedure CreateHeader; virtual;
    Procedure CreateUnitClause; virtual;
    Procedure Indent;
    Procedure Undent;
    Function IsKeyWord (Const S : String) : Boolean;
    Function EscapeKeyWord(Const S : String) : String;
    Function MakePascalString(S: String; AddQuotes: Boolean=False): String;
    Function PrettyPrint(Const S: string): String;
    Procedure AddLn(Const Aline: string);
    Procedure AddLn(Const Alines : array of string);
    Procedure AddLn(Const Alines : TStrings);
    Procedure AddLn(Const Fmt: string; Args : Array of const);
    Procedure Comment(Const AComment : String; Curly : Boolean = False);
    Procedure Comment(Const AComment : Array of String);
    Procedure Comment(Const AComment : TStrings);
    Procedure ClassHeader(Const AClassName: String); virtual;
    Procedure SimpleMethodBody(Lines: Array of string); virtual;
    procedure SaveToStream(const AStream: TStream);
    Procedure SaveToFile(Const AFileName : string);
    Property Source : TStrings Read FSource;
    Property CurrentSection : TCodeSection Read GetSection Write SetSection;
  Published
    Property OutputUnitName : String Read FOutputUnitName Write FOutputUnitName;
    Property ExtraUnits : String Read FExtraUnits Write FExtraUnits;
    Property LicenseText : TStrings Read FLicenseText Write SetLicenseText;
    Property Switches : TStrings Read FSwitches Write SetSwitches;
    Property OnLog : TCodeGeneratorLogEvent Read FOnLog Write FOnlog;
    Property AddTimeStamp : Boolean Read FAddTimeStamp Write FAddTimeStamp;
    Property KeywordSuffix : String Read FKeywordSuffix Write FKeywordSuffix;
    Property KeywordPrefix : String Read FKeywordPrefix Write FKeywordPrefix;
  end;

implementation
{ TPascalCodeGenerator }
procedure TPascalCodeGenerator.Indent;
begin
  FIndent:=FIndent+StringOfChar(' ',2);
end;

procedure TPascalCodeGenerator.Undent;

Var
  L : Integer;
begin
  L:=Length(Findent);
  if L>0  then
    FIndent:=Copy(FIndent,1,L-2)
end;

function TPascalCodeGenerator.IsKeyWord(const S: String): Boolean;

Const
   KW=';absolute;and;array;asm;begin;case;const;constructor;destructor;div;do;'+
       'downto;else;end;file;for;function;goto;if;implementation;in;inherited;'+
       'inline;interface;label;mod;nil;not;object;of;on;operator;or;packed;'+
       'procedure;program;record;reintroduce;repeat;self;set;shl;shr;string;then;'+
       'to;type;unit;until;uses;var;while;with;xor;dispose;exit;false;new;true;'+
       'as;class;dispinterface;except;exports;finalization;finally;initialization;'+
       'inline;is;library;on;out;packed;property;raise;resourcestring;threadvar;try;'+
       'private;published;length;setlength;';

begin
  Result:=Pos(';'+lowercase(S)+';',KW)<>0;
end;

function TPascalCodeGenerator.EscapeKeyWord(const S: String): String;
begin
  Result:=S;
  if IsKeyWord(S) then
    Result:=KeywordPrefix+Result+KeywordSuffix
end;

procedure TPascalCodeGenerator.AddLn(const Aline: string);

begin
  FSource.Add(FIndent+ALine);
end;

procedure TPascalCodeGenerator.AddLn(const Alines: array of string);

Var
  S : String;

begin
  For s in alines do
    Addln(S);
end;

procedure TPascalCodeGenerator.AddLn(const Alines: TStrings);
Var
  S : String;

begin
  For s in alines do
    Addln(S);
end;

procedure TPascalCodeGenerator.AddLn(const Fmt: string; Args: array of const);
begin
  AddLn(Format(Fmt,Args));
end;

procedure TPascalCodeGenerator.Comment(const AComment: String; Curly: Boolean);
begin
  if Curly then
    AddLn('{ '+AComment+' }')
  else
    AddLn('// '+AComment);
end;

procedure TPascalCodeGenerator.Comment(const AComment: array of String);
begin
  AddLn('{');
  Indent;
  AddLn(AComment);
  Undent;
  AddLn('}');
end;

procedure TPascalCodeGenerator.Comment(const AComment: TStrings);
begin
  AddLn('{');
  Indent;
  AddLn(AComment);
  Undent;
  AddLn('}');
end;



constructor TPascalCodeGenerator.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FSource:=TstringList.Create;
  FLicenseText:=TstringList.Create;
  FSwitches:=TstringList.Create;
  FSwitches.Add('MODE ObjFPC');
  FSwitches.Add('H+');
  SetLength(FSections,0);
  FSectionCount:=0;
  PushSection(csUnknown);
  FKeywordPrefix:='&';
end;

destructor TPascalCodeGenerator.Destroy;
begin
  FreeAndNil(FSwitches);
  FreeAndNil(FLicenseText);
  FreeAndNil(FSource);
  inherited Destroy;
end;

procedure TPascalCodeGenerator.EnsureSection(aSection: TCodeSection);

Const
  SectionKeyWords : Array[TCodesection] of string
    = ('', 'Const', 'Type', 'Var', 'Resourcestring', '');

begin
  If CurrentSection<>aSection then
    begin
    CurrentSection:=aSection;
    AddLn(SectionKeyWords[CurrentSection]);
    end;
end;

procedure TPascalCodeGenerator.PushSection(ASection : TCodeSection = csUnknown);
begin
  if FSectionCount=Length(FSections) then
    SetLength(FSections,FSectionCount+10);
  FSections[FSectionCount]:=ASection;
  Inc(FSectionCount);
end;

function TPascalCodeGenerator.PopSection: TCodeSection;
begin
  if FSectionCount=0 then
    Result:=csUnknown
  else
    begin
    Dec(FSectionCount);
    Result:=FSections[FSectionCount];
    end;

end;

procedure TPascalCodeGenerator.SaveToStream(const AStream : TStream);

begin
  FSource.SaveToStream(AStream)
end;

procedure TPascalCodeGenerator.SaveToFile(const AFileName: string);

Var
  F : TFileStream;
  B : Boolean;

begin
  B:=False;
  F:=Nil;
  try
    B:=(Source.Count=0) and (OutputUnitName='');
    if B then
      OutputUnitname:=ChangeFileExt(ExtractFileName(AFileName),'');
    F:=TFileStream.Create(aFilename,fmCreate);
    SaveToStream(F);
  finally
    F.Free;
    if B then
      OutputUnitName:='';
  end;
end;

procedure TPascalCodeGenerator.SetSection(AValue: TCodeSection);
begin
  if GetSection=AValue then
     Exit;
  FSections[FSectionCount-1]:=AValue;
end;

procedure TPascalCodeGenerator.SetSwitches(AValue: TStrings);
begin
  if FSwitches=AValue then Exit;
  FSwitches.Assign(AValue);
end;

function TPascalCodeGenerator.GetSection: TCodeSection;
begin
  Result:=FSections[FSectionCount-1];
end;

procedure TPascalCodeGenerator.SetLicenseText(AValue: TStrings);
begin
  if FLicenseText=AValue then Exit;
  FLicenseText.Assign(AValue);
end;

procedure TPascalCodeGenerator.DoLog(const Msg: String; AType: TCodegenLogType);
begin
  If Assigned(FOnLog) then
    FOnLog(Self,Atype,Msg);
end;

procedure TPascalCodeGenerator.DoLog(const Fmt: String; Args: array of const;
  AType: TCodegenLogType);
begin
  DoLog(Format(Fmt,Args),AType);
end;

procedure TPascalCodeGenerator.CreateHeader;

Var
  B,S : String;

begin
  if LicenseText.Count>0 then
    Comment(LicenseText);
  if AddTimeStamp then
    Comment('Generated on: '+DateTimeToStr(Now));
  For S in Switches do
    addln('{$%s}',[S]);
  addln('');
  addln('interface');
  addln('');
  S:=ExtraUnits;
  B:=BaseUnits;
  if (B<>'') then
    if (S<>'') then
      begin
      if (B[Length(B)]<>',') then
        B:=B+',';
      S:=B+S;
      end
    else
      S:=B;
  addln('uses %s;',[S]);
  addln('');
end;

procedure TPascalCodeGenerator.CreateUnitClause;
begin
  AddLn('Unit %s;',[OutputUnitName]);
  AddLn('');
end;

procedure TPascalCodeGenerator.SimpleMethodBody(Lines: array of string);

Var
   S : String;

begin
  AddLn('');
  AddLn('begin');
  Indent;
  For S in Lines do
    AddLn(S);
  Undent;
  AddLn('end;');
  AddLn('');
end;

function TPascalCodeGenerator.BaseUnits: String;
begin
  Result:='';
end;


function TPascalCodeGenerator.MakePascalString(S: String; AddQuotes: Boolean
  ): String;

begin
  Result:=StringReplace(S,'''','''''',[rfReplaceAll]);
  if AddQuotes then
    Result:=''''+Result+'''';
end;

function TPascalCodeGenerator.PrettyPrint(const S: string): String;

begin
  If (S='') then
    Result:=''
  else
    Result:=Upcase(S[1])+Copy(S,2,Length(S)-1);
end;

procedure TPascalCodeGenerator.ClassHeader(const AClassName: String);

begin
  AddLn('');
  AddLn('{ '+StringOfChar('-',68));
  AddLn('  '+AClassName);
  AddLn('  '+StringOfChar('-',68)+'}');
  AddLn('');
end;

end.

end.