Skip to main content
summaryrefslogtreecommitdiffstats
blob: caaca58e7ae25d4b622839776b43491d47b2b626 (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
/**
 * Copyright (c) 2014 CEA LIST.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Laurent Wouters laurent.wouters@cea.fr - Initial API and implementation
 *
 */
package org.eclipse.papyrus.infra.nattable.parsers;

import java.io.Reader;

/**
 * Represents a lexer for a CSV document
 *
 * Lexing rules are:
 * LineEnding -> '\n' | '\r' | '\r\n'
 * Separator -> what is given in parameter
 * TextMarker -> what is given in parameter
 * Whitespace -> (Unicode IsWhitespace character class) - (Separator | TextMarker | '\n' | '\r')
 * Cell -> (. - Whitespace)*
 * Cell -> TextMarker ( (.-TextMarker) | (TextMarker TextMarker)* ) TextMarker
 *
 * In these rules . represents any character and - represents the language difference operator.
 * The last rule means that inside a quoted cell value the content can be anything except the quote character, in which case it must be doubled.
 *
 * @author Laurent Wouters
 */
public class CSVLexer {
	/**
	 * Represents an error in this lexer
	 */
	public static final int TOKEN_ERROR = -1;
	/**
	 * Token type of cells' value in a CSV
	 */
	public static final int TOKEN_VALUE = 0;
	/**
	 * Token type of cells' separator
	 */
	public static final int TOKEN_SEPARATOR = 1;
	/**
	 * Token type of new line markers
	 */
	public static final int TOKEN_NEW_ROW = 2;
	/**
	 * Token type for the end of input marker
	 */
	public static final int TOKEN_EOF = 3;

	/**
	 * Size of the buffer used to build the tokens
	 */
	private static final int BUFFER_SIZE = 1024;

	/**
	 * Boolean to determinate if the beginning string whitespace must be kept or removed.
	 */
	private final boolean keepBeginningWhiteSpace;

	private RewindableTextStream input; // the input stream
	private char separator; // The cell separator character
	private char textMarker; // The raw text beginning and end character
	private char[] builder; // The buffer used to build the tokens
	private int lastTokenType; // The type of the last matched token
	private String lastTokenValue; // The value of the last matched token

	/**
	 * Initializes this lexer
	 *
	 * @param input
	 *            The input text reader
	 * @param valueSeparator
	 *            The character that separates values in rows
	 * @param textMarker
	 *            The character that marks the beginning and end of raw text
	 */
	public CSVLexer(final Reader input, final char valueSeparator, final char textMarker) {
		this(input, valueSeparator, textMarker, false);
	}
	
	/**
	 * Initializes this lexer with boolean to determinate if the beginning whitespace must be kept.
	 *
	 * @param input
	 *            The input text reader
	 * @param valueSeparator
	 *            The character that separates values in rows
	 * @param textMarker
	 *            The character that marks the beginning and end of raw text
	 * @param keepBeginningWhiteSpace
	 *            Boolean to determinate if the beginning string whitespace must be kept or removed
	 */
	public CSVLexer(final Reader input, final char valueSeparator, final char textMarker, final boolean keepBeginningWhiteSpace) {
		this.input = new RewindableTextStream(input);
		this.separator = valueSeparator;
		this.textMarker = textMarker;
		this.builder = new char[BUFFER_SIZE];
		this.lastTokenType = TOKEN_ERROR;
		this.lastTokenValue = null;
		this.keepBeginningWhiteSpace = keepBeginningWhiteSpace;
	}

	/**
	 * Gets the type of the last matched token
	 *
	 * @return The type of the last matched token
	 */
	public int getTokenType() {
		return lastTokenType;
	}

	/**
	 * Gets the value of the last matched token
	 *
	 * @return The value of the last matched token
	 */
	public String getTokenValue() {
		return lastTokenValue;
	}

	/**
	 * Gets the next token in the input
	 *
	 * @return The next token
	 */
	public String next() {
		// ignore all whitespaces
		char c = input.read();
		if (input.isAtEnd()) {
			return getTokenEOF();
		}
		if (!keepBeginningWhiteSpace) {
			while (isWhitespace(c)) {
				c = input.read();
				if (input.isAtEnd()) {
					return getTokenEOF();
				}
			}
		}

		// Here c is not whitespace and we are not at the end
		if (c == separator) {
			return getTokenSeparator();
		}
		if (c == textMarker) {
			return onTextMarkerChar();
		}
		if (c == '\r' || c == '\n') {
			return onLineEndingChar(c);
		}

		// Here we are on normal data
		int length = 1;
		builder[0] = c;
		while (true) {
			c = input.read();
			if (input.isAtEnd()) {
				break;
			}
			if (c == separator || c == '\r' || c == '\n') {
				input.rewind(1);
				break;
			}
			builder[length] = c;
			length++;
		}

		// we matched the data
		// Now, trim the trailing white spaces
		while (length > 0 && isWhitespace(builder[length - 1])) {
			length--;
		}

		return getTokenValue(length);
	}

	/**
	 * Determines whether the given character is a white space that can be skipped
	 *
	 * @param c
	 *            The character
	 * @return <code>true</code> if the character can be skipped
	 */
	private boolean isWhitespace(char c) {
		if (c == separator || c == textMarker || c == '\n' || c == '\r') {
			return false;
		}
		return Character.isWhitespace(c);
	}

	/**
	 * Lexes the line ending token beginning with the given character
	 *
	 * @param c
	 *            The beginning character
	 * @return The matched token
	 */
	private String onLineEndingChar(char c) {
		if (c == '\n') {
			return getTokenNewRow();
		}
		// This was a '\r' character
		// Check for windows line ending style
		char n = input.read();
		if (input.isAtEnd()) {
			return getTokenNewRow();
		}
		if (n != '\n') {
			input.rewind(1);
		}
		return getTokenNewRow();
	}

	/**
	 * Lexes the raw text between marks
	 *
	 * @return The matched token
	 */
	private String onTextMarkerChar() {
		int length = 0;
		while (true) {
			char c = input.read();
			if (input.isAtEnd()) {
				return getTokenError();
			}
			if (c != textMarker) {
				builder[length] = c;
				length++;
			} else {
				// get the following char
				c = input.read();
				if (c == textMarker) {
					// This is a double marker
					builder[length] = c;
					length++;
				} else {
					// This was the end of the quoted text
					if (!input.isAtEnd()) {
						input.rewind(1);
					}
					return getTokenValue(length);
				}
			}
		}
	}

	/**
	 * Gets an error token
	 *
	 * @return An error token
	 */
	private String getTokenError() {
		lastTokenType = TOKEN_ERROR;
		lastTokenValue = null;
		return null;
	}

	/**
	 * Gets an end of input marker token
	 *
	 * @return An end of input marker token
	 */
	private String getTokenEOF() {
		lastTokenType = TOKEN_EOF;
		lastTokenValue = null;
		return null;
	}

	/**
	 * Gets a cell separator token
	 *
	 * @return A cell separator token
	 */
	private String getTokenSeparator() {
		lastTokenType = TOKEN_SEPARATOR;
		lastTokenValue = null;
		return null;
	}

	/**
	 * Gets a new row token
	 *
	 * @return A new row token
	 */
	private String getTokenNewRow() {
		lastTokenType = TOKEN_NEW_ROW;
		lastTokenValue = null;
		return null;
	}

	/**
	 * Gets a token representing a cell's value
	 *
	 * @param length
	 *            Length of the value
	 * @return A token
	 */
	private String getTokenValue(int length) {
		lastTokenType = TOKEN_VALUE;
		lastTokenValue = new String(builder, 0, length);
		return lastTokenValue;
	}

	/**
	 *
	 * @return
	 * 		the number of read characters
	 */
	public long getReadCharacters() {
		return this.input.getReadCharacters();
	}
}

Back to the top