Debian Codegraph @

pypy/module/_csv/interp_reader.py

raw symbols SCIP
1 from rpython.rlib.rutf8 import Utf8StringIterator, Utf8StringBuilder, unichr_as_utf8
2 from rpython.rlib import objectmodel
3 from rpython.rlib.rarithmetic import r_uint
4 from pypy.interpreter.baseobjspace import W_Root
5 from pypy.interpreter.error import OperationError
6 from pypy.interpreter.gateway import unwrap_spec
7 from pypy.interpreter.typedef import TypeDef, interp2app
8 from pypy.interpreter.typedef import interp_attrproperty_w, interp_attrproperty
9 from pypy.module._csv.interp_csv import _build_dialect
10 from pypy.module._csv.interp_csv import (QUOTE_MINIMAL, QUOTE_ALL,
11 QUOTE_NONNUMERIC, QUOTE_NONE)
12
13 (START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD,
14 IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD,
15 EAT_CRNL, AFTER_ESCAPED_CRNL) = range(9)
16
17
18 class W_Reader(W_Root):
19
20 def __init__(self, space, dialect, w_iter):
21 self.space = space
22 self.dialect = dialect
23 self.w_iter = w_iter
24 self.line_num = 0
25 self.sizehint = 1 # just used for first line
26
27 def iter_w(self):
28 return self
29
30 @objectmodel.dont_inline
31 def error(self, msg):
32 space = self.space
33 msg = 'line %d: %s' % (self.line_num, msg)
34 w_module = space.getbuiltinmodule('_csv')
35 w_error = space.getattr(w_module, space.newtext('Error'))
36 raise OperationError(w_error, space.newtext(msg))
37
38 def add_char(self, field_builder, c):
39 assert field_builder is not None
40 if field_builder.getlength() >= field_limit.limit:
41 raise self.error("field larger than field limit")
42 field_builder.append_code(c)
43
44 def save_field(self, field_builder):
45 space = self.space
46 field = field_builder.build()
47 w_obj = space.newutf8(field, field_builder.getlength())
48 if self.numeric_field:
49 self.numeric_field = False
50 w_obj = space.call_function(space.w_float, w_obj)
51 self.fields_w.append(w_obj)
52
53 def next_w(self):
54 space = self.space
55 dialect = self.dialect
56 self.fields_w = objectmodel.newlist_hint(self.sizehint)
57 self.numeric_field = False
58 field_builder = None # valid iff state not in [START_RECORD, EAT_CRNL]
59 state = START_RECORD
60 #
61 while True:
62 try:
63 w_line = space.next(self.w_iter)
64 except OperationError as e:
65 if e.match(space, space.w_StopIteration):
66 if (field_builder is not None and
67 state != START_RECORD and state != EAT_CRNL and
68 (len(field_builder.build()) > 0 or
69 state == IN_QUOTED_FIELD)):
70 if dialect.strict:
71 raise self.error("unexpected end of data")
72 else:
73 self.save_field(field_builder)
74 break
75 raise
76 self.line_num += 1
77 if space.isinstance_w(w_line, space.w_bytes):
78 raise self.error("iterator should return strings, not bytes "
79 "(did you open the file in text mode?")
80 line = space.utf8_w(w_line)
81 for c in Utf8StringIterator(line):
82 if state == START_RECORD:
83 if c == ord(u'\n') or c == ord(u'\r'):
84 state = EAT_CRNL
85 continue
86 # normal character - handle as START_FIELD
87 state = START_FIELD
88 # fall-through to the next case
89
90 if state == START_FIELD:
91 field_builder = Utf8StringBuilder(64)
92 # expecting field
93 if c == ord(u'\n') or c == ord(u'\r'):
94 # save empty field
95 self.save_field(field_builder)
96 state = EAT_CRNL
97 elif (c == dialect.quotechar and
98 dialect.quoting != QUOTE_NONE):
99 # start quoted field
100 state = IN_QUOTED_FIELD
101 elif c == dialect.escapechar:
102 # possible escaped character
103 state = ESCAPED_CHAR
104 elif c == ord(u' ') and dialect.skipinitialspace:
105 # ignore space at start of field
106 pass
107 elif c == dialect.delimiter:
108 # save empty field
109 self.save_field(field_builder)
110 else:
111 # begin new unquoted field
112 if dialect.quoting == QUOTE_NONNUMERIC:
113 self.numeric_field = True
114 self.add_char(field_builder, c)
115 state = IN_FIELD
116
117 elif state == ESCAPED_CHAR:
118 if c == ord(u'\n') or c == ord(u'\r'):
119 self.add_char(field_builder, c)
120 state = AFTER_ESCAPED_CRNL
121 else:
122 self.add_char(field_builder, c)
123 state = IN_FIELD
124
125 elif state == IN_FIELD or state == AFTER_ESCAPED_CRNL:
126 # in unquoted field
127 if c == ord(u'\n') or c == ord(u'\r'):
128 # end of line
129 self.save_field(field_builder)
130 state = EAT_CRNL
131 elif c == dialect.escapechar:
132 # possible escaped character
133 state = ESCAPED_CHAR
134 elif c == dialect.delimiter:
135 # save field - wait for new field
136 self.save_field(field_builder)
137 state = START_FIELD
138 else:
139 # normal character - save in field
140 self.add_char(field_builder, c)
141
142 elif state == IN_QUOTED_FIELD:
143 # in quoted field
144 if c == dialect.escapechar:
145 # Possible escape character
146 state = ESCAPE_IN_QUOTED_FIELD
147 elif (c == dialect.quotechar and
148 dialect.quoting != QUOTE_NONE):
149 if dialect.doublequote:
150 # doublequote; " represented by ""
151 state = QUOTE_IN_QUOTED_FIELD
152 else:
153 # end of quote part of field
154 state = IN_FIELD
155 else:
156 # normal character - save in field
157 self.add_char(field_builder, c)
158
159 elif state == ESCAPE_IN_QUOTED_FIELD:
160 self.add_char(field_builder, c)
161 state = IN_QUOTED_FIELD
162
163 elif state == QUOTE_IN_QUOTED_FIELD:
164 # doublequote - seen a quote in an quoted field
165 if (dialect.quoting != QUOTE_NONE and
166 c == dialect.quotechar):
167 # save "" as "
168 self.add_char(field_builder, c)
169 state = IN_QUOTED_FIELD
170 elif c == dialect.delimiter:
171 # save field - wait for new field
172 self.save_field(field_builder)
173 state = START_FIELD
174 elif c == ord(u'\n') or c == ord(u'\r'):
175 # end of line
176 self.save_field(field_builder)
177 state = EAT_CRNL
178 elif not dialect.strict:
179 self.add_char(field_builder, c)
180 state = IN_FIELD
181 else:
182 # illegal
183 raise self.error("'%s' expected after '%s'" % (
184 unichr_as_utf8(r_uint(dialect.delimiter)), unichr_as_utf8(r_uint(dialect.quotechar))))
185
186 elif state == EAT_CRNL:
187 if not (c == ord(u'\n') or c == ord(u'\r')):
188 raise self.error("new-line character seen in unquoted field - "
189 "do you need to open the file with newline=''?")
190
191 if state == IN_FIELD or state == QUOTE_IN_QUOTED_FIELD:
192 self.save_field(field_builder)
193 break
194 elif state == ESCAPED_CHAR:
195 self.add_char(field_builder, ord(u'\n'))
196 state = IN_FIELD
197 elif state == IN_QUOTED_FIELD:
198 pass
199 elif state == ESCAPE_IN_QUOTED_FIELD:
200 self.add_char(field_builder, ord(u'\n'))
201 state = IN_QUOTED_FIELD
202 elif state == START_FIELD:
203 # save empty field
204 field_builder = Utf8StringBuilder()
205 self.save_field(field_builder)
206 break
207 elif state == AFTER_ESCAPED_CRNL:
208 continue
209 else:
210 break
211 #
212 w_result = space.newlist(self.fields_w)
213 # assume all lines have the same number of fields
214 self.sizehint = len(self.fields_w)
215 self.fields_w = None
216 return w_result
217
218
219 def csv_reader(space, w_iterator, w_dialect=None,
220 w_delimiter = None,
221 w_doublequote = None,
222 w_escapechar = None,
223 w_lineterminator = None,
224 w_quotechar = None,
225 w_quoting = None,
226 w_skipinitialspace = None,
227 w_strict = None,
228 ):
229 """
230 csv_reader = reader(iterable [, dialect='excel']
231 [optional keyword args])
232 for row in csv_reader:
233 process(row)
234
235 The "iterable" argument can be any object that returns a line
236 of input for each iteration, such as a file object or a list. The
237 optional \"dialect\" parameter is discussed below. The function
238 also accepts optional keyword arguments which override settings
239 provided by the dialect.
240
241 The returned object is an iterator. Each iteration returns a row
242 of the CSV file (which can span multiple input lines)"""
243 w_iter = space.iter(w_iterator)
244 dialect = _build_dialect(space, w_dialect, w_delimiter, w_doublequote,
245 w_escapechar, w_lineterminator, w_quotechar,
246 w_quoting, w_skipinitialspace, w_strict)
247 return W_Reader(space, dialect, w_iter)
248
249 W_Reader.typedef = TypeDef(
250 '_csv.reader',
251 dialect = interp_attrproperty_w('dialect', W_Reader),
252 line_num = interp_attrproperty('line_num', W_Reader,
253 wrapfn="newint"),
254 __iter__ = interp2app(W_Reader.iter_w),
255 __next__ = interp2app(W_Reader.next_w),
256 __doc__ = """CSV reader
257
258 Reader objects are responsible for reading and parsing tabular data
259 in CSV format.""")
260 W_Reader.typedef.acceptable_as_base_class = False
261
262 # ____________________________________________________________
263
264 class FieldLimit:
265 limit = 128 * 1024 # max parsed field size
266 field_limit = FieldLimit()
267
268 @unwrap_spec(new_limit=int)
269 def csv_field_size_limit(space, new_limit=-1):
270 old_limit = field_limit.limit
271 if new_limit >= 0:
272 field_limit.limit = new_limit
273 return space.newint(old_limit)