summaryrefslogtreecommitdiff
path: root/src/corelib/fpg_csvparser.pas
blob: f5c0d0ede9147a3351e6b54454276404d821be2e (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
{
    fpGUI  -  Free Pascal GUI Toolkit

    Copyright (C) 2006 - 2014 See the file AUTHORS.txt, included in this
    distribution, for details of the copyright.

    See the file COPYING.modifiedLGPL, included in this distribution,
    for details about redistributing fpGUI.

    This program 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.

    Description:
      Uses a Finite State Machine to parse CSV files.
      Graeme Geldenhuys <graemeg@gmail.com>

      This unit shows how one could use the State Design Pattern to implement a
      FSM (Finite State Machine) to create a CSV Parser.  It handles invalid
      CSV as well and will raise an appropriate exception. In the State pattern,
      each of the states becomes a subclass of the base class. Each subclass must
      implement the abstract method which will handle the input character and
      decide on the next state.
}

unit fpg_CSVParser;

{$mode objfpc}{$H+}

interface

uses
  Classes;

type
  { forward declarations }
  TCSVParser        = class;
  TParserStateClass = class of TCSVParserState;


  { Abstract State object }
  TCSVParserState = class(TObject)
  private
    FParser: TCSVParser;
    procedure ChangeState(NewState: TParserStateClass);
    procedure AddCharToCurrField(Ch: char);
    procedure AddCurrFieldToList;
  public
    constructor Create(AParser: TCSVParser);
    { Must be implemented in the concrete classes to handle the input character
      and decide on the next state. }
    procedure ProcessChar(Ch: AnsiChar; Pos: integer); virtual; abstract;
  end;


  { A concrete state object - used when starting a new field }
  TCSVParserFieldStartState = class(TCSVParserState)
  public
    procedure ProcessChar(Ch: AnsiChar; Pos: integer); override;
  end;


  { A concrete state object - used while scanning a field }
  TCSVParserScanFieldState = class(TCSVParserState)
  public
    procedure ProcessChar(Ch: AnsiChar; Pos: integer); override;
  end;


  { A concrete state object - used while scanning double quoted fields }
  TCSVParserScanQuotedState = class(TCSVParserState)
  public
    procedure ProcessChar(Ch: AnsiChar; Pos: integer); override;
  end;


  { A concrete state object - used when found the ending double quote }
  TCSVParserEndQuotedState = class(TCSVParserState)
  public
    procedure ProcessChar(Ch: AnsiChar; Pos: integer); override;
  end;


  { A concrete state object - some error occured / invalid CSV structure }
  TCSVParserGotErrorState = class(TCSVParserState)
  public
    procedure ProcessChar(Ch: AnsiChar; Pos: integer); override;
  end;


  { The actual state machine - CSV parser }
  TCSVParser = class(TObject)
  private
    FCurrentLine: string;
    FState: TCSVParserState;
    { Cache state objects for greater performance. This comes in handy when
      parsing a large CSV file. For smaller files you might want to create them
      on the fly. }
    FFieldStartState: TCSVParserFieldStartState;
    FScanFieldState: TCSVParserScanFieldState;
    FScanQuotedState: TCSVParserScanQuotedState;
    FEndQuotedState: TCSVParserEndQuotedState;
    FGotErrorState: TCSVParserGotErrorState;
    { Fields used during parsing }
    FCurrField: string;
    FFieldList: TStrings;
    function GetState: TParserStateClass;
    procedure SetState(const Value: TParserStateClass);
  protected
    procedure AddCharToCurrField(Ch: char);
    procedure AddCurrFieldToList;
    { An example of Self Encapsulating Field refactoring }
    property State: TParserStateClass read GetState write SetState;
  public
    constructor Create;
    destructor Destroy; override;
    { prodecure to call, to start the parsing process }
    procedure ExtractFields(const S: string; const pFieldList: TStrings);
    property CurrentLine: string read FCurrentLine;
  end;


// global singleton function
function gCSVParser: TCSVParser;


implementation

uses
  SysUtils;

var
  uCSVParser: TCSVParser;


// Lazy mans singleton
function gCSVParser: TCSVParser;
begin
  if uCSVParser = nil then
    uCSVParser := TCSVParser.Create;
  Result := uCSVParser;
end;

{ TCSVParser }

constructor TCSVParser.Create;
begin
  inherited Create;
  FCurrentLine     := '';
  FFieldStartState := TCSVParserFieldStartState.Create(Self);
  FScanFieldState  := TCSVParserScanFieldState.Create(Self);
  FScanQuotedState := TCSVParserScanQuotedState.Create(Self);
  FEndQuotedState  := TCSVParserEndQuotedState.Create(Self);
  FGotErrorState   := TCSVParserGotErrorState.Create(Self);
end;

destructor TCSVParser.Destroy;
begin
  FFieldStartState.Free;
  FScanFieldState.Free;
  FScanQuotedState.Free;
  FEndQuotedState.Free;
  FGotErrorState.Free;
  inherited;
end;

function TCSVParser.GetState: TParserStateClass;
begin
  Result := TParserStateClass(FState.ClassType);
end;

procedure TCSVParser.SetState(const Value: TParserStateClass);
begin
  if Value = TCSVParserFieldStartState then
    FState := FFieldStartState
  else if Value = TCSVParserScanFieldState then
    FState := FScanFieldState
  else if Value = TCSVParserScanQuotedState then
    FState := FScanQuotedState
  else if Value = TCSVParserEndQuotedState then
    FState := FEndQuotedState
  else if Value = TCSVParserGotErrorState then
    FState := FGotErrorState;
end;

procedure TCSVParser.ExtractFields(const S: string; const pFieldList: TStrings);
var
  i: integer;
  Ch: AnsiChar;
begin
  FCurrentLine := S;
  FFieldList   := pFieldList;
  Assert(Assigned(FFieldList), 'FieldList not assigned');
  { Initialize by clearing the string list, and starting in FieldStart state }
  FFieldList.Clear;
  State        := TCSVParserFieldStartState;
  FCurrField   := '';

  { Read through all the characters in the string }
  for i := 1 to Length(s) do
  begin
    { Get the next character }
    Ch := s[i];
    FState.ProcessChar(Ch, i);
  end;

  { If we are in the ScanQuoted or GotError state at the end of the string, 
    there was a problem with a closing quote. You can add the second if test
    for an extra failsafe!  }
  if (State = TCSVParserScanQuotedState) then
    //      or (State = TCSVParserGotErrorState) then
    raise Exception.Create('Missing closing quote');

  { If the current field is not empty, add it to the list }
  if (FCurrField <> '') then
    AddCurrFieldToList;
end;

procedure TCSVParser.AddCharToCurrField(Ch: char);
begin
  FCurrField := FCurrField + Ch;
end;

procedure TCSVParser.AddCurrFieldToList;
begin
  FFieldList.Add(FCurrField);
  // Clear the field in preparation for collecting the next one
  FCurrField := '';
end;

{ TCSVParserState }

constructor TCSVParserState.Create(AParser: TCSVParser);
begin
  inherited Create;
  FParser := AParser;
end;

procedure TCSVParserState.ChangeState(NewState: TParserStateClass);
begin
  FParser.State := NewState;
end;

procedure TCSVParserState.AddCharToCurrField(Ch: char);
begin
  FParser.AddCharToCurrField(Ch);
end;

procedure TCSVParserState.AddCurrFieldToList;
begin
  FParser.AddCurrFieldToList;
end;

{ TCSVParserFieldStartState }

procedure TCSVParserFieldStartState.ProcessChar(Ch: AnsiChar; Pos: integer);
begin
  case Ch of
    '"': ChangeState(TCSVParserScanQuotedState);
    ',': AddCurrFieldToList;
    else
      AddCharToCurrField(Ch);
      ChangeState(TCSVParserScanFieldState);
  end;
end;

{ TCSVParserScanFieldState }

procedure TCSVParserScanFieldState.ProcessChar(Ch: AnsiChar; Pos: integer);
begin
  if (Ch = ',') then
  begin
    AddCurrFieldToList;
    ChangeState(TCSVParserFieldStartState);
  end
  else
    AddCharToCurrField(Ch);
end;

{ TCSVParserScanQuotedState }

procedure TCSVParserScanQuotedState.ProcessChar(Ch: AnsiChar; Pos: integer);
begin
  if (Ch = '"') then
    ChangeState(TCSVParserEndQuotedState)
  else
    AddCharToCurrField(Ch);
end;

{ TCSVParserEndQuotedState }

procedure TCSVParserEndQuotedState.ProcessChar(Ch: AnsiChar; Pos: integer);
begin
  if (Ch = ',') then
  begin
    AddCurrFieldToList;
    ChangeState(TCSVParserFieldStartState);
  end
  else
    ChangeState(TCSVParserGotErrorState);
end;

{ TCSVParserGotErrorState }

procedure TCSVParserGotErrorState.ProcessChar(Ch: AnsiChar; Pos: integer);
begin
  raise Exception.Create(Format('Error in line at position %d: ' + #10 +
    '<%s>', [Pos, FParser.CurrentLine]));
end;


initialization
  uCSVParser := nil;

finalization
  if uCSVParser <> nil then
    uCSVParser.Free;

end.