_csv.c 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  1. /* csv module */
  2. /*
  3. This module provides the low-level underpinnings of a CSV reading/writing
  4. module. Users should not use this module directly, but import the csv.py
  5. module instead.
  6. */
  7. #define MODULE_VERSION "1.0"
  8. #include "Python.h"
  9. #include "structmember.h" // PyMemberDef
  10. #include <stdbool.h>
  11. /*[clinic input]
  12. module _csv
  13. [clinic start generated code]*/
  14. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=385118b71aa43706]*/
  15. #include "clinic/_csv.c.h"
  16. #define NOT_SET ((Py_UCS4)-1)
  17. #define EOL ((Py_UCS4)-2)
  18. typedef struct {
  19. PyObject *error_obj; /* CSV exception */
  20. PyObject *dialects; /* Dialect registry */
  21. PyTypeObject *dialect_type;
  22. PyTypeObject *reader_type;
  23. PyTypeObject *writer_type;
  24. long field_limit; /* max parsed field size */
  25. PyObject *str_write;
  26. } _csvstate;
  27. static struct PyModuleDef _csvmodule;
  28. static inline _csvstate*
  29. get_csv_state(PyObject *module)
  30. {
  31. void *state = PyModule_GetState(module);
  32. assert(state != NULL);
  33. return (_csvstate *)state;
  34. }
  35. static int
  36. _csv_clear(PyObject *module)
  37. {
  38. _csvstate *module_state = PyModule_GetState(module);
  39. Py_CLEAR(module_state->error_obj);
  40. Py_CLEAR(module_state->dialects);
  41. Py_CLEAR(module_state->dialect_type);
  42. Py_CLEAR(module_state->reader_type);
  43. Py_CLEAR(module_state->writer_type);
  44. Py_CLEAR(module_state->str_write);
  45. return 0;
  46. }
  47. static int
  48. _csv_traverse(PyObject *module, visitproc visit, void *arg)
  49. {
  50. _csvstate *module_state = PyModule_GetState(module);
  51. Py_VISIT(module_state->error_obj);
  52. Py_VISIT(module_state->dialects);
  53. Py_VISIT(module_state->dialect_type);
  54. Py_VISIT(module_state->reader_type);
  55. Py_VISIT(module_state->writer_type);
  56. return 0;
  57. }
  58. static void
  59. _csv_free(void *module)
  60. {
  61. _csv_clear((PyObject *)module);
  62. }
  63. typedef enum {
  64. START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD,
  65. IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD,
  66. EAT_CRNL,AFTER_ESCAPED_CRNL
  67. } ParserState;
  68. typedef enum {
  69. QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE,
  70. QUOTE_STRINGS, QUOTE_NOTNULL
  71. } QuoteStyle;
  72. typedef struct {
  73. QuoteStyle style;
  74. const char *name;
  75. } StyleDesc;
  76. static const StyleDesc quote_styles[] = {
  77. { QUOTE_MINIMAL, "QUOTE_MINIMAL" },
  78. { QUOTE_ALL, "QUOTE_ALL" },
  79. { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" },
  80. { QUOTE_NONE, "QUOTE_NONE" },
  81. { QUOTE_STRINGS, "QUOTE_STRINGS" },
  82. { QUOTE_NOTNULL, "QUOTE_NOTNULL" },
  83. { 0 }
  84. };
  85. typedef struct {
  86. PyObject_HEAD
  87. char doublequote; /* is " represented by ""? */
  88. char skipinitialspace; /* ignore spaces following delimiter? */
  89. char strict; /* raise exception on bad CSV */
  90. int quoting; /* style of quoting to write */
  91. Py_UCS4 delimiter; /* field separator */
  92. Py_UCS4 quotechar; /* quote character */
  93. Py_UCS4 escapechar; /* escape character */
  94. PyObject *lineterminator; /* string to write between records */
  95. } DialectObj;
  96. typedef struct {
  97. PyObject_HEAD
  98. PyObject *input_iter; /* iterate over this for input lines */
  99. DialectObj *dialect; /* parsing dialect */
  100. PyObject *fields; /* field list for current record */
  101. ParserState state; /* current CSV parse state */
  102. Py_UCS4 *field; /* temporary buffer */
  103. Py_ssize_t field_size; /* size of allocated buffer */
  104. Py_ssize_t field_len; /* length of current field */
  105. int numeric_field; /* treat field as numeric */
  106. unsigned long line_num; /* Source-file line number */
  107. } ReaderObj;
  108. typedef struct {
  109. PyObject_HEAD
  110. PyObject *write; /* write output lines to this file */
  111. DialectObj *dialect; /* parsing dialect */
  112. Py_UCS4 *rec; /* buffer for parser.join */
  113. Py_ssize_t rec_size; /* size of allocated record */
  114. Py_ssize_t rec_len; /* length of record */
  115. int num_fields; /* number of fields in record */
  116. PyObject *error_obj; /* cached error object */
  117. } WriterObj;
  118. /*
  119. * DIALECT class
  120. */
  121. static PyObject *
  122. get_dialect_from_registry(PyObject *name_obj, _csvstate *module_state)
  123. {
  124. PyObject *dialect_obj;
  125. dialect_obj = PyDict_GetItemWithError(module_state->dialects, name_obj);
  126. if (dialect_obj == NULL) {
  127. if (!PyErr_Occurred())
  128. PyErr_Format(module_state->error_obj, "unknown dialect");
  129. }
  130. else
  131. Py_INCREF(dialect_obj);
  132. return dialect_obj;
  133. }
  134. static PyObject *
  135. get_char_or_None(Py_UCS4 c)
  136. {
  137. if (c == NOT_SET) {
  138. Py_RETURN_NONE;
  139. }
  140. else
  141. return PyUnicode_FromOrdinal(c);
  142. }
  143. static PyObject *
  144. Dialect_get_lineterminator(DialectObj *self, void *Py_UNUSED(ignored))
  145. {
  146. return Py_XNewRef(self->lineterminator);
  147. }
  148. static PyObject *
  149. Dialect_get_delimiter(DialectObj *self, void *Py_UNUSED(ignored))
  150. {
  151. return get_char_or_None(self->delimiter);
  152. }
  153. static PyObject *
  154. Dialect_get_escapechar(DialectObj *self, void *Py_UNUSED(ignored))
  155. {
  156. return get_char_or_None(self->escapechar);
  157. }
  158. static PyObject *
  159. Dialect_get_quotechar(DialectObj *self, void *Py_UNUSED(ignored))
  160. {
  161. return get_char_or_None(self->quotechar);
  162. }
  163. static PyObject *
  164. Dialect_get_quoting(DialectObj *self, void *Py_UNUSED(ignored))
  165. {
  166. return PyLong_FromLong(self->quoting);
  167. }
  168. static int
  169. _set_bool(const char *name, char *target, PyObject *src, bool dflt)
  170. {
  171. if (src == NULL)
  172. *target = dflt;
  173. else {
  174. int b = PyObject_IsTrue(src);
  175. if (b < 0)
  176. return -1;
  177. *target = (char)b;
  178. }
  179. return 0;
  180. }
  181. static int
  182. _set_int(const char *name, int *target, PyObject *src, int dflt)
  183. {
  184. if (src == NULL)
  185. *target = dflt;
  186. else {
  187. int value;
  188. if (!PyLong_CheckExact(src)) {
  189. PyErr_Format(PyExc_TypeError,
  190. "\"%s\" must be an integer", name);
  191. return -1;
  192. }
  193. value = _PyLong_AsInt(src);
  194. if (value == -1 && PyErr_Occurred()) {
  195. return -1;
  196. }
  197. *target = value;
  198. }
  199. return 0;
  200. }
  201. static int
  202. _set_char_or_none(const char *name, Py_UCS4 *target, PyObject *src, Py_UCS4 dflt)
  203. {
  204. if (src == NULL) {
  205. *target = dflt;
  206. }
  207. else {
  208. *target = NOT_SET;
  209. if (src != Py_None) {
  210. if (!PyUnicode_Check(src)) {
  211. PyErr_Format(PyExc_TypeError,
  212. "\"%s\" must be string or None, not %.200s", name,
  213. Py_TYPE(src)->tp_name);
  214. return -1;
  215. }
  216. Py_ssize_t len = PyUnicode_GetLength(src);
  217. if (len < 0) {
  218. return -1;
  219. }
  220. if (len != 1) {
  221. PyErr_Format(PyExc_TypeError,
  222. "\"%s\" must be a 1-character string",
  223. name);
  224. return -1;
  225. }
  226. /* PyUnicode_READY() is called in PyUnicode_GetLength() */
  227. *target = PyUnicode_READ_CHAR(src, 0);
  228. }
  229. }
  230. return 0;
  231. }
  232. static int
  233. _set_char(const char *name, Py_UCS4 *target, PyObject *src, Py_UCS4 dflt)
  234. {
  235. if (src == NULL) {
  236. *target = dflt;
  237. }
  238. else {
  239. if (!PyUnicode_Check(src)) {
  240. PyErr_Format(PyExc_TypeError,
  241. "\"%s\" must be string, not %.200s", name,
  242. Py_TYPE(src)->tp_name);
  243. return -1;
  244. }
  245. Py_ssize_t len = PyUnicode_GetLength(src);
  246. if (len < 0) {
  247. return -1;
  248. }
  249. if (len != 1) {
  250. PyErr_Format(PyExc_TypeError,
  251. "\"%s\" must be a 1-character string",
  252. name);
  253. return -1;
  254. }
  255. /* PyUnicode_READY() is called in PyUnicode_GetLength() */
  256. *target = PyUnicode_READ_CHAR(src, 0);
  257. }
  258. return 0;
  259. }
  260. static int
  261. _set_str(const char *name, PyObject **target, PyObject *src, const char *dflt)
  262. {
  263. if (src == NULL)
  264. *target = PyUnicode_DecodeASCII(dflt, strlen(dflt), NULL);
  265. else {
  266. if (src == Py_None)
  267. *target = NULL;
  268. else if (!PyUnicode_Check(src)) {
  269. PyErr_Format(PyExc_TypeError,
  270. "\"%s\" must be a string", name);
  271. return -1;
  272. }
  273. else {
  274. if (PyUnicode_READY(src) == -1)
  275. return -1;
  276. Py_XSETREF(*target, Py_NewRef(src));
  277. }
  278. }
  279. return 0;
  280. }
  281. static int
  282. dialect_check_quoting(int quoting)
  283. {
  284. const StyleDesc *qs;
  285. for (qs = quote_styles; qs->name; qs++) {
  286. if ((int)qs->style == quoting)
  287. return 0;
  288. }
  289. PyErr_Format(PyExc_TypeError, "bad \"quoting\" value");
  290. return -1;
  291. }
  292. #define D_OFF(x) offsetof(DialectObj, x)
  293. static struct PyMemberDef Dialect_memberlist[] = {
  294. { "skipinitialspace", T_BOOL, D_OFF(skipinitialspace), READONLY },
  295. { "doublequote", T_BOOL, D_OFF(doublequote), READONLY },
  296. { "strict", T_BOOL, D_OFF(strict), READONLY },
  297. { NULL }
  298. };
  299. static PyGetSetDef Dialect_getsetlist[] = {
  300. { "delimiter", (getter)Dialect_get_delimiter},
  301. { "escapechar", (getter)Dialect_get_escapechar},
  302. { "lineterminator", (getter)Dialect_get_lineterminator},
  303. { "quotechar", (getter)Dialect_get_quotechar},
  304. { "quoting", (getter)Dialect_get_quoting},
  305. {NULL},
  306. };
  307. static void
  308. Dialect_dealloc(DialectObj *self)
  309. {
  310. PyTypeObject *tp = Py_TYPE(self);
  311. PyObject_GC_UnTrack(self);
  312. tp->tp_clear((PyObject *)self);
  313. PyObject_GC_Del(self);
  314. Py_DECREF(tp);
  315. }
  316. static char *dialect_kws[] = {
  317. "dialect",
  318. "delimiter",
  319. "doublequote",
  320. "escapechar",
  321. "lineterminator",
  322. "quotechar",
  323. "quoting",
  324. "skipinitialspace",
  325. "strict",
  326. NULL
  327. };
  328. static _csvstate *
  329. _csv_state_from_type(PyTypeObject *type, const char *name)
  330. {
  331. PyObject *module = PyType_GetModuleByDef(type, &_csvmodule);
  332. if (module == NULL) {
  333. return NULL;
  334. }
  335. _csvstate *module_state = PyModule_GetState(module);
  336. if (module_state == NULL) {
  337. PyErr_Format(PyExc_SystemError,
  338. "%s: No _csv module state found", name);
  339. return NULL;
  340. }
  341. return module_state;
  342. }
  343. static PyObject *
  344. dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
  345. {
  346. DialectObj *self;
  347. PyObject *ret = NULL;
  348. PyObject *dialect = NULL;
  349. PyObject *delimiter = NULL;
  350. PyObject *doublequote = NULL;
  351. PyObject *escapechar = NULL;
  352. PyObject *lineterminator = NULL;
  353. PyObject *quotechar = NULL;
  354. PyObject *quoting = NULL;
  355. PyObject *skipinitialspace = NULL;
  356. PyObject *strict = NULL;
  357. if (!PyArg_ParseTupleAndKeywords(args, kwargs,
  358. "|OOOOOOOOO", dialect_kws,
  359. &dialect,
  360. &delimiter,
  361. &doublequote,
  362. &escapechar,
  363. &lineterminator,
  364. &quotechar,
  365. &quoting,
  366. &skipinitialspace,
  367. &strict))
  368. return NULL;
  369. _csvstate *module_state = _csv_state_from_type(type, "dialect_new");
  370. if (module_state == NULL) {
  371. return NULL;
  372. }
  373. if (dialect != NULL) {
  374. if (PyUnicode_Check(dialect)) {
  375. dialect = get_dialect_from_registry(dialect, module_state);
  376. if (dialect == NULL)
  377. return NULL;
  378. }
  379. else
  380. Py_INCREF(dialect);
  381. /* Can we reuse this instance? */
  382. if (PyObject_TypeCheck(dialect, module_state->dialect_type) &&
  383. delimiter == NULL &&
  384. doublequote == NULL &&
  385. escapechar == NULL &&
  386. lineterminator == NULL &&
  387. quotechar == NULL &&
  388. quoting == NULL &&
  389. skipinitialspace == NULL &&
  390. strict == NULL)
  391. return dialect;
  392. }
  393. self = (DialectObj *)type->tp_alloc(type, 0);
  394. if (self == NULL) {
  395. Py_CLEAR(dialect);
  396. return NULL;
  397. }
  398. self->lineterminator = NULL;
  399. Py_XINCREF(delimiter);
  400. Py_XINCREF(doublequote);
  401. Py_XINCREF(escapechar);
  402. Py_XINCREF(lineterminator);
  403. Py_XINCREF(quotechar);
  404. Py_XINCREF(quoting);
  405. Py_XINCREF(skipinitialspace);
  406. Py_XINCREF(strict);
  407. if (dialect != NULL) {
  408. #define DIALECT_GETATTR(v, n) \
  409. do { \
  410. if (v == NULL) { \
  411. v = PyObject_GetAttrString(dialect, n); \
  412. if (v == NULL) \
  413. PyErr_Clear(); \
  414. } \
  415. } while (0)
  416. DIALECT_GETATTR(delimiter, "delimiter");
  417. DIALECT_GETATTR(doublequote, "doublequote");
  418. DIALECT_GETATTR(escapechar, "escapechar");
  419. DIALECT_GETATTR(lineterminator, "lineterminator");
  420. DIALECT_GETATTR(quotechar, "quotechar");
  421. DIALECT_GETATTR(quoting, "quoting");
  422. DIALECT_GETATTR(skipinitialspace, "skipinitialspace");
  423. DIALECT_GETATTR(strict, "strict");
  424. }
  425. /* check types and convert to C values */
  426. #define DIASET(meth, name, target, src, dflt) \
  427. if (meth(name, target, src, dflt)) \
  428. goto err
  429. DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ',');
  430. DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, true);
  431. DIASET(_set_char_or_none, "escapechar", &self->escapechar, escapechar, NOT_SET);
  432. DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n");
  433. DIASET(_set_char_or_none, "quotechar", &self->quotechar, quotechar, '"');
  434. DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL);
  435. DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, false);
  436. DIASET(_set_bool, "strict", &self->strict, strict, false);
  437. /* validate options */
  438. if (dialect_check_quoting(self->quoting))
  439. goto err;
  440. if (self->delimiter == NOT_SET) {
  441. PyErr_SetString(PyExc_TypeError,
  442. "\"delimiter\" must be a 1-character string");
  443. goto err;
  444. }
  445. if (quotechar == Py_None && quoting == NULL)
  446. self->quoting = QUOTE_NONE;
  447. if (self->quoting != QUOTE_NONE && self->quotechar == NOT_SET) {
  448. PyErr_SetString(PyExc_TypeError,
  449. "quotechar must be set if quoting enabled");
  450. goto err;
  451. }
  452. if (self->lineterminator == NULL) {
  453. PyErr_SetString(PyExc_TypeError, "lineterminator must be set");
  454. goto err;
  455. }
  456. ret = Py_NewRef(self);
  457. err:
  458. Py_CLEAR(self);
  459. Py_CLEAR(dialect);
  460. Py_CLEAR(delimiter);
  461. Py_CLEAR(doublequote);
  462. Py_CLEAR(escapechar);
  463. Py_CLEAR(lineterminator);
  464. Py_CLEAR(quotechar);
  465. Py_CLEAR(quoting);
  466. Py_CLEAR(skipinitialspace);
  467. Py_CLEAR(strict);
  468. return ret;
  469. }
  470. /* Since dialect is now a heap type, it inherits pickling method for
  471. * protocol 0 and 1 from object, therefore it needs to be overridden */
  472. PyDoc_STRVAR(dialect_reduce_doc, "raises an exception to avoid pickling");
  473. static PyObject *
  474. Dialect_reduce(PyObject *self, PyObject *args) {
  475. PyErr_Format(PyExc_TypeError,
  476. "cannot pickle '%.100s' instances", _PyType_Name(Py_TYPE(self)));
  477. return NULL;
  478. }
  479. static struct PyMethodDef dialect_methods[] = {
  480. {"__reduce__", Dialect_reduce, METH_VARARGS, dialect_reduce_doc},
  481. {"__reduce_ex__", Dialect_reduce, METH_VARARGS, dialect_reduce_doc},
  482. {NULL, NULL}
  483. };
  484. PyDoc_STRVAR(Dialect_Type_doc,
  485. "CSV dialect\n"
  486. "\n"
  487. "The Dialect type records CSV parsing and generation options.\n");
  488. static int
  489. Dialect_clear(DialectObj *self)
  490. {
  491. Py_CLEAR(self->lineterminator);
  492. return 0;
  493. }
  494. static int
  495. Dialect_traverse(DialectObj *self, visitproc visit, void *arg)
  496. {
  497. Py_VISIT(self->lineterminator);
  498. Py_VISIT(Py_TYPE(self));
  499. return 0;
  500. }
  501. static PyType_Slot Dialect_Type_slots[] = {
  502. {Py_tp_doc, (char*)Dialect_Type_doc},
  503. {Py_tp_members, Dialect_memberlist},
  504. {Py_tp_getset, Dialect_getsetlist},
  505. {Py_tp_new, dialect_new},
  506. {Py_tp_methods, dialect_methods},
  507. {Py_tp_dealloc, Dialect_dealloc},
  508. {Py_tp_clear, Dialect_clear},
  509. {Py_tp_traverse, Dialect_traverse},
  510. {0, NULL}
  511. };
  512. PyType_Spec Dialect_Type_spec = {
  513. .name = "_csv.Dialect",
  514. .basicsize = sizeof(DialectObj),
  515. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  516. Py_TPFLAGS_IMMUTABLETYPE),
  517. .slots = Dialect_Type_slots,
  518. };
  519. /*
  520. * Return an instance of the dialect type, given a Python instance or kwarg
  521. * description of the dialect
  522. */
  523. static PyObject *
  524. _call_dialect(_csvstate *module_state, PyObject *dialect_inst, PyObject *kwargs)
  525. {
  526. PyObject *type = (PyObject *)module_state->dialect_type;
  527. if (dialect_inst) {
  528. return PyObject_VectorcallDict(type, &dialect_inst, 1, kwargs);
  529. }
  530. else {
  531. return PyObject_VectorcallDict(type, NULL, 0, kwargs);
  532. }
  533. }
  534. /*
  535. * READER
  536. */
  537. static int
  538. parse_save_field(ReaderObj *self)
  539. {
  540. PyObject *field;
  541. field = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
  542. (void *) self->field, self->field_len);
  543. if (field == NULL)
  544. return -1;
  545. self->field_len = 0;
  546. if (self->numeric_field) {
  547. PyObject *tmp;
  548. self->numeric_field = 0;
  549. tmp = PyNumber_Float(field);
  550. Py_DECREF(field);
  551. if (tmp == NULL)
  552. return -1;
  553. field = tmp;
  554. }
  555. if (PyList_Append(self->fields, field) < 0) {
  556. Py_DECREF(field);
  557. return -1;
  558. }
  559. Py_DECREF(field);
  560. return 0;
  561. }
  562. static int
  563. parse_grow_buff(ReaderObj *self)
  564. {
  565. assert((size_t)self->field_size <= PY_SSIZE_T_MAX / sizeof(Py_UCS4));
  566. Py_ssize_t field_size_new = self->field_size ? 2 * self->field_size : 4096;
  567. Py_UCS4 *field_new = self->field;
  568. PyMem_Resize(field_new, Py_UCS4, field_size_new);
  569. if (field_new == NULL) {
  570. PyErr_NoMemory();
  571. return 0;
  572. }
  573. self->field = field_new;
  574. self->field_size = field_size_new;
  575. return 1;
  576. }
  577. static int
  578. parse_add_char(ReaderObj *self, _csvstate *module_state, Py_UCS4 c)
  579. {
  580. if (self->field_len >= module_state->field_limit) {
  581. PyErr_Format(module_state->error_obj,
  582. "field larger than field limit (%ld)",
  583. module_state->field_limit);
  584. return -1;
  585. }
  586. if (self->field_len == self->field_size && !parse_grow_buff(self))
  587. return -1;
  588. self->field[self->field_len++] = c;
  589. return 0;
  590. }
  591. static int
  592. parse_process_char(ReaderObj *self, _csvstate *module_state, Py_UCS4 c)
  593. {
  594. DialectObj *dialect = self->dialect;
  595. switch (self->state) {
  596. case START_RECORD:
  597. /* start of record */
  598. if (c == EOL)
  599. /* empty line - return [] */
  600. break;
  601. else if (c == '\n' || c == '\r') {
  602. self->state = EAT_CRNL;
  603. break;
  604. }
  605. /* normal character - handle as START_FIELD */
  606. self->state = START_FIELD;
  607. /* fallthru */
  608. case START_FIELD:
  609. /* expecting field */
  610. if (c == '\n' || c == '\r' || c == EOL) {
  611. /* save empty field - return [fields] */
  612. if (parse_save_field(self) < 0)
  613. return -1;
  614. self->state = (c == EOL ? START_RECORD : EAT_CRNL);
  615. }
  616. else if (c == dialect->quotechar &&
  617. dialect->quoting != QUOTE_NONE) {
  618. /* start quoted field */
  619. self->state = IN_QUOTED_FIELD;
  620. }
  621. else if (c == dialect->escapechar) {
  622. /* possible escaped character */
  623. self->state = ESCAPED_CHAR;
  624. }
  625. else if (c == ' ' && dialect->skipinitialspace)
  626. /* ignore spaces at start of field */
  627. ;
  628. else if (c == dialect->delimiter) {
  629. /* save empty field */
  630. if (parse_save_field(self) < 0)
  631. return -1;
  632. }
  633. else {
  634. /* begin new unquoted field */
  635. if (dialect->quoting == QUOTE_NONNUMERIC)
  636. self->numeric_field = 1;
  637. if (parse_add_char(self, module_state, c) < 0)
  638. return -1;
  639. self->state = IN_FIELD;
  640. }
  641. break;
  642. case ESCAPED_CHAR:
  643. if (c == '\n' || c=='\r') {
  644. if (parse_add_char(self, module_state, c) < 0)
  645. return -1;
  646. self->state = AFTER_ESCAPED_CRNL;
  647. break;
  648. }
  649. if (c == EOL)
  650. c = '\n';
  651. if (parse_add_char(self, module_state, c) < 0)
  652. return -1;
  653. self->state = IN_FIELD;
  654. break;
  655. case AFTER_ESCAPED_CRNL:
  656. if (c == EOL)
  657. break;
  658. /*fallthru*/
  659. case IN_FIELD:
  660. /* in unquoted field */
  661. if (c == '\n' || c == '\r' || c == EOL) {
  662. /* end of line - return [fields] */
  663. if (parse_save_field(self) < 0)
  664. return -1;
  665. self->state = (c == EOL ? START_RECORD : EAT_CRNL);
  666. }
  667. else if (c == dialect->escapechar) {
  668. /* possible escaped character */
  669. self->state = ESCAPED_CHAR;
  670. }
  671. else if (c == dialect->delimiter) {
  672. /* save field - wait for new field */
  673. if (parse_save_field(self) < 0)
  674. return -1;
  675. self->state = START_FIELD;
  676. }
  677. else {
  678. /* normal character - save in field */
  679. if (parse_add_char(self, module_state, c) < 0)
  680. return -1;
  681. }
  682. break;
  683. case IN_QUOTED_FIELD:
  684. /* in quoted field */
  685. if (c == EOL)
  686. ;
  687. else if (c == dialect->escapechar) {
  688. /* Possible escape character */
  689. self->state = ESCAPE_IN_QUOTED_FIELD;
  690. }
  691. else if (c == dialect->quotechar &&
  692. dialect->quoting != QUOTE_NONE) {
  693. if (dialect->doublequote) {
  694. /* doublequote; " represented by "" */
  695. self->state = QUOTE_IN_QUOTED_FIELD;
  696. }
  697. else {
  698. /* end of quote part of field */
  699. self->state = IN_FIELD;
  700. }
  701. }
  702. else {
  703. /* normal character - save in field */
  704. if (parse_add_char(self, module_state, c) < 0)
  705. return -1;
  706. }
  707. break;
  708. case ESCAPE_IN_QUOTED_FIELD:
  709. if (c == EOL)
  710. c = '\n';
  711. if (parse_add_char(self, module_state, c) < 0)
  712. return -1;
  713. self->state = IN_QUOTED_FIELD;
  714. break;
  715. case QUOTE_IN_QUOTED_FIELD:
  716. /* doublequote - seen a quote in a quoted field */
  717. if (dialect->quoting != QUOTE_NONE &&
  718. c == dialect->quotechar) {
  719. /* save "" as " */
  720. if (parse_add_char(self, module_state, c) < 0)
  721. return -1;
  722. self->state = IN_QUOTED_FIELD;
  723. }
  724. else if (c == dialect->delimiter) {
  725. /* save field - wait for new field */
  726. if (parse_save_field(self) < 0)
  727. return -1;
  728. self->state = START_FIELD;
  729. }
  730. else if (c == '\n' || c == '\r' || c == EOL) {
  731. /* end of line - return [fields] */
  732. if (parse_save_field(self) < 0)
  733. return -1;
  734. self->state = (c == EOL ? START_RECORD : EAT_CRNL);
  735. }
  736. else if (!dialect->strict) {
  737. if (parse_add_char(self, module_state, c) < 0)
  738. return -1;
  739. self->state = IN_FIELD;
  740. }
  741. else {
  742. /* illegal */
  743. PyErr_Format(module_state->error_obj, "'%c' expected after '%c'",
  744. dialect->delimiter,
  745. dialect->quotechar);
  746. return -1;
  747. }
  748. break;
  749. case EAT_CRNL:
  750. if (c == '\n' || c == '\r')
  751. ;
  752. else if (c == EOL)
  753. self->state = START_RECORD;
  754. else {
  755. PyErr_Format(module_state->error_obj,
  756. "new-line character seen in unquoted field - "
  757. "do you need to open the file with newline=''?");
  758. return -1;
  759. }
  760. break;
  761. }
  762. return 0;
  763. }
  764. static int
  765. parse_reset(ReaderObj *self)
  766. {
  767. Py_XSETREF(self->fields, PyList_New(0));
  768. if (self->fields == NULL)
  769. return -1;
  770. self->field_len = 0;
  771. self->state = START_RECORD;
  772. self->numeric_field = 0;
  773. return 0;
  774. }
  775. static PyObject *
  776. Reader_iternext(ReaderObj *self)
  777. {
  778. PyObject *fields = NULL;
  779. Py_UCS4 c;
  780. Py_ssize_t pos, linelen;
  781. int kind;
  782. const void *data;
  783. PyObject *lineobj;
  784. _csvstate *module_state = _csv_state_from_type(Py_TYPE(self),
  785. "Reader.__next__");
  786. if (module_state == NULL) {
  787. return NULL;
  788. }
  789. if (parse_reset(self) < 0)
  790. return NULL;
  791. do {
  792. lineobj = PyIter_Next(self->input_iter);
  793. if (lineobj == NULL) {
  794. /* End of input OR exception */
  795. if (!PyErr_Occurred() && (self->field_len != 0 ||
  796. self->state == IN_QUOTED_FIELD)) {
  797. if (self->dialect->strict)
  798. PyErr_SetString(module_state->error_obj,
  799. "unexpected end of data");
  800. else if (parse_save_field(self) >= 0)
  801. break;
  802. }
  803. return NULL;
  804. }
  805. if (!PyUnicode_Check(lineobj)) {
  806. PyErr_Format(module_state->error_obj,
  807. "iterator should return strings, "
  808. "not %.200s "
  809. "(the file should be opened in text mode)",
  810. Py_TYPE(lineobj)->tp_name
  811. );
  812. Py_DECREF(lineobj);
  813. return NULL;
  814. }
  815. if (PyUnicode_READY(lineobj) == -1) {
  816. Py_DECREF(lineobj);
  817. return NULL;
  818. }
  819. ++self->line_num;
  820. kind = PyUnicode_KIND(lineobj);
  821. data = PyUnicode_DATA(lineobj);
  822. pos = 0;
  823. linelen = PyUnicode_GET_LENGTH(lineobj);
  824. while (linelen--) {
  825. c = PyUnicode_READ(kind, data, pos);
  826. if (parse_process_char(self, module_state, c) < 0) {
  827. Py_DECREF(lineobj);
  828. goto err;
  829. }
  830. pos++;
  831. }
  832. Py_DECREF(lineobj);
  833. if (parse_process_char(self, module_state, EOL) < 0)
  834. goto err;
  835. } while (self->state != START_RECORD);
  836. fields = self->fields;
  837. self->fields = NULL;
  838. err:
  839. return fields;
  840. }
  841. static void
  842. Reader_dealloc(ReaderObj *self)
  843. {
  844. PyTypeObject *tp = Py_TYPE(self);
  845. PyObject_GC_UnTrack(self);
  846. tp->tp_clear((PyObject *)self);
  847. if (self->field != NULL) {
  848. PyMem_Free(self->field);
  849. self->field = NULL;
  850. }
  851. PyObject_GC_Del(self);
  852. Py_DECREF(tp);
  853. }
  854. static int
  855. Reader_traverse(ReaderObj *self, visitproc visit, void *arg)
  856. {
  857. Py_VISIT(self->dialect);
  858. Py_VISIT(self->input_iter);
  859. Py_VISIT(self->fields);
  860. Py_VISIT(Py_TYPE(self));
  861. return 0;
  862. }
  863. static int
  864. Reader_clear(ReaderObj *self)
  865. {
  866. Py_CLEAR(self->dialect);
  867. Py_CLEAR(self->input_iter);
  868. Py_CLEAR(self->fields);
  869. return 0;
  870. }
  871. PyDoc_STRVAR(Reader_Type_doc,
  872. "CSV reader\n"
  873. "\n"
  874. "Reader objects are responsible for reading and parsing tabular data\n"
  875. "in CSV format.\n"
  876. );
  877. static struct PyMethodDef Reader_methods[] = {
  878. { NULL, NULL }
  879. };
  880. #define R_OFF(x) offsetof(ReaderObj, x)
  881. static struct PyMemberDef Reader_memberlist[] = {
  882. { "dialect", T_OBJECT, R_OFF(dialect), READONLY },
  883. { "line_num", T_ULONG, R_OFF(line_num), READONLY },
  884. { NULL }
  885. };
  886. static PyType_Slot Reader_Type_slots[] = {
  887. {Py_tp_doc, (char*)Reader_Type_doc},
  888. {Py_tp_traverse, Reader_traverse},
  889. {Py_tp_iter, PyObject_SelfIter},
  890. {Py_tp_iternext, Reader_iternext},
  891. {Py_tp_methods, Reader_methods},
  892. {Py_tp_members, Reader_memberlist},
  893. {Py_tp_clear, Reader_clear},
  894. {Py_tp_dealloc, Reader_dealloc},
  895. {0, NULL}
  896. };
  897. PyType_Spec Reader_Type_spec = {
  898. .name = "_csv.reader",
  899. .basicsize = sizeof(ReaderObj),
  900. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  901. Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  902. .slots = Reader_Type_slots
  903. };
  904. static PyObject *
  905. csv_reader(PyObject *module, PyObject *args, PyObject *keyword_args)
  906. {
  907. PyObject * iterator, * dialect = NULL;
  908. _csvstate *module_state = get_csv_state(module);
  909. ReaderObj * self = PyObject_GC_New(
  910. ReaderObj,
  911. module_state->reader_type);
  912. if (!self)
  913. return NULL;
  914. self->dialect = NULL;
  915. self->fields = NULL;
  916. self->input_iter = NULL;
  917. self->field = NULL;
  918. self->field_size = 0;
  919. self->line_num = 0;
  920. if (parse_reset(self) < 0) {
  921. Py_DECREF(self);
  922. return NULL;
  923. }
  924. if (!PyArg_UnpackTuple(args, "", 1, 2, &iterator, &dialect)) {
  925. Py_DECREF(self);
  926. return NULL;
  927. }
  928. self->input_iter = PyObject_GetIter(iterator);
  929. if (self->input_iter == NULL) {
  930. Py_DECREF(self);
  931. return NULL;
  932. }
  933. self->dialect = (DialectObj *)_call_dialect(module_state, dialect,
  934. keyword_args);
  935. if (self->dialect == NULL) {
  936. Py_DECREF(self);
  937. return NULL;
  938. }
  939. PyObject_GC_Track(self);
  940. return (PyObject *)self;
  941. }
  942. /*
  943. * WRITER
  944. */
  945. /* ---------------------------------------------------------------- */
  946. static void
  947. join_reset(WriterObj *self)
  948. {
  949. self->rec_len = 0;
  950. self->num_fields = 0;
  951. }
  952. #define MEM_INCR 32768
  953. /* Calculate new record length or append field to record. Return new
  954. * record length.
  955. */
  956. static Py_ssize_t
  957. join_append_data(WriterObj *self, int field_kind, const void *field_data,
  958. Py_ssize_t field_len, int *quoted,
  959. int copy_phase)
  960. {
  961. DialectObj *dialect = self->dialect;
  962. int i;
  963. Py_ssize_t rec_len;
  964. #define INCLEN \
  965. do {\
  966. if (!copy_phase && rec_len == PY_SSIZE_T_MAX) { \
  967. goto overflow; \
  968. } \
  969. rec_len++; \
  970. } while(0)
  971. #define ADDCH(c) \
  972. do {\
  973. if (copy_phase) \
  974. self->rec[rec_len] = c;\
  975. INCLEN;\
  976. } while(0)
  977. rec_len = self->rec_len;
  978. /* If this is not the first field we need a field separator */
  979. if (self->num_fields > 0)
  980. ADDCH(dialect->delimiter);
  981. /* Handle preceding quote */
  982. if (copy_phase && *quoted)
  983. ADDCH(dialect->quotechar);
  984. /* Copy/count field data */
  985. /* If field is null just pass over */
  986. for (i = 0; field_data && (i < field_len); i++) {
  987. Py_UCS4 c = PyUnicode_READ(field_kind, field_data, i);
  988. int want_escape = 0;
  989. if (c == dialect->delimiter ||
  990. c == dialect->escapechar ||
  991. c == dialect->quotechar ||
  992. c == '\n' ||
  993. c == '\r' ||
  994. PyUnicode_FindChar(
  995. dialect->lineterminator, c, 0,
  996. PyUnicode_GET_LENGTH(dialect->lineterminator), 1) >= 0) {
  997. if (dialect->quoting == QUOTE_NONE)
  998. want_escape = 1;
  999. else {
  1000. if (c == dialect->quotechar) {
  1001. if (dialect->doublequote)
  1002. ADDCH(dialect->quotechar);
  1003. else
  1004. want_escape = 1;
  1005. }
  1006. else if (c == dialect->escapechar) {
  1007. want_escape = 1;
  1008. }
  1009. if (!want_escape)
  1010. *quoted = 1;
  1011. }
  1012. if (want_escape) {
  1013. if (dialect->escapechar == NOT_SET) {
  1014. PyErr_Format(self->error_obj,
  1015. "need to escape, but no escapechar set");
  1016. return -1;
  1017. }
  1018. ADDCH(dialect->escapechar);
  1019. }
  1020. }
  1021. /* Copy field character into record buffer.
  1022. */
  1023. ADDCH(c);
  1024. }
  1025. if (*quoted) {
  1026. if (copy_phase)
  1027. ADDCH(dialect->quotechar);
  1028. else {
  1029. INCLEN; /* starting quote */
  1030. INCLEN; /* ending quote */
  1031. }
  1032. }
  1033. return rec_len;
  1034. overflow:
  1035. PyErr_NoMemory();
  1036. return -1;
  1037. #undef ADDCH
  1038. #undef INCLEN
  1039. }
  1040. static int
  1041. join_check_rec_size(WriterObj *self, Py_ssize_t rec_len)
  1042. {
  1043. assert(rec_len >= 0);
  1044. if (rec_len > self->rec_size) {
  1045. size_t rec_size_new = (size_t)(rec_len / MEM_INCR + 1) * MEM_INCR;
  1046. Py_UCS4 *rec_new = self->rec;
  1047. PyMem_Resize(rec_new, Py_UCS4, rec_size_new);
  1048. if (rec_new == NULL) {
  1049. PyErr_NoMemory();
  1050. return 0;
  1051. }
  1052. self->rec = rec_new;
  1053. self->rec_size = (Py_ssize_t)rec_size_new;
  1054. }
  1055. return 1;
  1056. }
  1057. static int
  1058. join_append(WriterObj *self, PyObject *field, int quoted)
  1059. {
  1060. DialectObj *dialect = self->dialect;
  1061. int field_kind = -1;
  1062. const void *field_data = NULL;
  1063. Py_ssize_t field_len = 0;
  1064. Py_ssize_t rec_len;
  1065. if (field != NULL) {
  1066. if (PyUnicode_READY(field) == -1)
  1067. return 0;
  1068. field_kind = PyUnicode_KIND(field);
  1069. field_data = PyUnicode_DATA(field);
  1070. field_len = PyUnicode_GET_LENGTH(field);
  1071. }
  1072. if (!field_len && dialect->delimiter == ' ' && dialect->skipinitialspace) {
  1073. if (dialect->quoting == QUOTE_NONE ||
  1074. (field == NULL &&
  1075. (dialect->quoting == QUOTE_STRINGS ||
  1076. dialect->quoting == QUOTE_NOTNULL)))
  1077. {
  1078. PyErr_Format(self->error_obj,
  1079. "empty field must be quoted if delimiter is a space "
  1080. "and skipinitialspace is true");
  1081. return 0;
  1082. }
  1083. quoted = 1;
  1084. }
  1085. rec_len = join_append_data(self, field_kind, field_data, field_len,
  1086. &quoted, 0);
  1087. if (rec_len < 0)
  1088. return 0;
  1089. /* grow record buffer if necessary */
  1090. if (!join_check_rec_size(self, rec_len))
  1091. return 0;
  1092. self->rec_len = join_append_data(self, field_kind, field_data, field_len,
  1093. &quoted, 1);
  1094. self->num_fields++;
  1095. return 1;
  1096. }
  1097. static int
  1098. join_append_lineterminator(WriterObj *self)
  1099. {
  1100. Py_ssize_t terminator_len, i;
  1101. int term_kind;
  1102. const void *term_data;
  1103. terminator_len = PyUnicode_GET_LENGTH(self->dialect->lineterminator);
  1104. if (terminator_len == -1)
  1105. return 0;
  1106. /* grow record buffer if necessary */
  1107. if (!join_check_rec_size(self, self->rec_len + terminator_len))
  1108. return 0;
  1109. term_kind = PyUnicode_KIND(self->dialect->lineterminator);
  1110. term_data = PyUnicode_DATA(self->dialect->lineterminator);
  1111. for (i = 0; i < terminator_len; i++)
  1112. self->rec[self->rec_len + i] = PyUnicode_READ(term_kind, term_data, i);
  1113. self->rec_len += terminator_len;
  1114. return 1;
  1115. }
  1116. PyDoc_STRVAR(csv_writerow_doc,
  1117. "writerow(iterable)\n"
  1118. "\n"
  1119. "Construct and write a CSV record from an iterable of fields. Non-string\n"
  1120. "elements will be converted to string.");
  1121. static PyObject *
  1122. csv_writerow(WriterObj *self, PyObject *seq)
  1123. {
  1124. DialectObj *dialect = self->dialect;
  1125. PyObject *iter, *field, *line, *result;
  1126. bool null_field = false;
  1127. iter = PyObject_GetIter(seq);
  1128. if (iter == NULL) {
  1129. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  1130. PyErr_Format(self->error_obj,
  1131. "iterable expected, not %.200s",
  1132. Py_TYPE(seq)->tp_name);
  1133. }
  1134. return NULL;
  1135. }
  1136. /* Join all fields in internal buffer.
  1137. */
  1138. join_reset(self);
  1139. while ((field = PyIter_Next(iter))) {
  1140. int append_ok;
  1141. int quoted;
  1142. switch (dialect->quoting) {
  1143. case QUOTE_NONNUMERIC:
  1144. quoted = !PyNumber_Check(field);
  1145. break;
  1146. case QUOTE_ALL:
  1147. quoted = 1;
  1148. break;
  1149. case QUOTE_STRINGS:
  1150. quoted = PyUnicode_Check(field);
  1151. break;
  1152. case QUOTE_NOTNULL:
  1153. quoted = field != Py_None;
  1154. break;
  1155. default:
  1156. quoted = 0;
  1157. break;
  1158. }
  1159. null_field = (field == Py_None);
  1160. if (PyUnicode_Check(field)) {
  1161. append_ok = join_append(self, field, quoted);
  1162. Py_DECREF(field);
  1163. }
  1164. else if (null_field) {
  1165. append_ok = join_append(self, NULL, quoted);
  1166. Py_DECREF(field);
  1167. }
  1168. else {
  1169. PyObject *str;
  1170. str = PyObject_Str(field);
  1171. Py_DECREF(field);
  1172. if (str == NULL) {
  1173. Py_DECREF(iter);
  1174. return NULL;
  1175. }
  1176. append_ok = join_append(self, str, quoted);
  1177. Py_DECREF(str);
  1178. }
  1179. if (!append_ok) {
  1180. Py_DECREF(iter);
  1181. return NULL;
  1182. }
  1183. }
  1184. Py_DECREF(iter);
  1185. if (PyErr_Occurred())
  1186. return NULL;
  1187. if (self->num_fields > 0 && self->rec_len == 0) {
  1188. if (dialect->quoting == QUOTE_NONE ||
  1189. (null_field &&
  1190. (dialect->quoting == QUOTE_STRINGS ||
  1191. dialect->quoting == QUOTE_NOTNULL)))
  1192. {
  1193. PyErr_Format(self->error_obj,
  1194. "single empty field record must be quoted");
  1195. return NULL;
  1196. }
  1197. self->num_fields--;
  1198. if (!join_append(self, NULL, 1))
  1199. return NULL;
  1200. }
  1201. /* Add line terminator.
  1202. */
  1203. if (!join_append_lineterminator(self)) {
  1204. return NULL;
  1205. }
  1206. line = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
  1207. (void *) self->rec, self->rec_len);
  1208. if (line == NULL) {
  1209. return NULL;
  1210. }
  1211. result = PyObject_CallOneArg(self->write, line);
  1212. Py_DECREF(line);
  1213. return result;
  1214. }
  1215. PyDoc_STRVAR(csv_writerows_doc,
  1216. "writerows(iterable of iterables)\n"
  1217. "\n"
  1218. "Construct and write a series of iterables to a csv file. Non-string\n"
  1219. "elements will be converted to string.");
  1220. static PyObject *
  1221. csv_writerows(WriterObj *self, PyObject *seqseq)
  1222. {
  1223. PyObject *row_iter, *row_obj, *result;
  1224. row_iter = PyObject_GetIter(seqseq);
  1225. if (row_iter == NULL) {
  1226. return NULL;
  1227. }
  1228. while ((row_obj = PyIter_Next(row_iter))) {
  1229. result = csv_writerow(self, row_obj);
  1230. Py_DECREF(row_obj);
  1231. if (!result) {
  1232. Py_DECREF(row_iter);
  1233. return NULL;
  1234. }
  1235. else
  1236. Py_DECREF(result);
  1237. }
  1238. Py_DECREF(row_iter);
  1239. if (PyErr_Occurred())
  1240. return NULL;
  1241. Py_RETURN_NONE;
  1242. }
  1243. static struct PyMethodDef Writer_methods[] = {
  1244. { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc},
  1245. { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc},
  1246. { NULL, NULL }
  1247. };
  1248. #define W_OFF(x) offsetof(WriterObj, x)
  1249. static struct PyMemberDef Writer_memberlist[] = {
  1250. { "dialect", T_OBJECT, W_OFF(dialect), READONLY },
  1251. { NULL }
  1252. };
  1253. static int
  1254. Writer_traverse(WriterObj *self, visitproc visit, void *arg)
  1255. {
  1256. Py_VISIT(self->dialect);
  1257. Py_VISIT(self->write);
  1258. Py_VISIT(self->error_obj);
  1259. Py_VISIT(Py_TYPE(self));
  1260. return 0;
  1261. }
  1262. static int
  1263. Writer_clear(WriterObj *self)
  1264. {
  1265. Py_CLEAR(self->dialect);
  1266. Py_CLEAR(self->write);
  1267. Py_CLEAR(self->error_obj);
  1268. return 0;
  1269. }
  1270. static void
  1271. Writer_dealloc(WriterObj *self)
  1272. {
  1273. PyTypeObject *tp = Py_TYPE(self);
  1274. PyObject_GC_UnTrack(self);
  1275. tp->tp_clear((PyObject *)self);
  1276. if (self->rec != NULL) {
  1277. PyMem_Free(self->rec);
  1278. }
  1279. PyObject_GC_Del(self);
  1280. Py_DECREF(tp);
  1281. }
  1282. PyDoc_STRVAR(Writer_Type_doc,
  1283. "CSV writer\n"
  1284. "\n"
  1285. "Writer objects are responsible for generating tabular data\n"
  1286. "in CSV format from sequence input.\n"
  1287. );
  1288. static PyType_Slot Writer_Type_slots[] = {
  1289. {Py_tp_doc, (char*)Writer_Type_doc},
  1290. {Py_tp_traverse, Writer_traverse},
  1291. {Py_tp_clear, Writer_clear},
  1292. {Py_tp_dealloc, Writer_dealloc},
  1293. {Py_tp_methods, Writer_methods},
  1294. {Py_tp_members, Writer_memberlist},
  1295. {0, NULL}
  1296. };
  1297. PyType_Spec Writer_Type_spec = {
  1298. .name = "_csv.writer",
  1299. .basicsize = sizeof(WriterObj),
  1300. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  1301. Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  1302. .slots = Writer_Type_slots,
  1303. };
  1304. static PyObject *
  1305. csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args)
  1306. {
  1307. PyObject * output_file, * dialect = NULL;
  1308. _csvstate *module_state = get_csv_state(module);
  1309. WriterObj * self = PyObject_GC_New(WriterObj, module_state->writer_type);
  1310. if (!self)
  1311. return NULL;
  1312. self->dialect = NULL;
  1313. self->write = NULL;
  1314. self->rec = NULL;
  1315. self->rec_size = 0;
  1316. self->rec_len = 0;
  1317. self->num_fields = 0;
  1318. self->error_obj = Py_NewRef(module_state->error_obj);
  1319. if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) {
  1320. Py_DECREF(self);
  1321. return NULL;
  1322. }
  1323. if (_PyObject_LookupAttr(output_file,
  1324. module_state->str_write,
  1325. &self->write) < 0) {
  1326. Py_DECREF(self);
  1327. return NULL;
  1328. }
  1329. if (self->write == NULL || !PyCallable_Check(self->write)) {
  1330. PyErr_SetString(PyExc_TypeError,
  1331. "argument 1 must have a \"write\" method");
  1332. Py_DECREF(self);
  1333. return NULL;
  1334. }
  1335. self->dialect = (DialectObj *)_call_dialect(module_state, dialect,
  1336. keyword_args);
  1337. if (self->dialect == NULL) {
  1338. Py_DECREF(self);
  1339. return NULL;
  1340. }
  1341. PyObject_GC_Track(self);
  1342. return (PyObject *)self;
  1343. }
  1344. /*
  1345. * DIALECT REGISTRY
  1346. */
  1347. /*[clinic input]
  1348. _csv.list_dialects
  1349. Return a list of all known dialect names.
  1350. names = csv.list_dialects()
  1351. [clinic start generated code]*/
  1352. static PyObject *
  1353. _csv_list_dialects_impl(PyObject *module)
  1354. /*[clinic end generated code: output=a5b92b215b006a6d input=8953943eb17d98ab]*/
  1355. {
  1356. return PyDict_Keys(get_csv_state(module)->dialects);
  1357. }
  1358. static PyObject *
  1359. csv_register_dialect(PyObject *module, PyObject *args, PyObject *kwargs)
  1360. {
  1361. PyObject *name_obj, *dialect_obj = NULL;
  1362. _csvstate *module_state = get_csv_state(module);
  1363. PyObject *dialect;
  1364. if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj))
  1365. return NULL;
  1366. if (!PyUnicode_Check(name_obj)) {
  1367. PyErr_SetString(PyExc_TypeError,
  1368. "dialect name must be a string");
  1369. return NULL;
  1370. }
  1371. if (PyUnicode_READY(name_obj) == -1)
  1372. return NULL;
  1373. dialect = _call_dialect(module_state, dialect_obj, kwargs);
  1374. if (dialect == NULL)
  1375. return NULL;
  1376. if (PyDict_SetItem(module_state->dialects, name_obj, dialect) < 0) {
  1377. Py_DECREF(dialect);
  1378. return NULL;
  1379. }
  1380. Py_DECREF(dialect);
  1381. Py_RETURN_NONE;
  1382. }
  1383. /*[clinic input]
  1384. _csv.unregister_dialect
  1385. name: object
  1386. Delete the name/dialect mapping associated with a string name.
  1387. csv.unregister_dialect(name)
  1388. [clinic start generated code]*/
  1389. static PyObject *
  1390. _csv_unregister_dialect_impl(PyObject *module, PyObject *name)
  1391. /*[clinic end generated code: output=0813ebca6c058df4 input=6b5c1557bf60c7e7]*/
  1392. {
  1393. _csvstate *module_state = get_csv_state(module);
  1394. if (PyDict_DelItem(module_state->dialects, name) < 0) {
  1395. if (PyErr_ExceptionMatches(PyExc_KeyError)) {
  1396. PyErr_Format(module_state->error_obj, "unknown dialect");
  1397. }
  1398. return NULL;
  1399. }
  1400. Py_RETURN_NONE;
  1401. }
  1402. /*[clinic input]
  1403. _csv.get_dialect
  1404. name: object
  1405. Return the dialect instance associated with name.
  1406. dialect = csv.get_dialect(name)
  1407. [clinic start generated code]*/
  1408. static PyObject *
  1409. _csv_get_dialect_impl(PyObject *module, PyObject *name)
  1410. /*[clinic end generated code: output=aa988cd573bebebb input=edf9ddab32e448fb]*/
  1411. {
  1412. return get_dialect_from_registry(name, get_csv_state(module));
  1413. }
  1414. /*[clinic input]
  1415. _csv.field_size_limit
  1416. new_limit: object = NULL
  1417. Sets an upper limit on parsed fields.
  1418. csv.field_size_limit([limit])
  1419. Returns old limit. If limit is not given, no new limit is set and
  1420. the old limit is returned
  1421. [clinic start generated code]*/
  1422. static PyObject *
  1423. _csv_field_size_limit_impl(PyObject *module, PyObject *new_limit)
  1424. /*[clinic end generated code: output=f2799ecd908e250b input=cec70e9226406435]*/
  1425. {
  1426. _csvstate *module_state = get_csv_state(module);
  1427. long old_limit = module_state->field_limit;
  1428. if (new_limit != NULL) {
  1429. if (!PyLong_CheckExact(new_limit)) {
  1430. PyErr_Format(PyExc_TypeError,
  1431. "limit must be an integer");
  1432. return NULL;
  1433. }
  1434. module_state->field_limit = PyLong_AsLong(new_limit);
  1435. if (module_state->field_limit == -1 && PyErr_Occurred()) {
  1436. module_state->field_limit = old_limit;
  1437. return NULL;
  1438. }
  1439. }
  1440. return PyLong_FromLong(old_limit);
  1441. }
  1442. static PyType_Slot error_slots[] = {
  1443. {0, NULL},
  1444. };
  1445. PyType_Spec error_spec = {
  1446. .name = "_csv.Error",
  1447. .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
  1448. .slots = error_slots,
  1449. };
  1450. /*
  1451. * MODULE
  1452. */
  1453. PyDoc_STRVAR(csv_module_doc,
  1454. "CSV parsing and writing.\n"
  1455. "\n"
  1456. "This module provides classes that assist in the reading and writing\n"
  1457. "of Comma Separated Value (CSV) files, and implements the interface\n"
  1458. "described by PEP 305. Although many CSV files are simple to parse,\n"
  1459. "the format is not formally defined by a stable specification and\n"
  1460. "is subtle enough that parsing lines of a CSV file with something\n"
  1461. "like line.split(\",\") is bound to fail. The module supports three\n"
  1462. "basic APIs: reading, writing, and registration of dialects.\n"
  1463. "\n"
  1464. "\n"
  1465. "DIALECT REGISTRATION:\n"
  1466. "\n"
  1467. "Readers and writers support a dialect argument, which is a convenient\n"
  1468. "handle on a group of settings. When the dialect argument is a string,\n"
  1469. "it identifies one of the dialects previously registered with the module.\n"
  1470. "If it is a class or instance, the attributes of the argument are used as\n"
  1471. "the settings for the reader or writer:\n"
  1472. "\n"
  1473. " class excel:\n"
  1474. " delimiter = ','\n"
  1475. " quotechar = '\"'\n"
  1476. " escapechar = None\n"
  1477. " doublequote = True\n"
  1478. " skipinitialspace = False\n"
  1479. " lineterminator = '\\r\\n'\n"
  1480. " quoting = QUOTE_MINIMAL\n"
  1481. "\n"
  1482. "SETTINGS:\n"
  1483. "\n"
  1484. " * quotechar - specifies a one-character string to use as the\n"
  1485. " quoting character. It defaults to '\"'.\n"
  1486. " * delimiter - specifies a one-character string to use as the\n"
  1487. " field separator. It defaults to ','.\n"
  1488. " * skipinitialspace - specifies how to interpret spaces which\n"
  1489. " immediately follow a delimiter. It defaults to False, which\n"
  1490. " means that spaces immediately following a delimiter is part\n"
  1491. " of the following field.\n"
  1492. " * lineterminator - specifies the character sequence which should\n"
  1493. " terminate rows.\n"
  1494. " * quoting - controls when quotes should be generated by the writer.\n"
  1495. " It can take on any of the following module constants:\n"
  1496. "\n"
  1497. " csv.QUOTE_MINIMAL means only when required, for example, when a\n"
  1498. " field contains either the quotechar or the delimiter\n"
  1499. " csv.QUOTE_ALL means that quotes are always placed around fields.\n"
  1500. " csv.QUOTE_NONNUMERIC means that quotes are always placed around\n"
  1501. " fields which do not parse as integers or floating point\n"
  1502. " numbers.\n"
  1503. " csv.QUOTE_STRINGS means that quotes are always placed around\n"
  1504. " fields which are strings. Note that the Python value None\n"
  1505. " is not a string.\n"
  1506. " csv.QUOTE_NOTNULL means that quotes are only placed around fields\n"
  1507. " that are not the Python value None.\n"
  1508. " csv.QUOTE_NONE means that quotes are never placed around fields.\n"
  1509. " * escapechar - specifies a one-character string used to escape\n"
  1510. " the delimiter when quoting is set to QUOTE_NONE.\n"
  1511. " * doublequote - controls the handling of quotes inside fields. When\n"
  1512. " True, two consecutive quotes are interpreted as one during read,\n"
  1513. " and when writing, each quote character embedded in the data is\n"
  1514. " written as two quotes\n");
  1515. PyDoc_STRVAR(csv_reader_doc,
  1516. " csv_reader = reader(iterable [, dialect='excel']\n"
  1517. " [optional keyword args])\n"
  1518. " for row in csv_reader:\n"
  1519. " process(row)\n"
  1520. "\n"
  1521. "The \"iterable\" argument can be any object that returns a line\n"
  1522. "of input for each iteration, such as a file object or a list. The\n"
  1523. "optional \"dialect\" parameter is discussed below. The function\n"
  1524. "also accepts optional keyword arguments which override settings\n"
  1525. "provided by the dialect.\n"
  1526. "\n"
  1527. "The returned object is an iterator. Each iteration returns a row\n"
  1528. "of the CSV file (which can span multiple input lines).\n");
  1529. PyDoc_STRVAR(csv_writer_doc,
  1530. " csv_writer = csv.writer(fileobj [, dialect='excel']\n"
  1531. " [optional keyword args])\n"
  1532. " for row in sequence:\n"
  1533. " csv_writer.writerow(row)\n"
  1534. "\n"
  1535. " [or]\n"
  1536. "\n"
  1537. " csv_writer = csv.writer(fileobj [, dialect='excel']\n"
  1538. " [optional keyword args])\n"
  1539. " csv_writer.writerows(rows)\n"
  1540. "\n"
  1541. "The \"fileobj\" argument can be any object that supports the file API.\n");
  1542. PyDoc_STRVAR(csv_register_dialect_doc,
  1543. "Create a mapping from a string name to a dialect class.\n"
  1544. " dialect = csv.register_dialect(name[, dialect[, **fmtparams]])");
  1545. static struct PyMethodDef csv_methods[] = {
  1546. { "reader", _PyCFunction_CAST(csv_reader),
  1547. METH_VARARGS | METH_KEYWORDS, csv_reader_doc},
  1548. { "writer", _PyCFunction_CAST(csv_writer),
  1549. METH_VARARGS | METH_KEYWORDS, csv_writer_doc},
  1550. { "register_dialect", _PyCFunction_CAST(csv_register_dialect),
  1551. METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc},
  1552. _CSV_LIST_DIALECTS_METHODDEF
  1553. _CSV_UNREGISTER_DIALECT_METHODDEF
  1554. _CSV_GET_DIALECT_METHODDEF
  1555. _CSV_FIELD_SIZE_LIMIT_METHODDEF
  1556. { NULL, NULL }
  1557. };
  1558. static int
  1559. csv_exec(PyObject *module) {
  1560. const StyleDesc *style;
  1561. PyObject *temp;
  1562. _csvstate *module_state = get_csv_state(module);
  1563. temp = PyType_FromModuleAndSpec(module, &Dialect_Type_spec, NULL);
  1564. module_state->dialect_type = (PyTypeObject *)temp;
  1565. if (PyModule_AddObjectRef(module, "Dialect", temp) < 0) {
  1566. return -1;
  1567. }
  1568. temp = PyType_FromModuleAndSpec(module, &Reader_Type_spec, NULL);
  1569. module_state->reader_type = (PyTypeObject *)temp;
  1570. if (PyModule_AddObjectRef(module, "Reader", temp) < 0) {
  1571. return -1;
  1572. }
  1573. temp = PyType_FromModuleAndSpec(module, &Writer_Type_spec, NULL);
  1574. module_state->writer_type = (PyTypeObject *)temp;
  1575. if (PyModule_AddObjectRef(module, "Writer", temp) < 0) {
  1576. return -1;
  1577. }
  1578. /* Add version to the module. */
  1579. if (PyModule_AddStringConstant(module, "__version__",
  1580. MODULE_VERSION) == -1) {
  1581. return -1;
  1582. }
  1583. /* Set the field limit */
  1584. module_state->field_limit = 128 * 1024;
  1585. /* Add _dialects dictionary */
  1586. module_state->dialects = PyDict_New();
  1587. if (PyModule_AddObjectRef(module, "_dialects", module_state->dialects) < 0) {
  1588. return -1;
  1589. }
  1590. /* Add quote styles into dictionary */
  1591. for (style = quote_styles; style->name; style++) {
  1592. if (PyModule_AddIntConstant(module, style->name,
  1593. style->style) == -1)
  1594. return -1;
  1595. }
  1596. /* Add the CSV exception object to the module. */
  1597. PyObject *bases = PyTuple_Pack(1, PyExc_Exception);
  1598. if (bases == NULL) {
  1599. return -1;
  1600. }
  1601. module_state->error_obj = PyType_FromModuleAndSpec(module, &error_spec,
  1602. bases);
  1603. Py_DECREF(bases);
  1604. if (module_state->error_obj == NULL) {
  1605. return -1;
  1606. }
  1607. if (PyModule_AddType(module, (PyTypeObject *)module_state->error_obj) != 0) {
  1608. return -1;
  1609. }
  1610. module_state->str_write = PyUnicode_InternFromString("write");
  1611. if (module_state->str_write == NULL) {
  1612. return -1;
  1613. }
  1614. return 0;
  1615. }
  1616. static PyModuleDef_Slot csv_slots[] = {
  1617. {Py_mod_exec, csv_exec},
  1618. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1619. {0, NULL}
  1620. };
  1621. static struct PyModuleDef _csvmodule = {
  1622. PyModuleDef_HEAD_INIT,
  1623. "_csv",
  1624. csv_module_doc,
  1625. sizeof(_csvstate),
  1626. csv_methods,
  1627. csv_slots,
  1628. _csv_traverse,
  1629. _csv_clear,
  1630. _csv_free
  1631. };
  1632. PyMODINIT_FUNC
  1633. PyInit__csv(void)
  1634. {
  1635. return PyModuleDef_Init(&_csvmodule);
  1636. }