_csv.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822
  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. PyUnicode_FindChar(
  993. dialect->lineterminator, c, 0,
  994. PyUnicode_GET_LENGTH(dialect->lineterminator), 1) >= 0) {
  995. if (dialect->quoting == QUOTE_NONE)
  996. want_escape = 1;
  997. else {
  998. if (c == dialect->quotechar) {
  999. if (dialect->doublequote)
  1000. ADDCH(dialect->quotechar);
  1001. else
  1002. want_escape = 1;
  1003. }
  1004. else if (c == dialect->escapechar) {
  1005. want_escape = 1;
  1006. }
  1007. if (!want_escape)
  1008. *quoted = 1;
  1009. }
  1010. if (want_escape) {
  1011. if (dialect->escapechar == NOT_SET) {
  1012. PyErr_Format(self->error_obj,
  1013. "need to escape, but no escapechar set");
  1014. return -1;
  1015. }
  1016. ADDCH(dialect->escapechar);
  1017. }
  1018. }
  1019. /* Copy field character into record buffer.
  1020. */
  1021. ADDCH(c);
  1022. }
  1023. if (*quoted) {
  1024. if (copy_phase)
  1025. ADDCH(dialect->quotechar);
  1026. else {
  1027. INCLEN; /* starting quote */
  1028. INCLEN; /* ending quote */
  1029. }
  1030. }
  1031. return rec_len;
  1032. overflow:
  1033. PyErr_NoMemory();
  1034. return -1;
  1035. #undef ADDCH
  1036. #undef INCLEN
  1037. }
  1038. static int
  1039. join_check_rec_size(WriterObj *self, Py_ssize_t rec_len)
  1040. {
  1041. assert(rec_len >= 0);
  1042. if (rec_len > self->rec_size) {
  1043. size_t rec_size_new = (size_t)(rec_len / MEM_INCR + 1) * MEM_INCR;
  1044. Py_UCS4 *rec_new = self->rec;
  1045. PyMem_Resize(rec_new, Py_UCS4, rec_size_new);
  1046. if (rec_new == NULL) {
  1047. PyErr_NoMemory();
  1048. return 0;
  1049. }
  1050. self->rec = rec_new;
  1051. self->rec_size = (Py_ssize_t)rec_size_new;
  1052. }
  1053. return 1;
  1054. }
  1055. static int
  1056. join_append(WriterObj *self, PyObject *field, int quoted)
  1057. {
  1058. int field_kind = -1;
  1059. const void *field_data = NULL;
  1060. Py_ssize_t field_len = 0;
  1061. Py_ssize_t rec_len;
  1062. if (field != NULL) {
  1063. if (PyUnicode_READY(field) == -1)
  1064. return 0;
  1065. field_kind = PyUnicode_KIND(field);
  1066. field_data = PyUnicode_DATA(field);
  1067. field_len = PyUnicode_GET_LENGTH(field);
  1068. }
  1069. rec_len = join_append_data(self, field_kind, field_data, field_len,
  1070. &quoted, 0);
  1071. if (rec_len < 0)
  1072. return 0;
  1073. /* grow record buffer if necessary */
  1074. if (!join_check_rec_size(self, rec_len))
  1075. return 0;
  1076. self->rec_len = join_append_data(self, field_kind, field_data, field_len,
  1077. &quoted, 1);
  1078. self->num_fields++;
  1079. return 1;
  1080. }
  1081. static int
  1082. join_append_lineterminator(WriterObj *self)
  1083. {
  1084. Py_ssize_t terminator_len, i;
  1085. int term_kind;
  1086. const void *term_data;
  1087. terminator_len = PyUnicode_GET_LENGTH(self->dialect->lineterminator);
  1088. if (terminator_len == -1)
  1089. return 0;
  1090. /* grow record buffer if necessary */
  1091. if (!join_check_rec_size(self, self->rec_len + terminator_len))
  1092. return 0;
  1093. term_kind = PyUnicode_KIND(self->dialect->lineterminator);
  1094. term_data = PyUnicode_DATA(self->dialect->lineterminator);
  1095. for (i = 0; i < terminator_len; i++)
  1096. self->rec[self->rec_len + i] = PyUnicode_READ(term_kind, term_data, i);
  1097. self->rec_len += terminator_len;
  1098. return 1;
  1099. }
  1100. PyDoc_STRVAR(csv_writerow_doc,
  1101. "writerow(iterable)\n"
  1102. "\n"
  1103. "Construct and write a CSV record from an iterable of fields. Non-string\n"
  1104. "elements will be converted to string.");
  1105. static PyObject *
  1106. csv_writerow(WriterObj *self, PyObject *seq)
  1107. {
  1108. DialectObj *dialect = self->dialect;
  1109. PyObject *iter, *field, *line, *result;
  1110. iter = PyObject_GetIter(seq);
  1111. if (iter == NULL) {
  1112. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  1113. PyErr_Format(self->error_obj,
  1114. "iterable expected, not %.200s",
  1115. Py_TYPE(seq)->tp_name);
  1116. }
  1117. return NULL;
  1118. }
  1119. /* Join all fields in internal buffer.
  1120. */
  1121. join_reset(self);
  1122. while ((field = PyIter_Next(iter))) {
  1123. int append_ok;
  1124. int quoted;
  1125. switch (dialect->quoting) {
  1126. case QUOTE_NONNUMERIC:
  1127. quoted = !PyNumber_Check(field);
  1128. break;
  1129. case QUOTE_ALL:
  1130. quoted = 1;
  1131. break;
  1132. case QUOTE_STRINGS:
  1133. quoted = PyUnicode_Check(field);
  1134. break;
  1135. case QUOTE_NOTNULL:
  1136. quoted = field != Py_None;
  1137. break;
  1138. default:
  1139. quoted = 0;
  1140. break;
  1141. }
  1142. if (PyUnicode_Check(field)) {
  1143. append_ok = join_append(self, field, quoted);
  1144. Py_DECREF(field);
  1145. }
  1146. else if (field == Py_None) {
  1147. append_ok = join_append(self, NULL, quoted);
  1148. Py_DECREF(field);
  1149. }
  1150. else {
  1151. PyObject *str;
  1152. str = PyObject_Str(field);
  1153. Py_DECREF(field);
  1154. if (str == NULL) {
  1155. Py_DECREF(iter);
  1156. return NULL;
  1157. }
  1158. append_ok = join_append(self, str, quoted);
  1159. Py_DECREF(str);
  1160. }
  1161. if (!append_ok) {
  1162. Py_DECREF(iter);
  1163. return NULL;
  1164. }
  1165. }
  1166. Py_DECREF(iter);
  1167. if (PyErr_Occurred())
  1168. return NULL;
  1169. if (self->num_fields > 0 && self->rec_len == 0) {
  1170. if (dialect->quoting == QUOTE_NONE) {
  1171. PyErr_Format(self->error_obj,
  1172. "single empty field record must be quoted");
  1173. return NULL;
  1174. }
  1175. self->num_fields--;
  1176. if (!join_append(self, NULL, 1))
  1177. return NULL;
  1178. }
  1179. /* Add line terminator.
  1180. */
  1181. if (!join_append_lineterminator(self)) {
  1182. return NULL;
  1183. }
  1184. line = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
  1185. (void *) self->rec, self->rec_len);
  1186. if (line == NULL) {
  1187. return NULL;
  1188. }
  1189. result = PyObject_CallOneArg(self->write, line);
  1190. Py_DECREF(line);
  1191. return result;
  1192. }
  1193. PyDoc_STRVAR(csv_writerows_doc,
  1194. "writerows(iterable of iterables)\n"
  1195. "\n"
  1196. "Construct and write a series of iterables to a csv file. Non-string\n"
  1197. "elements will be converted to string.");
  1198. static PyObject *
  1199. csv_writerows(WriterObj *self, PyObject *seqseq)
  1200. {
  1201. PyObject *row_iter, *row_obj, *result;
  1202. row_iter = PyObject_GetIter(seqseq);
  1203. if (row_iter == NULL) {
  1204. return NULL;
  1205. }
  1206. while ((row_obj = PyIter_Next(row_iter))) {
  1207. result = csv_writerow(self, row_obj);
  1208. Py_DECREF(row_obj);
  1209. if (!result) {
  1210. Py_DECREF(row_iter);
  1211. return NULL;
  1212. }
  1213. else
  1214. Py_DECREF(result);
  1215. }
  1216. Py_DECREF(row_iter);
  1217. if (PyErr_Occurred())
  1218. return NULL;
  1219. Py_RETURN_NONE;
  1220. }
  1221. static struct PyMethodDef Writer_methods[] = {
  1222. { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc},
  1223. { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc},
  1224. { NULL, NULL }
  1225. };
  1226. #define W_OFF(x) offsetof(WriterObj, x)
  1227. static struct PyMemberDef Writer_memberlist[] = {
  1228. { "dialect", T_OBJECT, W_OFF(dialect), READONLY },
  1229. { NULL }
  1230. };
  1231. static int
  1232. Writer_traverse(WriterObj *self, visitproc visit, void *arg)
  1233. {
  1234. Py_VISIT(self->dialect);
  1235. Py_VISIT(self->write);
  1236. Py_VISIT(self->error_obj);
  1237. Py_VISIT(Py_TYPE(self));
  1238. return 0;
  1239. }
  1240. static int
  1241. Writer_clear(WriterObj *self)
  1242. {
  1243. Py_CLEAR(self->dialect);
  1244. Py_CLEAR(self->write);
  1245. Py_CLEAR(self->error_obj);
  1246. return 0;
  1247. }
  1248. static void
  1249. Writer_dealloc(WriterObj *self)
  1250. {
  1251. PyTypeObject *tp = Py_TYPE(self);
  1252. PyObject_GC_UnTrack(self);
  1253. tp->tp_clear((PyObject *)self);
  1254. if (self->rec != NULL) {
  1255. PyMem_Free(self->rec);
  1256. }
  1257. PyObject_GC_Del(self);
  1258. Py_DECREF(tp);
  1259. }
  1260. PyDoc_STRVAR(Writer_Type_doc,
  1261. "CSV writer\n"
  1262. "\n"
  1263. "Writer objects are responsible for generating tabular data\n"
  1264. "in CSV format from sequence input.\n"
  1265. );
  1266. static PyType_Slot Writer_Type_slots[] = {
  1267. {Py_tp_doc, (char*)Writer_Type_doc},
  1268. {Py_tp_traverse, Writer_traverse},
  1269. {Py_tp_clear, Writer_clear},
  1270. {Py_tp_dealloc, Writer_dealloc},
  1271. {Py_tp_methods, Writer_methods},
  1272. {Py_tp_members, Writer_memberlist},
  1273. {0, NULL}
  1274. };
  1275. PyType_Spec Writer_Type_spec = {
  1276. .name = "_csv.writer",
  1277. .basicsize = sizeof(WriterObj),
  1278. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  1279. Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  1280. .slots = Writer_Type_slots,
  1281. };
  1282. static PyObject *
  1283. csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args)
  1284. {
  1285. PyObject * output_file, * dialect = NULL;
  1286. _csvstate *module_state = get_csv_state(module);
  1287. WriterObj * self = PyObject_GC_New(WriterObj, module_state->writer_type);
  1288. if (!self)
  1289. return NULL;
  1290. self->dialect = NULL;
  1291. self->write = NULL;
  1292. self->rec = NULL;
  1293. self->rec_size = 0;
  1294. self->rec_len = 0;
  1295. self->num_fields = 0;
  1296. self->error_obj = Py_NewRef(module_state->error_obj);
  1297. if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) {
  1298. Py_DECREF(self);
  1299. return NULL;
  1300. }
  1301. if (_PyObject_LookupAttr(output_file,
  1302. module_state->str_write,
  1303. &self->write) < 0) {
  1304. Py_DECREF(self);
  1305. return NULL;
  1306. }
  1307. if (self->write == NULL || !PyCallable_Check(self->write)) {
  1308. PyErr_SetString(PyExc_TypeError,
  1309. "argument 1 must have a \"write\" method");
  1310. Py_DECREF(self);
  1311. return NULL;
  1312. }
  1313. self->dialect = (DialectObj *)_call_dialect(module_state, dialect,
  1314. keyword_args);
  1315. if (self->dialect == NULL) {
  1316. Py_DECREF(self);
  1317. return NULL;
  1318. }
  1319. PyObject_GC_Track(self);
  1320. return (PyObject *)self;
  1321. }
  1322. /*
  1323. * DIALECT REGISTRY
  1324. */
  1325. /*[clinic input]
  1326. _csv.list_dialects
  1327. Return a list of all known dialect names.
  1328. names = csv.list_dialects()
  1329. [clinic start generated code]*/
  1330. static PyObject *
  1331. _csv_list_dialects_impl(PyObject *module)
  1332. /*[clinic end generated code: output=a5b92b215b006a6d input=8953943eb17d98ab]*/
  1333. {
  1334. return PyDict_Keys(get_csv_state(module)->dialects);
  1335. }
  1336. static PyObject *
  1337. csv_register_dialect(PyObject *module, PyObject *args, PyObject *kwargs)
  1338. {
  1339. PyObject *name_obj, *dialect_obj = NULL;
  1340. _csvstate *module_state = get_csv_state(module);
  1341. PyObject *dialect;
  1342. if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj))
  1343. return NULL;
  1344. if (!PyUnicode_Check(name_obj)) {
  1345. PyErr_SetString(PyExc_TypeError,
  1346. "dialect name must be a string");
  1347. return NULL;
  1348. }
  1349. if (PyUnicode_READY(name_obj) == -1)
  1350. return NULL;
  1351. dialect = _call_dialect(module_state, dialect_obj, kwargs);
  1352. if (dialect == NULL)
  1353. return NULL;
  1354. if (PyDict_SetItem(module_state->dialects, name_obj, dialect) < 0) {
  1355. Py_DECREF(dialect);
  1356. return NULL;
  1357. }
  1358. Py_DECREF(dialect);
  1359. Py_RETURN_NONE;
  1360. }
  1361. /*[clinic input]
  1362. _csv.unregister_dialect
  1363. name: object
  1364. Delete the name/dialect mapping associated with a string name.
  1365. csv.unregister_dialect(name)
  1366. [clinic start generated code]*/
  1367. static PyObject *
  1368. _csv_unregister_dialect_impl(PyObject *module, PyObject *name)
  1369. /*[clinic end generated code: output=0813ebca6c058df4 input=6b5c1557bf60c7e7]*/
  1370. {
  1371. _csvstate *module_state = get_csv_state(module);
  1372. if (PyDict_DelItem(module_state->dialects, name) < 0) {
  1373. if (PyErr_ExceptionMatches(PyExc_KeyError)) {
  1374. PyErr_Format(module_state->error_obj, "unknown dialect");
  1375. }
  1376. return NULL;
  1377. }
  1378. Py_RETURN_NONE;
  1379. }
  1380. /*[clinic input]
  1381. _csv.get_dialect
  1382. name: object
  1383. Return the dialect instance associated with name.
  1384. dialect = csv.get_dialect(name)
  1385. [clinic start generated code]*/
  1386. static PyObject *
  1387. _csv_get_dialect_impl(PyObject *module, PyObject *name)
  1388. /*[clinic end generated code: output=aa988cd573bebebb input=edf9ddab32e448fb]*/
  1389. {
  1390. return get_dialect_from_registry(name, get_csv_state(module));
  1391. }
  1392. /*[clinic input]
  1393. _csv.field_size_limit
  1394. new_limit: object = NULL
  1395. Sets an upper limit on parsed fields.
  1396. csv.field_size_limit([limit])
  1397. Returns old limit. If limit is not given, no new limit is set and
  1398. the old limit is returned
  1399. [clinic start generated code]*/
  1400. static PyObject *
  1401. _csv_field_size_limit_impl(PyObject *module, PyObject *new_limit)
  1402. /*[clinic end generated code: output=f2799ecd908e250b input=cec70e9226406435]*/
  1403. {
  1404. _csvstate *module_state = get_csv_state(module);
  1405. long old_limit = module_state->field_limit;
  1406. if (new_limit != NULL) {
  1407. if (!PyLong_CheckExact(new_limit)) {
  1408. PyErr_Format(PyExc_TypeError,
  1409. "limit must be an integer");
  1410. return NULL;
  1411. }
  1412. module_state->field_limit = PyLong_AsLong(new_limit);
  1413. if (module_state->field_limit == -1 && PyErr_Occurred()) {
  1414. module_state->field_limit = old_limit;
  1415. return NULL;
  1416. }
  1417. }
  1418. return PyLong_FromLong(old_limit);
  1419. }
  1420. static PyType_Slot error_slots[] = {
  1421. {0, NULL},
  1422. };
  1423. PyType_Spec error_spec = {
  1424. .name = "_csv.Error",
  1425. .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
  1426. .slots = error_slots,
  1427. };
  1428. /*
  1429. * MODULE
  1430. */
  1431. PyDoc_STRVAR(csv_module_doc,
  1432. "CSV parsing and writing.\n"
  1433. "\n"
  1434. "This module provides classes that assist in the reading and writing\n"
  1435. "of Comma Separated Value (CSV) files, and implements the interface\n"
  1436. "described by PEP 305. Although many CSV files are simple to parse,\n"
  1437. "the format is not formally defined by a stable specification and\n"
  1438. "is subtle enough that parsing lines of a CSV file with something\n"
  1439. "like line.split(\",\") is bound to fail. The module supports three\n"
  1440. "basic APIs: reading, writing, and registration of dialects.\n"
  1441. "\n"
  1442. "\n"
  1443. "DIALECT REGISTRATION:\n"
  1444. "\n"
  1445. "Readers and writers support a dialect argument, which is a convenient\n"
  1446. "handle on a group of settings. When the dialect argument is a string,\n"
  1447. "it identifies one of the dialects previously registered with the module.\n"
  1448. "If it is a class or instance, the attributes of the argument are used as\n"
  1449. "the settings for the reader or writer:\n"
  1450. "\n"
  1451. " class excel:\n"
  1452. " delimiter = ','\n"
  1453. " quotechar = '\"'\n"
  1454. " escapechar = None\n"
  1455. " doublequote = True\n"
  1456. " skipinitialspace = False\n"
  1457. " lineterminator = '\\r\\n'\n"
  1458. " quoting = QUOTE_MINIMAL\n"
  1459. "\n"
  1460. "SETTINGS:\n"
  1461. "\n"
  1462. " * quotechar - specifies a one-character string to use as the\n"
  1463. " quoting character. It defaults to '\"'.\n"
  1464. " * delimiter - specifies a one-character string to use as the\n"
  1465. " field separator. It defaults to ','.\n"
  1466. " * skipinitialspace - specifies how to interpret spaces which\n"
  1467. " immediately follow a delimiter. It defaults to False, which\n"
  1468. " means that spaces immediately following a delimiter is part\n"
  1469. " of the following field.\n"
  1470. " * lineterminator - specifies the character sequence which should\n"
  1471. " terminate rows.\n"
  1472. " * quoting - controls when quotes should be generated by the writer.\n"
  1473. " It can take on any of the following module constants:\n"
  1474. "\n"
  1475. " csv.QUOTE_MINIMAL means only when required, for example, when a\n"
  1476. " field contains either the quotechar or the delimiter\n"
  1477. " csv.QUOTE_ALL means that quotes are always placed around fields.\n"
  1478. " csv.QUOTE_NONNUMERIC means that quotes are always placed around\n"
  1479. " fields which do not parse as integers or floating point\n"
  1480. " numbers.\n"
  1481. " csv.QUOTE_STRINGS means that quotes are always placed around\n"
  1482. " fields which are strings. Note that the Python value None\n"
  1483. " is not a string.\n"
  1484. " csv.QUOTE_NOTNULL means that quotes are only placed around fields\n"
  1485. " that are not the Python value None.\n"
  1486. " csv.QUOTE_NONE means that quotes are never placed around fields.\n"
  1487. " * escapechar - specifies a one-character string used to escape\n"
  1488. " the delimiter when quoting is set to QUOTE_NONE.\n"
  1489. " * doublequote - controls the handling of quotes inside fields. When\n"
  1490. " True, two consecutive quotes are interpreted as one during read,\n"
  1491. " and when writing, each quote character embedded in the data is\n"
  1492. " written as two quotes\n");
  1493. PyDoc_STRVAR(csv_reader_doc,
  1494. " csv_reader = reader(iterable [, dialect='excel']\n"
  1495. " [optional keyword args])\n"
  1496. " for row in csv_reader:\n"
  1497. " process(row)\n"
  1498. "\n"
  1499. "The \"iterable\" argument can be any object that returns a line\n"
  1500. "of input for each iteration, such as a file object or a list. The\n"
  1501. "optional \"dialect\" parameter is discussed below. The function\n"
  1502. "also accepts optional keyword arguments which override settings\n"
  1503. "provided by the dialect.\n"
  1504. "\n"
  1505. "The returned object is an iterator. Each iteration returns a row\n"
  1506. "of the CSV file (which can span multiple input lines).\n");
  1507. PyDoc_STRVAR(csv_writer_doc,
  1508. " csv_writer = csv.writer(fileobj [, dialect='excel']\n"
  1509. " [optional keyword args])\n"
  1510. " for row in sequence:\n"
  1511. " csv_writer.writerow(row)\n"
  1512. "\n"
  1513. " [or]\n"
  1514. "\n"
  1515. " csv_writer = csv.writer(fileobj [, dialect='excel']\n"
  1516. " [optional keyword args])\n"
  1517. " csv_writer.writerows(rows)\n"
  1518. "\n"
  1519. "The \"fileobj\" argument can be any object that supports the file API.\n");
  1520. PyDoc_STRVAR(csv_register_dialect_doc,
  1521. "Create a mapping from a string name to a dialect class.\n"
  1522. " dialect = csv.register_dialect(name[, dialect[, **fmtparams]])");
  1523. static struct PyMethodDef csv_methods[] = {
  1524. { "reader", _PyCFunction_CAST(csv_reader),
  1525. METH_VARARGS | METH_KEYWORDS, csv_reader_doc},
  1526. { "writer", _PyCFunction_CAST(csv_writer),
  1527. METH_VARARGS | METH_KEYWORDS, csv_writer_doc},
  1528. { "register_dialect", _PyCFunction_CAST(csv_register_dialect),
  1529. METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc},
  1530. _CSV_LIST_DIALECTS_METHODDEF
  1531. _CSV_UNREGISTER_DIALECT_METHODDEF
  1532. _CSV_GET_DIALECT_METHODDEF
  1533. _CSV_FIELD_SIZE_LIMIT_METHODDEF
  1534. { NULL, NULL }
  1535. };
  1536. static int
  1537. csv_exec(PyObject *module) {
  1538. const StyleDesc *style;
  1539. PyObject *temp;
  1540. _csvstate *module_state = get_csv_state(module);
  1541. temp = PyType_FromModuleAndSpec(module, &Dialect_Type_spec, NULL);
  1542. module_state->dialect_type = (PyTypeObject *)temp;
  1543. if (PyModule_AddObjectRef(module, "Dialect", temp) < 0) {
  1544. return -1;
  1545. }
  1546. temp = PyType_FromModuleAndSpec(module, &Reader_Type_spec, NULL);
  1547. module_state->reader_type = (PyTypeObject *)temp;
  1548. if (PyModule_AddObjectRef(module, "Reader", temp) < 0) {
  1549. return -1;
  1550. }
  1551. temp = PyType_FromModuleAndSpec(module, &Writer_Type_spec, NULL);
  1552. module_state->writer_type = (PyTypeObject *)temp;
  1553. if (PyModule_AddObjectRef(module, "Writer", temp) < 0) {
  1554. return -1;
  1555. }
  1556. /* Add version to the module. */
  1557. if (PyModule_AddStringConstant(module, "__version__",
  1558. MODULE_VERSION) == -1) {
  1559. return -1;
  1560. }
  1561. /* Set the field limit */
  1562. module_state->field_limit = 128 * 1024;
  1563. /* Add _dialects dictionary */
  1564. module_state->dialects = PyDict_New();
  1565. if (PyModule_AddObjectRef(module, "_dialects", module_state->dialects) < 0) {
  1566. return -1;
  1567. }
  1568. /* Add quote styles into dictionary */
  1569. for (style = quote_styles; style->name; style++) {
  1570. if (PyModule_AddIntConstant(module, style->name,
  1571. style->style) == -1)
  1572. return -1;
  1573. }
  1574. /* Add the CSV exception object to the module. */
  1575. PyObject *bases = PyTuple_Pack(1, PyExc_Exception);
  1576. if (bases == NULL) {
  1577. return -1;
  1578. }
  1579. module_state->error_obj = PyType_FromModuleAndSpec(module, &error_spec,
  1580. bases);
  1581. Py_DECREF(bases);
  1582. if (module_state->error_obj == NULL) {
  1583. return -1;
  1584. }
  1585. if (PyModule_AddType(module, (PyTypeObject *)module_state->error_obj) != 0) {
  1586. return -1;
  1587. }
  1588. module_state->str_write = PyUnicode_InternFromString("write");
  1589. if (module_state->str_write == NULL) {
  1590. return -1;
  1591. }
  1592. return 0;
  1593. }
  1594. static PyModuleDef_Slot csv_slots[] = {
  1595. {Py_mod_exec, csv_exec},
  1596. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1597. {0, NULL}
  1598. };
  1599. static struct PyModuleDef _csvmodule = {
  1600. PyModuleDef_HEAD_INIT,
  1601. "_csv",
  1602. csv_module_doc,
  1603. sizeof(_csvstate),
  1604. csv_methods,
  1605. csv_slots,
  1606. _csv_traverse,
  1607. _csv_clear,
  1608. _csv_free
  1609. };
  1610. PyMODINIT_FUNC
  1611. PyInit__csv(void)
  1612. {
  1613. return PyModuleDef_Init(&_csvmodule);
  1614. }