_elementtree.c 108 KB
Newer Older
1 2 3
/*--------------------------------------------------------------------
 * Licensed to PSF under a Contributor Agreement.
 * See http://www.python.org/psf/license for licensing details.
4
 *
5
 * _elementtree - C accelerator for xml.etree.ElementTree
6 7
 * Copyright (c) 1999-2009 by Secret Labs AB.  All rights reserved.
 * Copyright (c) 1999-2009 by Fredrik Lundh.
8 9 10
 *
 * info@pythonware.com
 * http://www.pythonware.com
11
 *--------------------------------------------------------------------
12 13 14
 */

#include "Python.h"
15
#include "structmember.h"
16 17 18 19 20 21 22 23 24 25 26 27 28 29

/* -------------------------------------------------------------------- */
/* configuration */

/* An element can hold this many children without extra memory
   allocations. */
#define STATIC_CHILDREN 4

/* For best performance, chose a value so that 80-90% of all nodes
   have no more than the given number of children.  Set this to zero
   to minimize the size of the element structure itself (this only
   helps if you have lots of leaf nodes with attributes). */

/* Also note that pymalloc always allocates blocks in multiples of
30
   eight bytes.  For the current C version of ElementTree, this means
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
   that the number of children should be an even number, at least on
   32-bit platforms. */

/* -------------------------------------------------------------------- */

#if 0
static int memory = 0;
#define ALLOC(size, comment)\
do { memory += size; printf("%8d - %s\n", memory, comment); } while (0)
#define RELEASE(size, comment)\
do { memory -= size; printf("%8d - %s\n", memory, comment); } while (0)
#else
#define ALLOC(size, comment)
#define RELEASE(size, comment)
#endif

/* compiler tweaks */
#if defined(_MSC_VER)
#define LOCAL(type) static __inline type __fastcall
#else
#define LOCAL(type) static type
#endif

/* macros used to store 'join' flags in string object pointers.  note
   that all use of text and tail as object pointers must be wrapped in
   JOIN_OBJ.  see comments in the ElementObject definition for more
   info. */
#define JOIN_GET(p) ((Py_uintptr_t) (p) & 1)
#define JOIN_SET(p, flag) ((void*) ((Py_uintptr_t) (JOIN_OBJ(p)) | (flag)))
60
#define JOIN_OBJ(p) ((PyObject*) ((Py_uintptr_t) (p) & ~(Py_uintptr_t)1))
61

62 63 64
/* Py_CLEAR for a PyObject* that uses a join flag. Pass the pointer by
 * reference since this function sets it to NULL.
*/
65
static void _clear_joined_ptr(PyObject **p)
66 67 68 69 70 71 72 73
{
    if (*p) {
        PyObject *tmp = JOIN_OBJ(*p);
        *p = NULL;
        Py_DECREF(tmp);
    }
}

74 75 76 77 78 79 80
/* Types defined by this extension */
static PyTypeObject Element_Type;
static PyTypeObject ElementIter_Type;
static PyTypeObject TreeBuilder_Type;
static PyTypeObject XMLParser_Type;


81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
/* Per-module state; PEP 3121 */
typedef struct {
    PyObject *parseerror_obj;
    PyObject *deepcopy_obj;
    PyObject *elementpath_obj;
} elementtreestate;

static struct PyModuleDef elementtreemodule;

/* Given a module object (assumed to be _elementtree), get its per-module
 * state.
 */
#define ET_STATE(mod) ((elementtreestate *) PyModule_GetState(mod))

/* Find the module instance imported in the currently running sub-interpreter
 * and get its state.
 */
#define ET_STATE_GLOBAL \
    ((elementtreestate *) PyModule_GetState(PyState_FindModule(&elementtreemodule)))

static int
elementtree_clear(PyObject *m)
{
    elementtreestate *st = ET_STATE(m);
    Py_CLEAR(st->parseerror_obj);
    Py_CLEAR(st->deepcopy_obj);
    Py_CLEAR(st->elementpath_obj);
    return 0;
}

static int
elementtree_traverse(PyObject *m, visitproc visit, void *arg)
{
    elementtreestate *st = ET_STATE(m);
    Py_VISIT(st->parseerror_obj);
    Py_VISIT(st->deepcopy_obj);
    Py_VISIT(st->elementpath_obj);
    return 0;
}

static void
elementtree_free(void *m)
{
    elementtree_clear((PyObject *)m);
}
126 127 128 129 130 131 132 133 134

/* helpers */

LOCAL(PyObject*)
deepcopy(PyObject* object, PyObject* memo)
{
    /* do a deep copy of the given object */
    PyObject* args;
    PyObject* result;
135
    elementtreestate *st = ET_STATE_GLOBAL;
136

137
    if (!st->deepcopy_obj) {
138 139 140 141 142 143 144
        PyErr_SetString(
            PyExc_RuntimeError,
            "deepcopy helper not found"
            );
        return NULL;
    }

145
    args = PyTuple_Pack(2, object, memo);
146 147
    if (!args)
        return NULL;
148
    result = PyObject_CallObject(st->deepcopy_obj, args);
149 150 151 152 153 154 155 156 157 158 159
    Py_DECREF(args);
    return result;
}

LOCAL(PyObject*)
list_join(PyObject* list)
{
    /* join list elements (destroying the list in the process) */
    PyObject* joiner;
    PyObject* result;

160
    joiner = PyUnicode_FromStringAndSize("", 0);
161 162
    if (!joiner)
        return NULL;
163
    result = PyUnicode_Join(joiner, list);
164
    Py_DECREF(joiner);
165 166
    if (result)
        Py_DECREF(list);
167 168 169
    return result;
}

170 171 172 173 174 175 176 177 178
/* Is the given object an empty dictionary?
*/
static int
is_empty_dict(PyObject *obj)
{
    return PyDict_CheckExact(obj) && PyDict_Size(obj) == 0;
}


179
/* -------------------------------------------------------------------- */
180
/* the Element type */
181 182 183 184 185 186 187 188 189 190 191 192 193 194

typedef struct {

    /* attributes (a dictionary object), or None if no attributes */
    PyObject* attrib;

    /* child elements */
    int length; /* actual number of items */
    int allocated; /* allocated items */

    /* this either points to _children or to a malloced buffer */
    PyObject* *children;

    PyObject* _children[STATIC_CHILDREN];
195

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
} ElementObjectExtra;

typedef struct {
    PyObject_HEAD

    /* element tag (a string). */
    PyObject* tag;

    /* text before first child.  note that this is a tagged pointer;
       use JOIN_OBJ to get the object pointer.  the join flag is used
       to distinguish lists created by the tree builder from lists
       assigned to the attribute by application code; the former
       should be joined before being returned to the user, the latter
       should be left intact. */
    PyObject* text;

    /* text after this element, in parent.  note that this is a tagged
       pointer; use JOIN_OBJ to get the object pointer. */
    PyObject* tail;

    ElementObjectExtra* extra;

218 219
    PyObject *weakreflist; /* For tp_weaklistoffset */

220 221 222
} ElementObject;


223
#define Element_CheckExact(op) (Py_TYPE(op) == &Element_Type)
224 225

/* -------------------------------------------------------------------- */
226
/* Element constructors and destructor */
227 228

LOCAL(int)
229
create_extra(ElementObject* self, PyObject* attrib)
230 231
{
    self->extra = PyObject_Malloc(sizeof(ElementObjectExtra));
232 233
    if (!self->extra) {
        PyErr_NoMemory();
234
        return -1;
235
    }
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

    if (!attrib)
        attrib = Py_None;

    Py_INCREF(attrib);
    self->extra->attrib = attrib;

    self->extra->length = 0;
    self->extra->allocated = STATIC_CHILDREN;
    self->extra->children = self->extra->_children;

    return 0;
}

LOCAL(void)
251
dealloc_extra(ElementObject* self)
252
{
253 254 255
    ElementObjectExtra *myextra;
    int i;

256 257 258 259 260
    if (!self->extra)
        return;

    /* Avoid DECREFs calling into this code again (cycles, etc.)
    */
261
    myextra = self->extra;
262
    self->extra = NULL;
263

264
    Py_DECREF(myextra->attrib);
265

266 267
    for (i = 0; i < myextra->length; i++)
        Py_DECREF(myextra->children[i]);
268

269 270
    if (myextra->children != myextra->_children)
        PyObject_Free(myextra->children);
271

272
    PyObject_Free(myextra);
273 274
}

275 276 277
/* Convenience internal function to create new Element objects with the given
 * tag and attributes.
*/
278
LOCAL(PyObject*)
279
create_new_element(PyObject* tag, PyObject* attrib)
280 281 282
{
    ElementObject* self;

283
    self = PyObject_GC_New(ElementObject, &Element_Type);
284 285 286 287 288 289 290 291 292 293 294 295 296
    if (self == NULL)
        return NULL;
    self->extra = NULL;

    Py_INCREF(tag);
    self->tag = tag;

    Py_INCREF(Py_None);
    self->text = Py_None;

    Py_INCREF(Py_None);
    self->tail = Py_None;

297 298
    self->weakreflist = NULL;

299 300 301
    ALLOC(sizeof(ElementObject), "create element");
    PyObject_GC_Track(self);

302 303
    if (attrib != Py_None && !is_empty_dict(attrib)) {
        if (create_extra(self, attrib) < 0) {
304
            Py_DECREF(self);
305 306 307 308
            return NULL;
        }
    }

309 310 311
    return (PyObject*) self;
}

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
static PyObject *
element_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    ElementObject *e = (ElementObject *)type->tp_alloc(type, 0);
    if (e != NULL) {
        Py_INCREF(Py_None);
        e->tag = Py_None;

        Py_INCREF(Py_None);
        e->text = Py_None;

        Py_INCREF(Py_None);
        e->tail = Py_None;

        e->extra = NULL;
327
        e->weakreflist = NULL;
328 329 330 331
    }
    return (PyObject *)e;
}

332 333
/* Helper function for extracting the attrib dictionary from a keywords dict.
 * This is required by some constructors/functions in this module that can
334
 * either accept attrib as a keyword argument or all attributes splashed
335
 * directly into *kwds.
336 337 338
 *
 * Return a dictionary with the content of kwds merged into the content of
 * attrib. If there is no attrib keyword, return a copy of kwds.
339 340 341 342
 */
static PyObject*
get_attrib_from_keywords(PyObject *kwds)
{
343 344
    PyObject *attrib_str = PyUnicode_FromString("attrib");
    PyObject *attrib = PyDict_GetItem(kwds, attrib_str);
345 346 347 348 349 350

    if (attrib) {
        /* If attrib was found in kwds, copy its value and remove it from
         * kwds
         */
        if (!PyDict_Check(attrib)) {
351
            Py_DECREF(attrib_str);
352 353 354 355 356
            PyErr_Format(PyExc_TypeError, "attrib must be dict, not %.100s",
                         Py_TYPE(attrib)->tp_name);
            return NULL;
        }
        attrib = PyDict_Copy(attrib);
357
        PyDict_DelItem(kwds, attrib_str);
358 359 360
    } else {
        attrib = PyDict_New();
    }
361 362 363 364 365

    Py_DECREF(attrib_str);

    /* attrib can be NULL if PyDict_New failed */
    if (attrib)
366 367
        if (PyDict_Update(attrib, kwds) < 0)
            return NULL;
368 369 370
    return attrib;
}

371 372 373 374 375 376 377 378 379 380 381
static int
element_init(PyObject *self, PyObject *args, PyObject *kwds)
{
    PyObject *tag;
    PyObject *tmp;
    PyObject *attrib = NULL;
    ElementObject *self_elem;

    if (!PyArg_ParseTuple(args, "O|O!:Element", &tag, &PyDict_Type, &attrib))
        return -1;

382 383 384 385 386 387 388
    if (attrib) {
        /* attrib passed as positional arg */
        attrib = PyDict_Copy(attrib);
        if (!attrib)
            return -1;
        if (kwds) {
            if (PyDict_Update(attrib, kwds) < 0) {
389
                Py_DECREF(attrib);
390 391 392 393 394 395
                return -1;
            }
        }
    } else if (kwds) {
        /* have keywords args */
        attrib = get_attrib_from_keywords(kwds);
396 397 398 399 400 401
        if (!attrib)
            return -1;
    }

    self_elem = (ElementObject *)self;

402
    if (attrib != NULL && !is_empty_dict(attrib)) {
403
        if (create_extra(self_elem, attrib) < 0) {
404
            Py_DECREF(attrib);
405 406 407 408
            return -1;
        }
    }

409
    /* We own a reference to attrib here and it's no longer needed. */
410
    Py_XDECREF(attrib);
411 412 413 414

    /* Replace the objects already pointed to by tag, text and tail. */
    tmp = self_elem->tag;
    Py_INCREF(tag);
415
    self_elem->tag = tag;
416 417 418 419
    Py_DECREF(tmp);

    tmp = self_elem->text;
    Py_INCREF(Py_None);
420
    self_elem->text = Py_None;
421 422 423 424
    Py_DECREF(JOIN_OBJ(tmp));

    tmp = self_elem->tail;
    Py_INCREF(Py_None);
425
    self_elem->tail = Py_None;
426 427 428 429 430
    Py_DECREF(JOIN_OBJ(tmp));

    return 0;
}

431
LOCAL(int)
432
element_resize(ElementObject* self, Py_ssize_t extra)
433
{
434
    Py_ssize_t size;
435 436 437 438 439
    PyObject* *children;

    /* make sure self->children can hold the given number of extra
       elements.  set an exception and return -1 if allocation failed */

440 441 442 443
    if (!self->extra) {
        if (create_extra(self, NULL) < 0)
            return -1;
    }
444 445 446 447 448 449

    size = self->extra->length + extra;

    if (size > self->extra->allocated) {
        /* use Python 2.4's list growth strategy */
        size = (size >> 3) + (size < 9 ? 3 : 6) + size;
450
        /* Coverity CID #182 size_error: Allocating 1 bytes to pointer "children"
451 452
         * which needs at least 4 bytes.
         * Although it's a false alarm always assume at least one child to
453 454 455
         * be safe.
         */
        size = size ? size : 1;
456 457 458 459 460 461 462
        if ((size_t)size > PY_SSIZE_T_MAX/sizeof(PyObject*))
            goto nomemory;
        if (size > INT_MAX) {
            PyErr_SetString(PyExc_OverflowError,
                            "too many children");
            return -1;
        }
463
        if (self->extra->children != self->extra->_children) {
464
            /* Coverity CID #182 size_error: Allocating 1 bytes to pointer
465
             * "children", which needs at least 4 bytes. Although it's a
466 467
             * false alarm always assume at least one child to be safe.
             */
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
            children = PyObject_Realloc(self->extra->children,
                                        size * sizeof(PyObject*));
            if (!children)
                goto nomemory;
        } else {
            children = PyObject_Malloc(size * sizeof(PyObject*));
            if (!children)
                goto nomemory;
            /* copy existing children from static area to malloc buffer */
            memcpy(children, self->extra->children,
                   self->extra->length * sizeof(PyObject*));
        }
        self->extra->children = children;
        self->extra->allocated = size;
    }

    return 0;

  nomemory:
    PyErr_NoMemory();
    return -1;
}

LOCAL(int)
element_add_subelement(ElementObject* self, PyObject* element)
{
    /* add a child element to a parent */

    if (element_resize(self, 1) < 0)
        return -1;

    Py_INCREF(element);
    self->extra->children[self->extra->length] = element;

    self->extra->length++;

    return 0;
}

LOCAL(PyObject*)
element_get_attrib(ElementObject* self)
{
    /* return borrowed reference to attrib dictionary */
    /* note: this function assumes that the extra section exists */

    PyObject* res = self->extra->attrib;

    if (res == Py_None) {
        /* create missing dictionary */
        res = PyDict_New();
        if (!res)
            return NULL;
520
        Py_DECREF(Py_None);
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
        self->extra->attrib = res;
    }

    return res;
}

LOCAL(PyObject*)
element_get_text(ElementObject* self)
{
    /* return borrowed reference to text attribute */

    PyObject* res = self->text;

    if (JOIN_GET(res)) {
        res = JOIN_OBJ(res);
        if (PyList_CheckExact(res)) {
            res = list_join(res);
            if (!res)
                return NULL;
            self->text = res;
        }
    }

    return res;
}

LOCAL(PyObject*)
element_get_tail(ElementObject* self)
{
    /* return borrowed reference to text attribute */

    PyObject* res = self->tail;

    if (JOIN_GET(res)) {
        res = JOIN_OBJ(res);
        if (PyList_CheckExact(res)) {
            res = list_join(res);
            if (!res)
                return NULL;
            self->tail = res;
        }
    }

    return res;
}

static PyObject*
568
subelement(PyObject *self, PyObject *args, PyObject *kwds)
569 570 571 572 573 574 575 576
{
    PyObject* elem;

    ElementObject* parent;
    PyObject* tag;
    PyObject* attrib = NULL;
    if (!PyArg_ParseTuple(args, "O!O|O!:SubElement",
                          &Element_Type, &parent, &tag,
Eli Bendersky's avatar
Eli Bendersky committed
577
                          &PyDict_Type, &attrib)) {
578
        return NULL;
Eli Bendersky's avatar
Eli Bendersky committed
579
    }
580

581 582 583 584 585 586 587 588 589 590 591 592 593
    if (attrib) {
        /* attrib passed as positional arg */
        attrib = PyDict_Copy(attrib);
        if (!attrib)
            return NULL;
        if (kwds) {
            if (PyDict_Update(attrib, kwds) < 0) {
                return NULL;
            }
        }
    } else if (kwds) {
        /* have keyword args */
        attrib = get_attrib_from_keywords(kwds);
594 595 596
        if (!attrib)
            return NULL;
    } else {
597
        /* no attrib arg, no kwds, so no attribute */
598 599 600 601
        Py_INCREF(Py_None);
        attrib = Py_None;
    }

602
    elem = create_new_element(tag, attrib);
603
    Py_DECREF(attrib);
604 605
    if (elem == NULL)
        return NULL;
606

607 608
    if (element_add_subelement(parent, elem) < 0) {
        Py_DECREF(elem);
609
        return NULL;
610
    }
611 612 613 614

    return elem;
}

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
static int
element_gc_traverse(ElementObject *self, visitproc visit, void *arg)
{
    Py_VISIT(self->tag);
    Py_VISIT(JOIN_OBJ(self->text));
    Py_VISIT(JOIN_OBJ(self->tail));

    if (self->extra) {
        int i;
        Py_VISIT(self->extra->attrib);

        for (i = 0; i < self->extra->length; ++i)
            Py_VISIT(self->extra->children[i]);
    }
    return 0;
}

static int
element_gc_clear(ElementObject *self)
634
{
635
    Py_CLEAR(self->tag);
636 637
    _clear_joined_ptr(&self->text);
    _clear_joined_ptr(&self->tail);
638 639 640 641 642

    /* After dropping all references from extra, it's no longer valid anyway,
     * so fully deallocate it.
    */
    dealloc_extra(self);
643 644
    return 0;
}
645

646 647 648 649
static void
element_dealloc(ElementObject* self)
{
    PyObject_GC_UnTrack(self);
650 651 652 653

    if (self->weakreflist != NULL)
        PyObject_ClearWeakRefs((PyObject *) self);

654 655 656
    /* element_gc_clear clears all references and deallocates extra
    */
    element_gc_clear(self);
657 658

    RELEASE(sizeof(ElementObject), "destroy element");
659
    Py_TYPE(self)->tp_free((PyObject *)self);
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
}

/* -------------------------------------------------------------------- */

static PyObject*
element_append(ElementObject* self, PyObject* args)
{
    PyObject* element;
    if (!PyArg_ParseTuple(args, "O!:append", &Element_Type, &element))
        return NULL;

    if (element_add_subelement(self, element) < 0)
        return NULL;

    Py_RETURN_NONE;
}

static PyObject*
678
element_clearmethod(ElementObject* self, PyObject* args)
679 680 681 682
{
    if (!PyArg_ParseTuple(args, ":clear"))
        return NULL;

683
    dealloc_extra(self);
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704

    Py_INCREF(Py_None);
    Py_DECREF(JOIN_OBJ(self->text));
    self->text = Py_None;

    Py_INCREF(Py_None);
    Py_DECREF(JOIN_OBJ(self->tail));
    self->tail = Py_None;

    Py_RETURN_NONE;
}

static PyObject*
element_copy(ElementObject* self, PyObject* args)
{
    int i;
    ElementObject* element;

    if (!PyArg_ParseTuple(args, ":__copy__"))
        return NULL;

705
    element = (ElementObject*) create_new_element(
Eli Bendersky's avatar
Eli Bendersky committed
706
        self->tag, (self->extra) ? self->extra->attrib : Py_None);
707 708 709 710 711 712 713 714 715 716 717 718
    if (!element)
        return NULL;

    Py_DECREF(JOIN_OBJ(element->text));
    element->text = self->text;
    Py_INCREF(JOIN_OBJ(element->text));

    Py_DECREF(JOIN_OBJ(element->tail));
    element->tail = self->tail;
    Py_INCREF(JOIN_OBJ(element->tail));

    if (self->extra) {
719 720
        if (element_resize(element, self->extra->length) < 0) {
            Py_DECREF(element);
721
            return NULL;
722
        }
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764

        for (i = 0; i < self->extra->length; i++) {
            Py_INCREF(self->extra->children[i]);
            element->extra->children[i] = self->extra->children[i];
        }

        element->extra->length = self->extra->length;
    }

    return (PyObject*) element;
}

static PyObject*
element_deepcopy(ElementObject* self, PyObject* args)
{
    int i;
    ElementObject* element;
    PyObject* tag;
    PyObject* attrib;
    PyObject* text;
    PyObject* tail;
    PyObject* id;

    PyObject* memo;
    if (!PyArg_ParseTuple(args, "O:__deepcopy__", &memo))
        return NULL;

    tag = deepcopy(self->tag, memo);
    if (!tag)
        return NULL;

    if (self->extra) {
        attrib = deepcopy(self->extra->attrib, memo);
        if (!attrib) {
            Py_DECREF(tag);
            return NULL;
        }
    } else {
        Py_INCREF(Py_None);
        attrib = Py_None;
    }

765
    element = (ElementObject*) create_new_element(tag, attrib);
766 767 768 769 770 771

    Py_DECREF(tag);
    Py_DECREF(attrib);

    if (!element)
        return NULL;
772

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
    text = deepcopy(JOIN_OBJ(self->text), memo);
    if (!text)
        goto error;
    Py_DECREF(element->text);
    element->text = JOIN_SET(text, JOIN_GET(self->text));

    tail = deepcopy(JOIN_OBJ(self->tail), memo);
    if (!tail)
        goto error;
    Py_DECREF(element->tail);
    element->tail = JOIN_SET(tail, JOIN_GET(self->tail));

    if (self->extra) {
        if (element_resize(element, self->extra->length) < 0)
            goto error;

        for (i = 0; i < self->extra->length; i++) {
            PyObject* child = deepcopy(self->extra->children[i], memo);
            if (!child) {
                element->extra->length = i;
                goto error;
            }
            element->extra->children[i] = child;
        }

        element->extra->length = self->extra->length;
    }

    /* add object to memo dictionary (so deepcopy won't visit it again) */
802
    id = PyLong_FromSsize_t((Py_uintptr_t) self);
803 804
    if (!id)
        goto error;
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819

    i = PyDict_SetItem(memo, id, (PyObject*) element);

    Py_DECREF(id);

    if (i < 0)
        goto error;

    return (PyObject*) element;

  error:
    Py_DECREF(element);
    return NULL;
}

820
static PyObject*
821
element_sizeof(PyObject* myself, PyObject* args)
822
{
823
    ElementObject *self = (ElementObject*)myself;
824 825 826 827 828 829 830 831 832
    Py_ssize_t result = sizeof(ElementObject);
    if (self->extra) {
        result += sizeof(ElementObjectExtra);
        if (self->extra->children != self->extra->_children)
            result += sizeof(PyObject*) * self->extra->allocated;
    }
    return PyLong_FromSsize_t(result);
}

833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
/* dict keys for getstate/setstate. */
#define PICKLED_TAG "tag"
#define PICKLED_CHILDREN "_children"
#define PICKLED_ATTRIB "attrib"
#define PICKLED_TAIL "tail"
#define PICKLED_TEXT "text"

/* __getstate__ returns a fabricated instance dict as in the pure-Python
 * Element implementation, for interoperability/interchangeability.  This
 * makes the pure-Python implementation details an API, but (a) there aren't
 * any unnecessary structures there; and (b) it buys compatibility with 3.2
 * pickles.  See issue #16076.
 */
static PyObject *
element_getstate(ElementObject *self)
{
    int i, noattrib;
    PyObject *instancedict = NULL, *children;

    /* Build a list of children. */
    children = PyList_New(self->extra ? self->extra->length : 0);
    if (!children)
        return NULL;
    for (i = 0; i < PyList_GET_SIZE(children); i++) {
        PyObject *child = self->extra->children[i];
        Py_INCREF(child);
        PyList_SET_ITEM(children, i, child);
    }

    /* Construct the state object. */
    noattrib = (self->extra == NULL || self->extra->attrib == Py_None);
    if (noattrib)
        instancedict = Py_BuildValue("{sOsOs{}sOsO}",
                                     PICKLED_TAG, self->tag,
                                     PICKLED_CHILDREN, children,
                                     PICKLED_ATTRIB,
869 870
                                     PICKLED_TEXT, JOIN_OBJ(self->text),
                                     PICKLED_TAIL, JOIN_OBJ(self->tail));
871 872 873 874 875
    else
        instancedict = Py_BuildValue("{sOsOsOsOsO}",
                                     PICKLED_TAG, self->tag,
                                     PICKLED_CHILDREN, children,
                                     PICKLED_ATTRIB, self->extra->attrib,
876 877
                                     PICKLED_TEXT, JOIN_OBJ(self->text),
                                     PICKLED_TAIL, JOIN_OBJ(self->tail));
878 879
    if (instancedict) {
        Py_DECREF(children);
880
        return instancedict;
881
    }
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
    else {
        for (i = 0; i < PyList_GET_SIZE(children); i++)
            Py_DECREF(PyList_GET_ITEM(children, i));
        Py_DECREF(children);

        return NULL;
    }
}

static PyObject *
element_setstate_from_attributes(ElementObject *self,
                                 PyObject *tag,
                                 PyObject *attrib,
                                 PyObject *text,
                                 PyObject *tail,
                                 PyObject *children)
{
899
    int i, nchildren;
900 901 902 903 904 905 906 907 908 909

    if (!tag) {
        PyErr_SetString(PyExc_TypeError, "tag may not be NULL");
        return NULL;
    }

    Py_CLEAR(self->tag);
    self->tag = tag;
    Py_INCREF(self->tag);

910 911 912
    _clear_joined_ptr(&self->text);
    self->text = text ? JOIN_SET(text, PyList_CheckExact(text)) : Py_None;
    Py_INCREF(JOIN_OBJ(self->text));
913

914 915 916
    _clear_joined_ptr(&self->tail);
    self->tail = tail ? JOIN_SET(tail, PyList_CheckExact(tail)) : Py_None;
    Py_INCREF(JOIN_OBJ(self->tail));
917 918 919 920 921 922 923

    /* Handle ATTRIB and CHILDREN. */
    if (!children && !attrib)
        Py_RETURN_NONE;

    /* Compute 'nchildren'. */
    if (children) {
924
        Py_ssize_t size;
925 926 927 928
        if (!PyList_Check(children)) {
            PyErr_SetString(PyExc_TypeError, "'_children' is not a list");
            return NULL;
        }
929 930 931 932 933 934 935
        size = PyList_Size(children);
        /* expat limits nchildren to int */
        if (size > INT_MAX) {
            PyErr_SetString(PyExc_OverflowError, "too many children");
            return NULL;
        }
        nchildren = (int)size;
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
    }
    else {
        nchildren = 0;
    }

    /* Allocate 'extra'. */
    if (element_resize(self, nchildren)) {
        return NULL;
    }
    assert(self->extra && self->extra->allocated >= nchildren);

    /* Copy children */
    for (i = 0; i < nchildren; i++) {
        self->extra->children[i] = PyList_GET_ITEM(children, i);
        Py_INCREF(self->extra->children[i]);
    }

    self->extra->length = nchildren;
    self->extra->allocated = nchildren;

    /* Stash attrib. */
    if (attrib) {
        Py_CLEAR(self->extra->attrib);
        self->extra->attrib = attrib;
        Py_INCREF(attrib);
    }

    Py_RETURN_NONE;
}

/* __setstate__ for Element instance from the Python implementation.
 * 'state' should be the instance dict.
 */
static PyObject *
element_setstate_from_Python(ElementObject *self, PyObject *state)
{
    static char *kwlist[] = {PICKLED_TAG, PICKLED_ATTRIB, PICKLED_TEXT,
                             PICKLED_TAIL, PICKLED_CHILDREN, 0};
    PyObject *args;
    PyObject *tag, *attrib, *text, *tail, *children;
976
    PyObject *retval;
977 978 979

    tag = attrib = text = tail = children = NULL;
    args = PyTuple_New(0);
980
    if (!args)
981
        return NULL;
982 983 984 985 986

    if (PyArg_ParseTupleAndKeywords(args, state, "|$OOOOO", kwlist, &tag,
                                    &attrib, &text, &tail, &children))
        retval = element_setstate_from_attributes(self, tag, attrib, text,
                                                  tail, children);
987
    else
988 989 990 991
        retval = NULL;

    Py_DECREF(args);
    return retval;
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
}

static PyObject *
element_setstate(ElementObject *self, PyObject *state)
{
    if (!PyDict_CheckExact(state)) {
        PyErr_Format(PyExc_TypeError,
                     "Don't know how to unpickle \"%.200R\" as an Element",
                     state);
        return NULL;
    }
    else
        return element_setstate_from_Python(self, state);
}

1007 1008 1009
LOCAL(int)
checkpath(PyObject* tag)
{
1010 1011
    Py_ssize_t i;
    int check = 1;
1012 1013 1014

    /* check if a tag contains an xpath character */

1015 1016
#define PATHCHAR(ch) \
    (ch == '/' || ch == '*' || ch == '[' || ch == '@' || ch == '.')
1017 1018

    if (PyUnicode_Check(tag)) {
Martin v. Löwis's avatar
Martin v. Löwis committed
1019 1020 1021 1022 1023 1024
        const Py_ssize_t len = PyUnicode_GET_LENGTH(tag);
        void *data = PyUnicode_DATA(tag);
        unsigned int kind = PyUnicode_KIND(tag);
        for (i = 0; i < len; i++) {
            Py_UCS4 ch = PyUnicode_READ(kind, data, i);
            if (ch == '{')
1025
                check = 0;
Martin v. Löwis's avatar
Martin v. Löwis committed
1026
            else if (ch == '}')
1027
                check = 1;
Martin v. Löwis's avatar
Martin v. Löwis committed
1028
            else if (check && PATHCHAR(ch))
1029 1030 1031 1032
                return 1;
        }
        return 0;
    }
1033 1034 1035
    if (PyBytes_Check(tag)) {
        char *p = PyBytes_AS_STRING(tag);
        for (i = 0; i < PyBytes_GET_SIZE(tag); i++) {
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
            if (p[i] == '{')
                check = 0;
            else if (p[i] == '}')
                check = 1;
            else if (check && PATHCHAR(p[i]))
                return 1;
        }
        return 0;
    }

    return 1; /* unknown type; might be path expression */
}

1049 1050 1051 1052
static PyObject*
element_extend(ElementObject* self, PyObject* args)
{
    PyObject* seq;
1053
    Py_ssize_t i;
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067

    PyObject* seq_in;
    if (!PyArg_ParseTuple(args, "O:extend", &seq_in))
        return NULL;

    seq = PySequence_Fast(seq_in, "");
    if (!seq) {
        PyErr_Format(
            PyExc_TypeError,
            "expected sequence, not \"%.200s\"", Py_TYPE(seq_in)->tp_name
            );
        return NULL;
    }

1068
    for (i = 0; i < PySequence_Fast_GET_SIZE(seq); i++) {
1069
        PyObject* element = PySequence_Fast_GET_ITEM(seq, i);
1070 1071
        Py_INCREF(element);
        if (!PyObject_TypeCheck(element, (PyTypeObject *)&Element_Type)) {
1072 1073 1074 1075
            PyErr_Format(
                PyExc_TypeError,
                "expected an Element, not \"%.200s\"",
                Py_TYPE(element)->tp_name);
1076 1077
            Py_DECREF(seq);
            Py_DECREF(element);
1078 1079 1080
            return NULL;
        }

1081 1082
        if (element_add_subelement(self, element) < 0) {
            Py_DECREF(seq);
1083
            Py_DECREF(element);
1084 1085
            return NULL;
        }
1086
        Py_DECREF(element);
1087 1088 1089 1090 1091 1092 1093
    }

    Py_DECREF(seq);

    Py_RETURN_NONE;
}

1094
static PyObject*
1095
element_find(ElementObject *self, PyObject *args, PyObject *kwds)
1096 1097 1098
{
    int i;
    PyObject* tag;
1099
    PyObject* namespaces = Py_None;
1100
    static char *kwlist[] = {"path", "namespaces", 0};
1101
    elementtreestate *st = ET_STATE_GLOBAL;
1102

1103 1104
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:find", kwlist,
                                     &tag, &namespaces))
1105 1106
        return NULL;

1107
    if (checkpath(tag) || namespaces != Py_None) {
1108
        _Py_IDENTIFIER(find);
1109
        return _PyObject_CallMethodId(
1110
            st->elementpath_obj, &PyId_find, "OOO", self, tag, namespaces
1111
            );
1112
    }
1113 1114 1115

    if (!self->extra)
        Py_RETURN_NONE;
1116

1117 1118
    for (i = 0; i < self->extra->length; i++) {
        PyObject* item = self->extra->children[i];
1119 1120 1121 1122 1123 1124
        int rc;
        if (!Element_CheckExact(item))
            continue;
        Py_INCREF(item);
        rc = PyObject_RichCompareBool(((ElementObject*)item)->tag, tag, Py_EQ);
        if (rc > 0)
1125
            return item;
1126 1127 1128
        Py_DECREF(item);
        if (rc < 0)
            return NULL;
1129 1130 1131 1132 1133 1134
    }

    Py_RETURN_NONE;
}

static PyObject*
1135
element_findtext(ElementObject *self, PyObject *args, PyObject *kwds)
1136 1137 1138 1139
{
    int i;
    PyObject* tag;
    PyObject* default_value = Py_None;
1140
    PyObject* namespaces = Py_None;
1141
    _Py_IDENTIFIER(findtext);
1142
    static char *kwlist[] = {"path", "default", "namespaces", 0};
1143
    elementtreestate *st = ET_STATE_GLOBAL;
1144

1145 1146
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO:findtext", kwlist,
                                     &tag, &default_value, &namespaces))
1147 1148
        return NULL;

1149
    if (checkpath(tag) || namespaces != Py_None)
1150
        return _PyObject_CallMethodId(
1151
            st->elementpath_obj, &PyId_findtext, "OOOO", self, tag, default_value, namespaces
1152 1153 1154 1155 1156 1157 1158 1159 1160
            );

    if (!self->extra) {
        Py_INCREF(default_value);
        return default_value;
    }

    for (i = 0; i < self->extra->length; i++) {
        ElementObject* item = (ElementObject*) self->extra->children[i];
1161 1162 1163 1164 1165 1166
        int rc;
        if (!Element_CheckExact(item))
            continue;
        Py_INCREF(item);
        rc = PyObject_RichCompareBool(item->tag, tag, Py_EQ);
        if (rc > 0) {
1167
            PyObject* text = element_get_text(item);
1168 1169
            if (text == Py_None) {
                Py_DECREF(item);
1170
                return PyUnicode_New(0, 0);
1171
            }
1172
            Py_XINCREF(text);
1173
            Py_DECREF(item);
1174 1175
            return text;
        }
1176 1177 1178
        Py_DECREF(item);
        if (rc < 0)
            return NULL;
1179 1180 1181 1182 1183 1184 1185
    }

    Py_INCREF(default_value);
    return default_value;
}

static PyObject*
1186
element_findall(ElementObject *self, PyObject *args, PyObject *kwds)
1187 1188 1189 1190
{
    int i;
    PyObject* out;
    PyObject* tag;
1191
    PyObject* namespaces = Py_None;
1192
    static char *kwlist[] = {"path", "namespaces", 0};
1193
    elementtreestate *st = ET_STATE_GLOBAL;
1194

1195 1196
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:findall", kwlist,
                                     &tag, &namespaces))
1197 1198
        return NULL;

1199
    if (checkpath(tag) || namespaces != Py_None) {
1200
        _Py_IDENTIFIER(findall);
1201
        return _PyObject_CallMethodId(
1202
            st->elementpath_obj, &PyId_findall, "OOO", self, tag, namespaces
1203
            );
1204
    }
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214

    out = PyList_New(0);
    if (!out)
        return NULL;

    if (!self->extra)
        return out;

    for (i = 0; i < self->extra->length; i++) {
        PyObject* item = self->extra->children[i];
1215 1216 1217 1218 1219 1220 1221 1222 1223
        int rc;
        if (!Element_CheckExact(item))
            continue;
        Py_INCREF(item);
        rc = PyObject_RichCompareBool(((ElementObject*)item)->tag, tag, Py_EQ);
        if (rc != 0 && (rc < 0 || PyList_Append(out, item) < 0)) {
            Py_DECREF(item);
            Py_DECREF(out);
            return NULL;
1224
        }
1225
        Py_DECREF(item);
1226 1227 1228 1229 1230
    }

    return out;
}

1231
static PyObject*
1232
element_iterfind(ElementObject *self, PyObject *args, PyObject *kwds)
1233 1234 1235
{
    PyObject* tag;
    PyObject* namespaces = Py_None;
1236
    _Py_IDENTIFIER(iterfind);
1237
    static char *kwlist[] = {"path", "namespaces", 0};
1238
    elementtreestate *st = ET_STATE_GLOBAL;
1239

1240
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:iterfind", kwlist,
Eli Bendersky's avatar
Eli Bendersky committed
1241
                                     &tag, &namespaces)) {
1242
        return NULL;
Eli Bendersky's avatar
Eli Bendersky committed
1243
    }
1244

1245
    return _PyObject_CallMethodId(
Eli Bendersky's avatar
Eli Bendersky committed
1246
        st->elementpath_obj, &PyId_iterfind, "OOO", self, tag, namespaces);
1247 1248
}

1249
static PyObject*
1250
element_get(ElementObject* self, PyObject* args, PyObject* kwds)
1251 1252
{
    PyObject* value;
1253
    static char* kwlist[] = {"key", "default", 0};
1254 1255 1256

    PyObject* key;
    PyObject* default_value = Py_None;
1257 1258 1259

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:get", kwlist, &key,
                                     &default_value))
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
        return NULL;

    if (!self->extra || self->extra->attrib == Py_None)
        value = default_value;
    else {
        value = PyDict_GetItem(self->extra->attrib, key);
        if (!value)
            value = default_value;
    }

    Py_INCREF(value);
    return value;
}

static PyObject*
element_getchildren(ElementObject* self, PyObject* args)
{
    int i;
    PyObject* list;

1280 1281
    /* FIXME: report as deprecated? */

1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
    if (!PyArg_ParseTuple(args, ":getchildren"))
        return NULL;

    if (!self->extra)
        return PyList_New(0);

    list = PyList_New(self->extra->length);
    if (!list)
        return NULL;

    for (i = 0; i < self->extra->length; i++) {
        PyObject* item = self->extra->children[i];
        Py_INCREF(item);
        PyList_SET_ITEM(list, i, item);
    }

    return list;
}

1301

1302 1303
static PyObject *
create_elementiter(ElementObject *self, PyObject *tag, int gettext);
1304 1305


1306
static PyObject *
1307
element_iter(ElementObject *self, PyObject *args, PyObject *kwds)
1308 1309
{
    PyObject* tag = Py_None;
1310 1311 1312
    static char* kwlist[] = {"tag", 0};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:iter", kwlist, &tag))
1313
        return NULL;
1314

1315
    return create_elementiter(self, tag, 0);
1316 1317
}

1318

1319
static PyObject*
1320
element_itertext(ElementObject* self, PyObject* args)
1321
{
1322 1323
    if (!PyArg_ParseTuple(args, ":itertext"))
        return NULL;
1324

1325
    return create_elementiter(self, Py_None, 1);
1326 1327
}

1328

1329
static PyObject*
1330
element_getitem(PyObject* self_, Py_ssize_t index)
1331
{
1332
    ElementObject* self = (ElementObject*) self_;
1333

1334 1335 1336 1337 1338
    if (!self->extra || index < 0 || index >= self->extra->length) {
        PyErr_SetString(
            PyExc_IndexError,
            "child index out of range"
            );
1339 1340 1341
        return NULL;
    }

1342 1343
    Py_INCREF(self->extra->children[index]);
    return self->extra->children[index];
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
}

static PyObject*
element_insert(ElementObject* self, PyObject* args)
{
    int i;

    int index;
    PyObject* element;
    if (!PyArg_ParseTuple(args, "iO!:insert", &index,
                          &Element_Type, &element))
        return NULL;

1357 1358 1359 1360
    if (!self->extra) {
        if (create_extra(self, NULL) < 0)
            return NULL;
    }
1361

1362 1363 1364 1365 1366
    if (index < 0) {
        index += self->extra->length;
        if (index < 0)
            index = 0;
    }
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
    if (index > self->extra->length)
        index = self->extra->length;

    if (element_resize(self, 1) < 0)
        return NULL;

    for (i = self->extra->length; i > index; i--)
        self->extra->children[i] = self->extra->children[i-1];

    Py_INCREF(element);
    self->extra->children[index] = element;

    self->extra->length++;

    Py_RETURN_NONE;
}

static PyObject*
element_items(ElementObject* self, PyObject* args)
{
    if (!PyArg_ParseTuple(args, ":items"))
        return NULL;

    if (!self->extra || self->extra->attrib == Py_None)
        return PyList_New(0);

    return PyDict_Items(self->extra->attrib);
}

static PyObject*
element_keys(ElementObject* self, PyObject* args)
{
    if (!PyArg_ParseTuple(args, ":keys"))
        return NULL;

    if (!self->extra || self->extra->attrib == Py_None)
        return PyList_New(0);

    return PyDict_Keys(self->extra->attrib);
}

Martin v. Löwis's avatar
Martin v. Löwis committed
1408
static Py_ssize_t
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
element_length(ElementObject* self)
{
    if (!self->extra)
        return 0;

    return self->extra->length;
}

static PyObject*
element_makeelement(PyObject* self, PyObject* args, PyObject* kw)
{
    PyObject* elem;

    PyObject* tag;
    PyObject* attrib;
    if (!PyArg_ParseTuple(args, "OO:makeelement", &tag, &attrib))
        return NULL;

    attrib = PyDict_Copy(attrib);
    if (!attrib)
        return NULL;

1431
    elem = create_new_element(tag, attrib);
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441

    Py_DECREF(attrib);

    return elem;
}

static PyObject*
element_remove(ElementObject* self, PyObject* args)
{
    int i;
1442
    int rc;
1443
    PyObject* element;
1444 1445
    PyObject* found;

1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    if (!PyArg_ParseTuple(args, "O!:remove", &Element_Type, &element))
        return NULL;

    if (!self->extra) {
        /* element has no children, so raise exception */
        PyErr_SetString(
            PyExc_ValueError,
            "list.remove(x): x not in list"
            );
        return NULL;
    }

    for (i = 0; i < self->extra->length; i++) {
        if (self->extra->children[i] == element)
            break;
1461 1462
        rc = PyObject_RichCompareBool(self->extra->children[i], element, Py_EQ);
        if (rc > 0)
1463
            break;
1464 1465
        if (rc < 0)
            return NULL;
1466 1467
    }

1468
    if (i >= self->extra->length) {
1469 1470 1471 1472 1473 1474 1475 1476
        /* element is not in children, so raise exception */
        PyErr_SetString(
            PyExc_ValueError,
            "list.remove(x): x not in list"
            );
        return NULL;
    }

1477
    found = self->extra->children[i];
1478 1479 1480 1481 1482

    self->extra->length--;
    for (; i < self->extra->length; i++)
        self->extra->children[i] = self->extra->children[i+1];

1483
    Py_DECREF(found);
1484 1485 1486 1487 1488 1489
    Py_RETURN_NONE;
}

static PyObject*
element_repr(ElementObject* self)
{
1490 1491 1492 1493
    if (self->tag)
        return PyUnicode_FromFormat("<Element %R at %p>", self->tag, self);
    else
        return PyUnicode_FromFormat("<Element at %p>", self);
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
}

static PyObject*
element_set(ElementObject* self, PyObject* args)
{
    PyObject* attrib;

    PyObject* key;
    PyObject* value;
    if (!PyArg_ParseTuple(args, "OO:set", &key, &value))
        return NULL;

1506 1507 1508 1509
    if (!self->extra) {
        if (create_extra(self, NULL) < 0)
            return NULL;
    }
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521

    attrib = element_get_attrib(self);
    if (!attrib)
        return NULL;

    if (PyDict_SetItem(attrib, key, value) < 0)
        return NULL;

    Py_RETURN_NONE;
}

static int
1522
element_setitem(PyObject* self_, Py_ssize_t index_, PyObject* item)
1523
{
1524
    ElementObject* self = (ElementObject*) self_;
1525
    int i, index;
1526 1527
    PyObject* old;

1528
    if (!self->extra || index_ < 0 || index_ >= self->extra->length) {
1529 1530 1531 1532 1533
        PyErr_SetString(
            PyExc_IndexError,
            "child assignment index out of range");
        return -1;
    }
1534
    index = (int)index_;
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551

    old = self->extra->children[index];

    if (item) {
        Py_INCREF(item);
        self->extra->children[index] = item;
    } else {
        self->extra->length--;
        for (i = index; i < self->extra->length; i++)
            self->extra->children[i] = self->extra->children[i+1];
    }

    Py_DECREF(old);

    return 0;
}

1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
static PyObject*
element_subscr(PyObject* self_, PyObject* item)
{
    ElementObject* self = (ElementObject*) self_;

    if (PyIndex_Check(item)) {
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);

        if (i == -1 && PyErr_Occurred()) {
            return NULL;
        }
        if (i < 0 && self->extra)
            i += self->extra->length;
        return element_getitem(self_, i);
    }
    else if (PySlice_Check(item)) {
        Py_ssize_t start, stop, step, slicelen, cur, i;
        PyObject* list;

        if (!self->extra)
            return PyList_New(0);

Martin v. Löwis's avatar
Martin v. Löwis committed
1574
        if (PySlice_GetIndicesEx(item,
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
                self->extra->length,
                &start, &stop, &step, &slicelen) < 0) {
            return NULL;
        }

        if (slicelen <= 0)
            return PyList_New(0);
        else {
            list = PyList_New(slicelen);
            if (!list)
                return NULL;

            for (cur = start, i = 0; i < slicelen;
                 cur += step, i++) {
                PyObject* item = self->extra->children[cur];
                Py_INCREF(item);
                PyList_SET_ITEM(list, i, item);
            }

            return list;
        }
    }
    else {
        PyErr_SetString(PyExc_TypeError,
                "element indices must be integers");
        return NULL;
    }
}

static int
element_ass_subscr(PyObject* self_, PyObject* item, PyObject* value)
{
    ElementObject* self = (ElementObject*) self_;

    if (PyIndex_Check(item)) {
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);

        if (i == -1 && PyErr_Occurred()) {
            return -1;
        }
        if (i < 0 && self->extra)
            i += self->extra->length;
        return element_setitem(self_, i, value);
    }
    else if (PySlice_Check(item)) {
        Py_ssize_t start, stop, step, slicelen, newlen, cur, i;

        PyObject* recycle = NULL;
1623
        PyObject* seq;
1624

1625 1626 1627 1628
        if (!self->extra) {
            if (create_extra(self, NULL) < 0)
                return -1;
        }
1629

Martin v. Löwis's avatar
Martin v. Löwis committed
1630
        if (PySlice_GetIndicesEx(item,
1631 1632 1633 1634
                self->extra->length,
                &start, &stop, &step, &slicelen) < 0) {
            return -1;
        }
1635
        assert(slicelen <= self->extra->length);
1636

1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
        if (value == NULL) {
            /* Delete slice */
            size_t cur;
            Py_ssize_t i;

            if (slicelen <= 0)
                return 0;

            /* Since we're deleting, the direction of the range doesn't matter,
             * so for simplicity make it always ascending.
            */
            if (step < 0) {
                stop = start + 1;
                start = stop + step * (slicelen - 1) - 1;
                step = -step;
            }

            assert((size_t)slicelen <= PY_SIZE_MAX / sizeof(PyObject *));

            /* recycle is a list that will contain all the children
             * scheduled for removal.
            */
            if (!(recycle = PyList_New(slicelen))) {
                PyErr_NoMemory();
                return -1;
            }

            /* This loop walks over all the children that have to be deleted,
             * with cur pointing at them. num_moved is the amount of children
             * until the next deleted child that have to be "shifted down" to
             * occupy the deleted's places.
             * Note that in the ith iteration, shifting is done i+i places down
             * because i children were already removed.
            */
            for (cur = start, i = 0; cur < (size_t)stop; cur += step, ++i) {
                /* Compute how many children have to be moved, clipping at the
                 * list end.
                */
                Py_ssize_t num_moved = step - 1;
                if (cur + step >= (size_t)self->extra->length) {
                    num_moved = self->extra->length - cur - 1;
                }

                PyList_SET_ITEM(recycle, i, self->extra->children[cur]);

                memmove(
                    self->extra->children + cur - i,
                    self->extra->children + cur + 1,
                    num_moved * sizeof(PyObject *));
            }

            /* Leftover "tail" after the last removed child */
            cur = start + (size_t)slicelen * step;
            if (cur < (size_t)self->extra->length) {
                memmove(
                    self->extra->children + cur - slicelen,
                    self->extra->children + cur,
                    (self->extra->length - cur) * sizeof(PyObject *));
            }

1697
            self->extra->length -= (int)slicelen;
1698 1699 1700 1701 1702

            /* Discard the recycle list with all the deleted sub-elements */
            Py_XDECREF(recycle);
            return 0;
        }
1703 1704 1705 1706 1707 1708 1709 1710 1711

        /* A new slice is actually being assigned */
        seq = PySequence_Fast(value, "");
        if (!seq) {
            PyErr_Format(
                PyExc_TypeError,
                "expected sequence, not \"%.200s\"", Py_TYPE(value)->tp_name
                );
            return -1;
1712
        }
1713
        newlen = PySequence_Size(seq);
1714 1715 1716

        if (step !=  1 && newlen != slicelen)
        {
1717
            Py_DECREF(seq);
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
            PyErr_Format(PyExc_ValueError,
                "attempt to assign sequence of size %zd "
                "to extended slice of size %zd",
                newlen, slicelen
                );
            return -1;
        }

        /* Resize before creating the recycle bin, to prevent refleaks. */
        if (newlen > slicelen) {
            if (element_resize(self, newlen - slicelen) < 0) {
1729
                Py_DECREF(seq);
1730 1731 1732
                return -1;
            }
        }
1733 1734
        assert(newlen - slicelen <= INT_MAX - self->extra->length);
        assert(newlen - slicelen >= -self->extra->length);
1735 1736 1737 1738 1739 1740 1741

        if (slicelen > 0) {
            /* to avoid recursive calls to this method (via decref), move
               old items to the recycle bin here, and get rid of them when
               we're done modifying the element */
            recycle = PyList_New(slicelen);
            if (!recycle) {
1742
                Py_DECREF(seq);
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
                return -1;
            }
            for (cur = start, i = 0; i < slicelen;
                 cur += step, i++)
                PyList_SET_ITEM(recycle, i, self->extra->children[cur]);
        }

        if (newlen < slicelen) {
            /* delete slice */
            for (i = stop; i < self->extra->length; i++)
                self->extra->children[i + newlen - slicelen] = self->extra->children[i];
        } else if (newlen > slicelen) {
            /* insert slice */
            for (i = self->extra->length-1; i >= stop; i--)
                self->extra->children[i + newlen - slicelen] = self->extra->children[i];
        }

        /* replace the slice */
        for (cur = start, i = 0; i < newlen;
             cur += step, i++) {
            PyObject* element = PySequence_Fast_GET_ITEM(seq, i);
            Py_INCREF(element);
            self->extra->children[cur] = element;
        }

1768
        self->extra->length += (int)(newlen - slicelen);
1769

1770
        Py_DECREF(seq);
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783

        /* discard the recycle bin, and everything in it */
        Py_XDECREF(recycle);

        return 0;
    }
    else {
        PyErr_SetString(PyExc_TypeError,
                "element indices must be integers");
        return -1;
    }
}

1784 1785
static PyMethodDef element_methods[] = {

1786
    {"clear", (PyCFunction) element_clearmethod, METH_VARARGS},
1787

1788
    {"get", (PyCFunction) element_get, METH_VARARGS | METH_KEYWORDS},
1789 1790
    {"set", (PyCFunction) element_set, METH_VARARGS},

1791 1792 1793
    {"find", (PyCFunction) element_find, METH_VARARGS | METH_KEYWORDS},
    {"findtext", (PyCFunction) element_findtext, METH_VARARGS | METH_KEYWORDS},
    {"findall", (PyCFunction) element_findall, METH_VARARGS | METH_KEYWORDS},
1794 1795

    {"append", (PyCFunction) element_append, METH_VARARGS},
1796
    {"extend", (PyCFunction) element_extend, METH_VARARGS},
1797 1798 1799
    {"insert", (PyCFunction) element_insert, METH_VARARGS},
    {"remove", (PyCFunction) element_remove, METH_VARARGS},

1800
    {"iter", (PyCFunction) element_iter, METH_VARARGS | METH_KEYWORDS},
1801
    {"itertext", (PyCFunction) element_itertext, METH_VARARGS},
1802
    {"iterfind", (PyCFunction) element_iterfind, METH_VARARGS | METH_KEYWORDS},
1803

1804
    {"getiterator", (PyCFunction) element_iter, METH_VARARGS | METH_KEYWORDS},
1805 1806 1807 1808 1809 1810 1811 1812 1813
    {"getchildren", (PyCFunction) element_getchildren, METH_VARARGS},

    {"items", (PyCFunction) element_items, METH_VARARGS},
    {"keys", (PyCFunction) element_keys, METH_VARARGS},

    {"makeelement", (PyCFunction) element_makeelement, METH_VARARGS},

    {"__copy__", (PyCFunction) element_copy, METH_VARARGS},
    {"__deepcopy__", (PyCFunction) element_deepcopy, METH_VARARGS},
1814
    {"__sizeof__", element_sizeof, METH_NOARGS},
1815 1816
    {"__getstate__", (PyCFunction)element_getstate, METH_NOARGS},
    {"__setstate__", (PyCFunction)element_setstate, METH_O},
1817 1818 1819 1820

    {NULL, NULL}
};

1821
static PyObject*
1822
element_getattro(ElementObject* self, PyObject* nameobj)
1823 1824
{
    PyObject* res;
1825
    char *name = "";
1826

1827
    if (PyUnicode_Check(nameobj))
1828
        name = _PyUnicode_AsString(nameobj);
1829

1830 1831
    if (name == NULL)
        return NULL;
1832

1833 1834 1835 1836 1837 1838
    /* handle common attributes first */
    if (strcmp(name, "tag") == 0) {
        res = self->tag;
        Py_INCREF(res);
        return res;
    } else if (strcmp(name, "text") == 0) {
1839
        res = element_get_text(self);
1840
        Py_XINCREF(res);
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
        return res;
    }

    /* methods */
    res = PyObject_GenericGetAttr((PyObject*) self, nameobj);
    if (res)
        return res;

    /* less common attributes */
    if (strcmp(name, "tail") == 0) {
        PyErr_Clear();
1852 1853
        res = element_get_tail(self);
    } else if (strcmp(name, "attrib") == 0) {
1854
        PyErr_Clear();
1855 1856 1857 1858
        if (!self->extra) {
            if (create_extra(self, NULL) < 0)
                return NULL;
        }
1859
        res = element_get_attrib(self);
1860 1861
    }

1862 1863 1864 1865
    if (!res)
        return NULL;

    Py_INCREF(res);
1866 1867 1868
    return res;
}

1869
static int
1870
element_setattro(ElementObject* self, PyObject* nameobj, PyObject* value)
1871
{
1872
    char *name = "";
1873 1874 1875 1876 1877 1878

    if (value == NULL) {
        PyErr_SetString(PyExc_AttributeError,
            "can't delete attribute");
        return -1;
    }
1879 1880
    if (PyUnicode_Check(nameobj))
        name = _PyUnicode_AsString(nameobj);
Victor Stinner's avatar
Victor Stinner committed
1881
    if (name == NULL)
1882
        return -1;
Victor Stinner's avatar
Victor Stinner committed
1883 1884

    if (strcmp(name, "tag") == 0) {
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
        Py_DECREF(self->tag);
        self->tag = value;
        Py_INCREF(self->tag);
    } else if (strcmp(name, "text") == 0) {
        Py_DECREF(JOIN_OBJ(self->text));
        self->text = value;
        Py_INCREF(self->text);
    } else if (strcmp(name, "tail") == 0) {
        Py_DECREF(JOIN_OBJ(self->tail));
        self->tail = value;
        Py_INCREF(self->tail);
    } else if (strcmp(name, "attrib") == 0) {
1897 1898 1899 1900
        if (!self->extra) {
            if (create_extra(self, NULL) < 0)
                return -1;
        }
1901 1902 1903 1904
        Py_DECREF(self->extra->attrib);
        self->extra->attrib = value;
        Py_INCREF(self->extra->attrib);
    } else {
1905
        PyErr_SetString(PyExc_AttributeError,
1906
            "Can't set arbitrary attributes on Element");
1907
        return -1;
1908 1909
    }

1910
    return 0;
1911 1912 1913
}

static PySequenceMethods element_as_sequence = {
Martin v. Löwis's avatar
Martin v. Löwis committed
1914
    (lenfunc) element_length,
1915 1916
    0, /* sq_concat */
    0, /* sq_repeat */
Martin v. Löwis's avatar
Martin v. Löwis committed
1917
    element_getitem,
1918
    0,
Martin v. Löwis's avatar
Martin v. Löwis committed
1919
    element_setitem,
1920 1921 1922 1923 1924 1925 1926
    0,
};

static PyMappingMethods element_as_mapping = {
    (lenfunc) element_length,
    (binaryfunc) element_subscr,
    (objobjargproc) element_ass_subscr,
1927 1928
};

1929
static PyTypeObject Element_Type = {
1930
    PyVarObject_HEAD_INIT(NULL, 0)
1931
    "xml.etree.ElementTree.Element", sizeof(ElementObject), 0,
1932
    /* methods */
1933 1934 1935
    (destructor)element_dealloc,                    /* tp_dealloc */
    0,                                              /* tp_print */
    0,                                              /* tp_getattr */
1936
    0,                                              /* tp_setattr */
1937 1938 1939 1940 1941 1942 1943 1944 1945
    0,                                              /* tp_reserved */
    (reprfunc)element_repr,                         /* tp_repr */
    0,                                              /* tp_as_number */
    &element_as_sequence,                           /* tp_as_sequence */
    &element_as_mapping,                            /* tp_as_mapping */
    0,                                              /* tp_hash */
    0,                                              /* tp_call */
    0,                                              /* tp_str */
    (getattrofunc)element_getattro,                 /* tp_getattro */
1946
    (setattrofunc)element_setattro,                 /* tp_setattro */
1947
    0,                                              /* tp_as_buffer */
1948 1949
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
                                                    /* tp_flags */
1950
    0,                                              /* tp_doc */
1951 1952
    (traverseproc)element_gc_traverse,              /* tp_traverse */
    (inquiry)element_gc_clear,                      /* tp_clear */
1953
    0,                                              /* tp_richcompare */
1954
    offsetof(ElementObject, weakreflist),           /* tp_weaklistoffset */
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
    0,                                              /* tp_iter */
    0,                                              /* tp_iternext */
    element_methods,                                /* tp_methods */
    0,                                              /* tp_members */
    0,                                              /* tp_getset */
    0,                                              /* tp_base */
    0,                                              /* tp_dict */
    0,                                              /* tp_descr_get */
    0,                                              /* tp_descr_set */
    0,                                              /* tp_dictoffset */
    (initproc)element_init,                         /* tp_init */
    PyType_GenericAlloc,                            /* tp_alloc */
    element_new,                                    /* tp_new */
    0,                                              /* tp_free */
1969 1970
};

1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
/******************************* Element iterator ****************************/

/* ElementIterObject represents the iteration state over an XML element in
 * pre-order traversal. To keep track of which sub-element should be returned
 * next, a stack of parents is maintained. This is a standard stack-based
 * iterative pre-order traversal of a tree.
 * The stack is managed using a single-linked list starting at parent_stack.
 * Each stack node contains the saved parent to which we should return after
 * the current one is exhausted, and the next child to examine in that parent.
 */
typedef struct ParentLocator_t {
    ElementObject *parent;
    Py_ssize_t child_index;
    struct ParentLocator_t *next;
} ParentLocator;

typedef struct {
    PyObject_HEAD
    ParentLocator *parent_stack;
    ElementObject *root_element;
    PyObject *sought_tag;
    int root_done;
    int gettext;
} ElementIterObject;


static void
elementiter_dealloc(ElementIterObject *it)
{
    ParentLocator *p = it->parent_stack;
    while (p) {
        ParentLocator *temp = p;
        Py_XDECREF(p->parent);
        p = p->next;
        PyObject_Free(temp);
    }

    Py_XDECREF(it->sought_tag);
    Py_XDECREF(it->root_element);

    PyObject_GC_UnTrack(it);
    PyObject_GC_Del(it);
}

static int
elementiter_traverse(ElementIterObject *it, visitproc visit, void *arg)
{
    ParentLocator *p = it->parent_stack;
    while (p) {
        Py_VISIT(p->parent);
        p = p->next;
    }

    Py_VISIT(it->root_element);
    Py_VISIT(it->sought_tag);
    return 0;
}

/* Helper function for elementiter_next. Add a new parent to the parent stack.
 */
static ParentLocator *
parent_stack_push_new(ParentLocator *stack, ElementObject *parent)
{
    ParentLocator *new_node = PyObject_Malloc(sizeof(ParentLocator));
    if (new_node) {
        new_node->parent = parent;
        Py_INCREF(parent);
        new_node->child_index = 0;
        new_node->next = stack;
    }
    return new_node;
}

static PyObject *
elementiter_next(ElementIterObject *it)
{
    /* Sub-element iterator.
2048
     *
2049 2050 2051 2052 2053 2054 2055 2056 2057
     * A short note on gettext: this function serves both the iter() and
     * itertext() methods to avoid code duplication. However, there are a few
     * small differences in the way these iterations work. Namely:
     *   - itertext() only yields text from nodes that have it, and continues
     *     iterating when a node doesn't have text (so it doesn't return any
     *     node like iter())
     *   - itertext() also has to handle tail, after finishing with all the
     *     children of a node.
     */
2058 2059
    ElementObject *cur_parent;
    Py_ssize_t child_index;
2060
    int rc;
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081

    while (1) {
        /* Handle the case reached in the beginning and end of iteration, where
         * the parent stack is empty. The root_done flag gives us indication
         * whether we've just started iterating (so root_done is 0), in which
         * case the root is returned. If root_done is 1 and we're here, the
         * iterator is exhausted.
         */
        if (!it->parent_stack->parent) {
            if (it->root_done) {
                PyErr_SetNone(PyExc_StopIteration);
                return NULL;
            } else {
                it->parent_stack = parent_stack_push_new(it->parent_stack,
                                                         it->root_element);
                if (!it->parent_stack) {
                    PyErr_NoMemory();
                    return NULL;
                }

                it->root_done = 1;
2082 2083 2084 2085 2086 2087 2088 2089
                rc = (it->sought_tag == Py_None);
                if (!rc) {
                    rc = PyObject_RichCompareBool(it->root_element->tag,
                                                  it->sought_tag, Py_EQ);
                    if (rc < 0)
                        return NULL;
                }
                if (rc) {
2090
                    if (it->gettext) {
2091 2092 2093
                        PyObject *text = element_get_text(it->root_element);
                        if (!text)
                            return NULL;
2094 2095 2096 2097
                        rc = PyObject_IsTrue(text);
                        if (rc < 0)
                            return NULL;
                        if (rc) {
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
                            Py_INCREF(text);
                            return text;
                        }
                    } else {
                        Py_INCREF(it->root_element);
                        return (PyObject *)it->root_element;
                    }
                }
            }
        }

        /* See if there are children left to traverse in the current parent. If
         * yes, visit the next child. If not, pop the stack and try again.
         */
2112 2113
        cur_parent = it->parent_stack->parent;
        child_index = it->parent_stack->child_index;
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
        if (cur_parent->extra && child_index < cur_parent->extra->length) {
            ElementObject *child = (ElementObject *)
                cur_parent->extra->children[child_index];
            it->parent_stack->child_index++;
            it->parent_stack = parent_stack_push_new(it->parent_stack,
                                                     child);
            if (!it->parent_stack) {
                PyErr_NoMemory();
                return NULL;
            }

            if (it->gettext) {
2126 2127 2128
                PyObject *text = element_get_text(child);
                if (!text)
                    return NULL;
2129 2130 2131 2132
                rc = PyObject_IsTrue(text);
                if (rc < 0)
                    return NULL;
                if (rc) {
2133 2134 2135
                    Py_INCREF(text);
                    return text;
                }
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
            } else {
                rc = (it->sought_tag == Py_None);
                if (!rc) {
                    rc = PyObject_RichCompareBool(child->tag,
                                                  it->sought_tag, Py_EQ);
                    if (rc < 0)
                        return NULL;
                }
                if (rc) {
                    Py_INCREF(child);
                    return (PyObject *)child;
                }
2148 2149 2150
            }
        }
        else {
2151
            PyObject *tail;
2152
            ParentLocator *next = it->parent_stack->next;
2153 2154 2155 2156 2157 2158 2159
            if (it->gettext) {
                tail = element_get_tail(cur_parent);
                if (!tail)
                    return NULL;
            }
            else
                tail = Py_None;
2160 2161 2162 2163 2164 2165 2166 2167
            Py_XDECREF(it->parent_stack->parent);
            PyObject_Free(it->parent_stack);
            it->parent_stack = next;

            /* Note that extra condition on it->parent_stack->parent here;
             * this is because itertext() is supposed to only return *inner*
             * text, not text following the element it began iteration with.
             */
2168 2169 2170 2171 2172 2173 2174 2175
            if (it->parent_stack->parent) {
                rc = PyObject_IsTrue(tail);
                if (rc < 0)
                    return NULL;
                if (rc) {
                    Py_INCREF(tail);
                    return tail;
                }
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
            }
        }
    }

    return NULL;
}


static PyTypeObject ElementIter_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
2186 2187
    /* Using the module's name since the pure-Python implementation does not
       have such a type. */
2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
    "_elementtree._element_iterator",           /* tp_name */
    sizeof(ElementIterObject),                  /* tp_basicsize */
    0,                                          /* tp_itemsize */
    /* methods */
    (destructor)elementiter_dealloc,            /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    0,                                          /* tp_repr */
    0,                                          /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    0,                                          /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
    0,                                          /* tp_getattro */
    0,                                          /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
    0,                                          /* tp_doc */
    (traverseproc)elementiter_traverse,         /* tp_traverse */
    0,                                          /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    PyObject_SelfIter,                          /* tp_iter */
    (iternextfunc)elementiter_next,             /* tp_iternext */
    0,                                          /* tp_methods */
    0,                                          /* tp_members */
    0,                                          /* tp_getset */
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    0,                                          /* tp_descr_get */
    0,                                          /* tp_descr_set */
    0,                                          /* tp_dictoffset */
    0,                                          /* tp_init */
    0,                                          /* tp_alloc */
    0,                                          /* tp_new */
};


static PyObject *
create_elementiter(ElementObject *self, PyObject *tag, int gettext)
{
    ElementIterObject *it;

    it = PyObject_GC_New(ElementIterObject, &ElementIter_Type);
    if (!it)
        return NULL;

2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
    if (PyUnicode_Check(tag)) {
        if (PyUnicode_READY(tag) < 0)
            return NULL;
        if (PyUnicode_GET_LENGTH(tag) == 1 && PyUnicode_READ_CHAR(tag, 0) == '*')
            tag = Py_None;
    }
    else if (PyBytes_Check(tag)) {
        if (PyBytes_GET_SIZE(tag) == 1 && *PyBytes_AS_STRING(tag) == '*')
            tag = Py_None;
    }
Victor Stinner's avatar
Victor Stinner committed
2248 2249

    Py_INCREF(tag);
2250 2251 2252
    it->sought_tag = tag;
    it->root_done = 0;
    it->gettext = gettext;
Victor Stinner's avatar
Victor Stinner committed
2253
    Py_INCREF(self);
2254 2255 2256
    it->root_element = self;

    PyObject_GC_Track(it);
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267

    it->parent_stack = PyObject_Malloc(sizeof(ParentLocator));
    if (it->parent_stack == NULL) {
        Py_DECREF(it);
        PyErr_NoMemory();
        return NULL;
    }
    it->parent_stack->parent = NULL;
    it->parent_stack->child_index = 0;
    it->parent_stack->next = NULL;

2268 2269 2270 2271
    return (PyObject *)it;
}


2272 2273 2274 2275 2276 2277
/* ==================================================================== */
/* the tree builder type */

typedef struct {
    PyObject_HEAD

2278
    PyObject *root; /* root node (first created node) */
2279

2280 2281
    PyObject *this; /* current node */
    PyObject *last; /* most recently created node */
2282

2283
    PyObject *data; /* data collector (string or list), or NULL */
2284

2285 2286
    PyObject *stack; /* element stack */
    Py_ssize_t index; /* current stack size (0 means empty) */
2287

2288 2289
    PyObject *element_factory;

2290
    /* element tracing */
2291 2292 2293 2294 2295
    PyObject *events; /* list of events, or NULL if not collecting */
    PyObject *start_event_obj; /* event objects (NULL to ignore) */
    PyObject *end_event_obj;
    PyObject *start_ns_event_obj;
    PyObject *end_ns_event_obj;
2296 2297
} TreeBuilderObject;

2298
#define TreeBuilder_CheckExact(op) (Py_TYPE(op) == &TreeBuilder_Type)
2299 2300 2301 2302

/* -------------------------------------------------------------------- */
/* constructor and destructor */

2303 2304
static PyObject *
treebuilder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2305
{
2306 2307 2308
    TreeBuilderObject *t = (TreeBuilderObject *)type->tp_alloc(type, 0);
    if (t != NULL) {
        t->root = NULL;
2309

2310
        Py_INCREF(Py_None);
2311
        t->this = Py_None;
2312
        Py_INCREF(Py_None);
2313
        t->last = Py_None;
2314

2315
        t->data = NULL;
2316
        t->element_factory = NULL;
2317 2318 2319 2320
        t->stack = PyList_New(20);
        if (!t->stack) {
            Py_DECREF(t->this);
            Py_DECREF(t->last);
2321
            Py_DECREF((PyObject *) t);
2322 2323 2324
            return NULL;
        }
        t->index = 0;
2325

2326 2327 2328 2329 2330
        t->events = NULL;
        t->start_event_obj = t->end_event_obj = NULL;
        t->start_ns_event_obj = t->end_ns_event_obj = NULL;
    }
    return (PyObject *)t;
2331 2332
}

2333 2334
static int
treebuilder_init(PyObject *self, PyObject *args, PyObject *kwds)
2335
{
2336
    static char *kwlist[] = {"element_factory", 0};
2337 2338
    PyObject *element_factory = NULL;
    TreeBuilderObject *self_tb = (TreeBuilderObject *)self;
2339
    PyObject *tmp;
2340 2341 2342 2343 2344 2345 2346 2347

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:TreeBuilder", kwlist,
                                     &element_factory)) {
        return -1;
    }

    if (element_factory) {
        Py_INCREF(element_factory);
2348
        tmp = self_tb->element_factory;
2349
        self_tb->element_factory = element_factory;
2350
        Py_XDECREF(tmp);
2351 2352
    }

2353
    return 0;
2354 2355
}

2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
static int
treebuilder_gc_traverse(TreeBuilderObject *self, visitproc visit, void *arg)
{
    Py_VISIT(self->root);
    Py_VISIT(self->this);
    Py_VISIT(self->last);
    Py_VISIT(self->data);
    Py_VISIT(self->stack);
    Py_VISIT(self->element_factory);
    return 0;
}

static int
treebuilder_gc_clear(TreeBuilderObject *self)
2370
{
2371 2372 2373 2374 2375 2376 2377 2378 2379
    Py_CLEAR(self->end_ns_event_obj);
    Py_CLEAR(self->start_ns_event_obj);
    Py_CLEAR(self->end_event_obj);
    Py_CLEAR(self->start_event_obj);
    Py_CLEAR(self->events);
    Py_CLEAR(self->stack);
    Py_CLEAR(self->data);
    Py_CLEAR(self->last);
    Py_CLEAR(self->this);
2380
    Py_CLEAR(self->element_factory);
2381
    Py_CLEAR(self->root);
2382 2383
    return 0;
}
2384

2385 2386 2387 2388 2389
static void
treebuilder_dealloc(TreeBuilderObject *self)
{
    PyObject_GC_UnTrack(self);
    treebuilder_gc_clear(self);
2390
    Py_TYPE(self)->tp_free((PyObject *)self);
2391 2392
}

2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
/* -------------------------------------------------------------------- */
/* helpers for handling of arbitrary element-like objects */

static int
treebuilder_set_element_text_or_tail(PyObject *element, PyObject *data,
                                     PyObject **dest, _Py_Identifier *name)
{
    if (Element_CheckExact(element)) {
        Py_DECREF(JOIN_OBJ(*dest));
        *dest = JOIN_SET(data, PyList_CheckExact(data));
        return 0;
    }
    else {
        PyObject *joined = list_join(data);
        int r;
        if (joined == NULL)
            return -1;
        r = _PyObject_SetAttrId(element, name, joined);
        Py_DECREF(joined);
        return r;
    }
}

/* These two functions steal a reference to data */
static int
treebuilder_set_element_text(PyObject *element, PyObject *data)
{
    _Py_IDENTIFIER(text);
    return treebuilder_set_element_text_or_tail(
        element, data, &((ElementObject *) element)->text, &PyId_text);
}

static int
treebuilder_set_element_tail(PyObject *element, PyObject *data)
{
    _Py_IDENTIFIER(tail);
    return treebuilder_set_element_text_or_tail(
        element, data, &((ElementObject *) element)->tail, &PyId_tail);
}

static int
treebuilder_add_subelement(PyObject *element, PyObject *child)
{
    _Py_IDENTIFIER(append);
    if (Element_CheckExact(element)) {
        ElementObject *elem = (ElementObject *) element;
        return element_add_subelement(elem, child);
    }
    else {
        PyObject *res;
        res = _PyObject_CallMethodId(element, &PyId_append, "O", child);
        if (res == NULL)
            return -1;
        Py_DECREF(res);
        return 0;
    }
}

2451 2452 2453 2454 2455 2456 2457 2458 2459
/* -------------------------------------------------------------------- */
/* handlers */

LOCAL(PyObject*)
treebuilder_handle_start(TreeBuilderObject* self, PyObject* tag,
                         PyObject* attrib)
{
    PyObject* node;
    PyObject* this;
2460
    elementtreestate *st = ET_STATE_GLOBAL;
2461 2462 2463

    if (self->data) {
        if (self->this == self->last) {
2464 2465 2466 2467 2468 2469
            if (treebuilder_set_element_text(self->last, self->data))
                return NULL;
        }
        else {
            if (treebuilder_set_element_tail(self->last, self->data))
                return NULL;
2470 2471 2472 2473
        }
        self->data = NULL;
    }

2474
    if (self->element_factory && self->element_factory != Py_None) {
2475 2476 2477 2478 2479
        node = PyObject_CallFunction(self->element_factory, "OO", tag, attrib);
    } else {
        node = create_new_element(tag, attrib);
    }
    if (!node) {
2480
        return NULL;
2481
    }
2482

2483
    this = self->this;
2484 2485

    if (this != Py_None) {
2486
        if (treebuilder_add_subelement(this, node) < 0)
2487
            goto error;
2488 2489 2490
    } else {
        if (self->root) {
            PyErr_SetString(
2491
                st->parseerror_obj,
2492 2493
                "multiple elements on top level"
                );
2494
            goto error;
2495 2496 2497 2498 2499 2500 2501
        }
        Py_INCREF(node);
        self->root = node;
    }

    if (self->index < PyList_GET_SIZE(self->stack)) {
        if (PyList_SetItem(self->stack, self->index, this) < 0)
2502
            goto error;
2503 2504 2505
        Py_INCREF(this);
    } else {
        if (PyList_Append(self->stack, this) < 0)
2506
            goto error;
2507 2508 2509 2510 2511
    }
    self->index++;

    Py_DECREF(this);
    Py_INCREF(node);
2512
    self->this = node;
2513 2514 2515

    Py_DECREF(self->last);
    Py_INCREF(node);
2516
    self->last = node;
2517 2518 2519 2520

    if (self->start_event_obj) {
        PyObject* res;
        PyObject* action = self->start_event_obj;
2521
        res = PyTuple_Pack(2, action, node);
2522 2523 2524 2525 2526 2527 2528 2529
        if (res) {
            PyList_Append(self->events, res);
            Py_DECREF(res);
        } else
            PyErr_Clear(); /* FIXME: propagate error */
    }

    return node;
2530 2531 2532 2533

  error:
    Py_DECREF(node);
    return NULL;
2534 2535 2536 2537 2538 2539
}

LOCAL(PyObject*)
treebuilder_handle_data(TreeBuilderObject* self, PyObject* data)
{
    if (!self->data) {
2540
        if (self->last == Py_None) {
2541 2542 2543
            /* ignore calls to data before the first call to start */
            Py_RETURN_NONE;
        }
2544 2545 2546 2547
        /* store the first item as is */
        Py_INCREF(data); self->data = data;
    } else {
        /* more than one item; use a list to collect items */
2548 2549
        if (PyBytes_CheckExact(self->data) && Py_REFCNT(self->data) == 1 &&
            PyBytes_CheckExact(data) && PyBytes_GET_SIZE(data) == 1) {
2550
            /* XXX this code path unused in Python 3? */
2551 2552
            /* expat often generates single character data sections; handle
               the most common case by resizing the existing string... */
2553 2554
            Py_ssize_t size = PyBytes_GET_SIZE(self->data);
            if (_PyBytes_Resize(&self->data, size + 1) < 0)
2555
                return NULL;
2556
            PyBytes_AS_STRING(self->data)[size] = PyBytes_AS_STRING(data)[0];
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579
        } else if (PyList_CheckExact(self->data)) {
            if (PyList_Append(self->data, data) < 0)
                return NULL;
        } else {
            PyObject* list = PyList_New(2);
            if (!list)
                return NULL;
            PyList_SET_ITEM(list, 0, self->data);
            Py_INCREF(data); PyList_SET_ITEM(list, 1, data);
            self->data = list;
        }
    }

    Py_RETURN_NONE;
}

LOCAL(PyObject*)
treebuilder_handle_end(TreeBuilderObject* self, PyObject* tag)
{
    PyObject* item;

    if (self->data) {
        if (self->this == self->last) {
2580 2581
            if (treebuilder_set_element_text(self->last, self->data))
                return NULL;
2582
        } else {
2583 2584
            if (treebuilder_set_element_tail(self->last, self->data))
                return NULL;
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603
        }
        self->data = NULL;
    }

    if (self->index == 0) {
        PyErr_SetString(
            PyExc_IndexError,
            "pop from empty stack"
            );
        return NULL;
    }

    self->index--;

    item = PyList_GET_ITEM(self->stack, self->index);
    Py_INCREF(item);

    Py_DECREF(self->last);

2604 2605
    self->last = self->this;
    self->this = item;
2606 2607 2608 2609 2610

    if (self->end_event_obj) {
        PyObject* res;
        PyObject* action = self->end_event_obj;
        PyObject* node = (PyObject*) self->last;
2611
        res = PyTuple_Pack(2, action, node);
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
        if (res) {
            PyList_Append(self->events, res);
            Py_DECREF(res);
        } else
            PyErr_Clear(); /* FIXME: propagate error */
    }

    Py_INCREF(self->last);
    return (PyObject*) self->last;
}

LOCAL(void)
treebuilder_handle_namespace(TreeBuilderObject* self, int start,
2625
                             PyObject *prefix, PyObject *uri)
2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637
{
    PyObject* res;
    PyObject* action;
    PyObject* parcel;

    if (!self->events)
        return;

    if (start) {
        if (!self->start_ns_event_obj)
            return;
        action = self->start_ns_event_obj;
2638
        parcel = Py_BuildValue("OO", prefix, uri);
2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657
        if (!parcel)
            return;
        Py_INCREF(action);
    } else {
        if (!self->end_ns_event_obj)
            return;
        action = self->end_ns_event_obj;
        Py_INCREF(action);
        parcel = Py_None;
        Py_INCREF(parcel);
    }

    res = PyTuple_New(2);

    if (res) {
        PyTuple_SET_ITEM(res, 0, action);
        PyTuple_SET_ITEM(res, 1, parcel);
        PyList_Append(self->events, res);
        Py_DECREF(res);
2658 2659 2660 2661
    }
    else {
        Py_DECREF(action);
        Py_DECREF(parcel);
2662
        PyErr_Clear(); /* FIXME: propagate error */
2663
    }
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
}

/* -------------------------------------------------------------------- */
/* methods (in alphabetical order) */

static PyObject*
treebuilder_data(TreeBuilderObject* self, PyObject* args)
{
    PyObject* data;
    if (!PyArg_ParseTuple(args, "O:data", &data))
        return NULL;

    return treebuilder_handle_data(self, data);
}

static PyObject*
treebuilder_end(TreeBuilderObject* self, PyObject* args)
{
    PyObject* tag;
    if (!PyArg_ParseTuple(args, "O:end", &tag))
        return NULL;

    return treebuilder_handle_end(self, tag);
}

LOCAL(PyObject*)
treebuilder_done(TreeBuilderObject* self)
{
    PyObject* res;

    /* FIXME: check stack size? */

    if (self->root)
        res = self->root;
    else
        res = Py_None;

    Py_INCREF(res);
    return res;
}

static PyObject*
treebuilder_close(TreeBuilderObject* self, PyObject* args)
{
    if (!PyArg_ParseTuple(args, ":close"))
        return NULL;

    return treebuilder_done(self);
}

static PyObject*
treebuilder_start(TreeBuilderObject* self, PyObject* args)
{
    PyObject* tag;
    PyObject* attrib = Py_None;
    if (!PyArg_ParseTuple(args, "O|O:start", &tag, &attrib))
        return NULL;

    return treebuilder_handle_start(self, tag, attrib);
}

static PyMethodDef treebuilder_methods[] = {
    {"data", (PyCFunction) treebuilder_data, METH_VARARGS},
    {"start", (PyCFunction) treebuilder_start, METH_VARARGS},
    {"end", (PyCFunction) treebuilder_end, METH_VARARGS},
    {"close", (PyCFunction) treebuilder_close, METH_VARARGS},
    {NULL, NULL}
};

2733
static PyTypeObject TreeBuilder_Type = {
2734
    PyVarObject_HEAD_INIT(NULL, 0)
2735
    "xml.etree.ElementTree.TreeBuilder", sizeof(TreeBuilderObject), 0,
2736
    /* methods */
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751
    (destructor)treebuilder_dealloc,                /* tp_dealloc */
    0,                                              /* tp_print */
    0,                                              /* tp_getattr */
    0,                                              /* tp_setattr */
    0,                                              /* tp_reserved */
    0,                                              /* tp_repr */
    0,                                              /* tp_as_number */
    0,                                              /* tp_as_sequence */
    0,                                              /* tp_as_mapping */
    0,                                              /* tp_hash */
    0,                                              /* tp_call */
    0,                                              /* tp_str */
    0,                                              /* tp_getattro */
    0,                                              /* tp_setattro */
    0,                                              /* tp_as_buffer */
2752 2753
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
                                                    /* tp_flags */
2754
    0,                                              /* tp_doc */
2755 2756
    (traverseproc)treebuilder_gc_traverse,          /* tp_traverse */
    (inquiry)treebuilder_gc_clear,                  /* tp_clear */
2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772
    0,                                              /* tp_richcompare */
    0,                                              /* tp_weaklistoffset */
    0,                                              /* tp_iter */
    0,                                              /* tp_iternext */
    treebuilder_methods,                            /* tp_methods */
    0,                                              /* tp_members */
    0,                                              /* tp_getset */
    0,                                              /* tp_base */
    0,                                              /* tp_dict */
    0,                                              /* tp_descr_get */
    0,                                              /* tp_descr_set */
    0,                                              /* tp_dictoffset */
    (initproc)treebuilder_init,                     /* tp_init */
    PyType_GenericAlloc,                            /* tp_alloc */
    treebuilder_new,                                /* tp_new */
    0,                                              /* tp_free */
2773 2774 2775 2776 2777 2778 2779
};

/* ==================================================================== */
/* the expat interface */

#include "expat.h"
#include "pyexpat.h"
2780 2781 2782 2783

/* The PyExpat_CAPI structure is an immutable dispatch table, so it can be
 * cached globally without being in per-module state.
 */
2784
static struct PyExpat_CAPI *expat_capi;
2785 2786
#define EXPAT(func) (expat_capi->func)

2787 2788 2789
static XML_Memory_Handling_Suite ExpatMemoryHandler = {
    PyObject_Malloc, PyObject_Realloc, PyObject_Free};

2790 2791 2792 2793 2794
typedef struct {
    PyObject_HEAD

    XML_Parser parser;

2795 2796
    PyObject *target;
    PyObject *entity;
2797

2798
    PyObject *names;
2799

2800 2801 2802
    PyObject *handle_start;
    PyObject *handle_data;
    PyObject *handle_end;
2803

2804 2805 2806
    PyObject *handle_comment;
    PyObject *handle_pi;
    PyObject *handle_doctype;
2807

2808
    PyObject *handle_close;
2809

2810 2811
} XMLParserObject;

2812
static PyObject* xmlparser_doctype(XMLParserObject* self, PyObject* args);
2813

2814 2815 2816 2817 2818 2819 2820 2821
/* helpers */

LOCAL(PyObject*)
makeuniversal(XMLParserObject* self, const char* string)
{
    /* convert a UTF-8 tag/attribute name from the expat parser
       to a universal name string */

2822
    Py_ssize_t size = (Py_ssize_t) strlen(string);
2823 2824 2825 2826
    PyObject* key;
    PyObject* value;

    /* look the 'raw' name up in the names dictionary */
2827
    key = PyBytes_FromStringAndSize(string, size);
2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
    if (!key)
        return NULL;

    value = PyDict_GetItem(self->names, key);

    if (value) {
        Py_INCREF(value);
    } else {
        /* new name.  convert to universal name, and decode as
           necessary */

        PyObject* tag;
        char* p;
2841
        Py_ssize_t i;
2842 2843 2844 2845 2846 2847 2848

        /* look for namespace separator */
        for (i = 0; i < size; i++)
            if (string[i] == '}')
                break;
        if (i != size) {
            /* convert to universal name */
2849
            tag = PyBytes_FromStringAndSize(NULL, size+1);
2850 2851 2852 2853
            if (tag == NULL) {
                Py_DECREF(key);
                return NULL;
            }
2854
            p = PyBytes_AS_STRING(tag);
2855 2856 2857 2858 2859 2860 2861 2862
            p[0] = '{';
            memcpy(p+1, string, size);
            size++;
        } else {
            /* plain name; use key as tag */
            Py_INCREF(key);
            tag = key;
        }
2863

2864
        /* decode universal name */
2865
        p = PyBytes_AS_STRING(tag);
2866 2867 2868 2869 2870 2871
        value = PyUnicode_DecodeUTF8(p, size, "strict");
        Py_DECREF(tag);
        if (!value) {
            Py_DECREF(key);
            return NULL;
        }
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884

        /* add to names dictionary */
        if (PyDict_SetItem(self->names, key, value) < 0) {
            Py_DECREF(key);
            Py_DECREF(value);
            return NULL;
        }
    }

    Py_DECREF(key);
    return value;
}

2885 2886 2887 2888
/* Set the ParseError exception with the given parameters.
 * If message is not NULL, it's used as the error string. Otherwise, the
 * message string is the default for the given error_code.
*/
2889
static void
2890
expat_set_error(enum XML_Error error_code, int line, int column, char *message)
2891
{
2892
    PyObject *errmsg, *error, *position, *code;
2893
    elementtreestate *st = ET_STATE_GLOBAL;
2894

2895
    errmsg = PyUnicode_FromFormat("%s: line %d, column %d",
2896 2897
                message ? message : EXPAT(ErrorString)(error_code),
                line, column);
2898 2899
    if (errmsg == NULL)
        return;
2900

2901
    error = PyObject_CallFunction(st->parseerror_obj, "O", errmsg);
2902
    Py_DECREF(errmsg);
2903 2904 2905
    if (!error)
        return;

2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
    /* Add code and position attributes */
    code = PyLong_FromLong((long)error_code);
    if (!code) {
        Py_DECREF(error);
        return;
    }
    if (PyObject_SetAttrString(error, "code", code) == -1) {
        Py_DECREF(error);
        Py_DECREF(code);
        return;
    }
    Py_DECREF(code);

2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
    position = Py_BuildValue("(ii)", line, column);
    if (!position) {
        Py_DECREF(error);
        return;
    }
    if (PyObject_SetAttrString(error, "position", position) == -1) {
        Py_DECREF(error);
        Py_DECREF(position);
        return;
    }
    Py_DECREF(position);

2931
    PyErr_SetObject(st->parseerror_obj, error);
2932 2933 2934
    Py_DECREF(error);
}

2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
/* -------------------------------------------------------------------- */
/* handlers */

static void
expat_default_handler(XMLParserObject* self, const XML_Char* data_in,
                      int data_len)
{
    PyObject* key;
    PyObject* value;
    PyObject* res;

    if (data_len < 2 || data_in[0] != '&')
        return;

2949 2950 2951
    if (PyErr_Occurred())
        return;

2952
    key = PyUnicode_DecodeUTF8(data_in + 1, data_len - 2, "strict");
2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967
    if (!key)
        return;

    value = PyDict_GetItem(self->entity, key);

    if (value) {
        if (TreeBuilder_CheckExact(self->target))
            res = treebuilder_handle_data(
                (TreeBuilderObject*) self->target, value
                );
        else if (self->handle_data)
            res = PyObject_CallFunction(self->handle_data, "O", value);
        else
            res = NULL;
        Py_XDECREF(res);
2968 2969
    } else if (!PyErr_Occurred()) {
        /* Report the first error, not the last */
2970 2971
        char message[128] = "undefined entity ";
        strncat(message, data_in, data_len < 100?data_len:100);
2972
        expat_set_error(
2973
            XML_ERROR_UNDEFINED_ENTITY,
2974
            EXPAT(GetErrorLineNumber)(self->parser),
2975 2976
            EXPAT(GetErrorColumnNumber)(self->parser),
            message
2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
            );
    }

    Py_DECREF(key);
}

static void
expat_start_handler(XMLParserObject* self, const XML_Char* tag_in,
                    const XML_Char **attrib_in)
{
    PyObject* res;
    PyObject* tag;
    PyObject* attrib;
    int ok;

2992 2993 2994
    if (PyErr_Occurred())
        return;

2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
    /* tag name */
    tag = makeuniversal(self, tag_in);
    if (!tag)
        return; /* parser will look for errors */

    /* attributes */
    if (attrib_in[0]) {
        attrib = PyDict_New();
        if (!attrib)
            return;
        while (attrib_in[0] && attrib_in[1]) {
            PyObject* key = makeuniversal(self, attrib_in[0]);
3007
            PyObject* value = PyUnicode_DecodeUTF8(attrib_in[1], strlen(attrib_in[1]), "strict");
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023
            if (!key || !value) {
                Py_XDECREF(value);
                Py_XDECREF(key);
                Py_DECREF(attrib);
                return;
            }
            ok = PyDict_SetItem(attrib, key, value);
            Py_DECREF(value);
            Py_DECREF(key);
            if (ok < 0) {
                Py_DECREF(attrib);
                return;
            }
            attrib_in += 2;
        }
    } else {
3024
        /* Pass an empty dictionary on */
3025 3026 3027 3028 3029 3030
        attrib = PyDict_New();
        if (!attrib)
            return;
    }

    if (TreeBuilder_CheckExact(self->target)) {
3031 3032 3033
        /* shortcut */
        res = treebuilder_handle_start((TreeBuilderObject*) self->target,
                                       tag, attrib);
3034
    }
3035
    else if (self->handle_start) {
3036
        res = PyObject_CallFunction(self->handle_start, "OO", tag, attrib);
3037
    } else
3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052
        res = NULL;

    Py_DECREF(tag);
    Py_DECREF(attrib);

    Py_XDECREF(res);
}

static void
expat_data_handler(XMLParserObject* self, const XML_Char* data_in,
                   int data_len)
{
    PyObject* data;
    PyObject* res;

3053 3054 3055
    if (PyErr_Occurred())
        return;

3056
    data = PyUnicode_DecodeUTF8(data_in, data_len, "strict");
3057 3058
    if (!data)
        return; /* parser will look for errors */
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078

    if (TreeBuilder_CheckExact(self->target))
        /* shortcut */
        res = treebuilder_handle_data((TreeBuilderObject*) self->target, data);
    else if (self->handle_data)
        res = PyObject_CallFunction(self->handle_data, "O", data);
    else
        res = NULL;

    Py_DECREF(data);

    Py_XDECREF(res);
}

static void
expat_end_handler(XMLParserObject* self, const XML_Char* tag_in)
{
    PyObject* tag;
    PyObject* res = NULL;

3079 3080 3081
    if (PyErr_Occurred())
        return;

3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102
    if (TreeBuilder_CheckExact(self->target))
        /* shortcut */
        /* the standard tree builder doesn't look at the end tag */
        res = treebuilder_handle_end(
            (TreeBuilderObject*) self->target, Py_None
            );
    else if (self->handle_end) {
        tag = makeuniversal(self, tag_in);
        if (tag) {
            res = PyObject_CallFunction(self->handle_end, "O", tag);
            Py_DECREF(tag);
        }
    }

    Py_XDECREF(res);
}

static void
expat_start_ns_handler(XMLParserObject* self, const XML_Char* prefix,
                       const XML_Char *uri)
{
3103 3104 3105
    PyObject* sprefix = NULL;
    PyObject* suri = NULL;

3106 3107 3108
    if (PyErr_Occurred())
        return;

3109
    if (uri)
3110
        suri = PyUnicode_DecodeUTF8(uri, strlen(uri), "strict");
3111
    else
3112
        suri = PyUnicode_FromString("");
3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124
    if (!suri)
        return;

    if (prefix)
        sprefix = PyUnicode_DecodeUTF8(prefix, strlen(prefix), "strict");
    else
        sprefix = PyUnicode_FromString("");
    if (!sprefix) {
        Py_DECREF(suri);
        return;
    }

3125
    treebuilder_handle_namespace(
3126
        (TreeBuilderObject*) self->target, 1, sprefix, suri
3127
        );
3128 3129 3130

    Py_DECREF(sprefix);
    Py_DECREF(suri);
3131 3132 3133 3134 3135
}

static void
expat_end_ns_handler(XMLParserObject* self, const XML_Char* prefix_in)
{
3136 3137 3138
    if (PyErr_Occurred())
        return;

3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149
    treebuilder_handle_namespace(
        (TreeBuilderObject*) self->target, 0, NULL, NULL
        );
}

static void
expat_comment_handler(XMLParserObject* self, const XML_Char* comment_in)
{
    PyObject* comment;
    PyObject* res;

3150 3151 3152
    if (PyErr_Occurred())
        return;

3153
    if (self->handle_comment) {
3154
        comment = PyUnicode_DecodeUTF8(comment_in, strlen(comment_in), "strict");
3155 3156 3157 3158 3159 3160 3161 3162
        if (comment) {
            res = PyObject_CallFunction(self->handle_comment, "O", comment);
            Py_XDECREF(res);
            Py_DECREF(comment);
        }
    }
}

3163
static void
3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174
expat_start_doctype_handler(XMLParserObject *self,
                            const XML_Char *doctype_name,
                            const XML_Char *sysid,
                            const XML_Char *pubid,
                            int has_internal_subset)
{
    PyObject *self_pyobj = (PyObject *)self;
    PyObject *doctype_name_obj, *sysid_obj, *pubid_obj;
    PyObject *parser_doctype = NULL;
    PyObject *res = NULL;

3175 3176 3177
    if (PyErr_Occurred())
        return;

3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210
    doctype_name_obj = makeuniversal(self, doctype_name);
    if (!doctype_name_obj)
        return;

    if (sysid) {
        sysid_obj = makeuniversal(self, sysid);
        if (!sysid_obj) {
            Py_DECREF(doctype_name_obj);
            return;
        }
    } else {
        Py_INCREF(Py_None);
        sysid_obj = Py_None;
    }

    if (pubid) {
        pubid_obj = makeuniversal(self, pubid);
        if (!pubid_obj) {
            Py_DECREF(doctype_name_obj);
            Py_DECREF(sysid_obj);
            return;
        }
    } else {
        Py_INCREF(Py_None);
        pubid_obj = Py_None;
    }

    /* If the target has a handler for doctype, call it. */
    if (self->handle_doctype) {
        res = PyObject_CallFunction(self->handle_doctype, "OOO",
                                    doctype_name_obj, pubid_obj, sysid_obj);
        Py_CLEAR(res);
    }
3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223
    else {
        /* Now see if the parser itself has a doctype method. If yes and it's
         * a custom method, call it but warn about deprecation. If it's only
         * the vanilla XMLParser method, do nothing.
         */
        parser_doctype = PyObject_GetAttrString(self_pyobj, "doctype");
        if (parser_doctype &&
            !(PyCFunction_Check(parser_doctype) &&
              PyCFunction_GET_SELF(parser_doctype) == self_pyobj &&
              PyCFunction_GET_FUNCTION(parser_doctype) ==
                    (PyCFunction) xmlparser_doctype)) {
            res = xmlparser_doctype(self, NULL);
            if (!res)
3224
                goto clear;
3225
            Py_DECREF(res);
3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238
            res = PyObject_CallFunction(parser_doctype, "OOO",
                                        doctype_name_obj, pubid_obj, sysid_obj);
            Py_CLEAR(res);
        }
    }

clear:
    Py_XDECREF(parser_doctype);
    Py_DECREF(doctype_name_obj);
    Py_DECREF(pubid_obj);
    Py_DECREF(sysid_obj);
}

3239 3240 3241 3242 3243 3244 3245 3246
static void
expat_pi_handler(XMLParserObject* self, const XML_Char* target_in,
                 const XML_Char* data_in)
{
    PyObject* target;
    PyObject* data;
    PyObject* res;

3247 3248 3249
    if (PyErr_Occurred())
        return;

3250
    if (self->handle_pi) {
3251 3252
        target = PyUnicode_DecodeUTF8(target_in, strlen(target_in), "strict");
        data = PyUnicode_DecodeUTF8(data_in, strlen(data_in), "strict");
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266
        if (target && data) {
            res = PyObject_CallFunction(self->handle_pi, "OO", target, data);
            Py_XDECREF(res);
            Py_DECREF(data);
            Py_DECREF(target);
        } else {
            Py_XDECREF(data);
            Py_XDECREF(target);
        }
    }
}

/* -------------------------------------------------------------------- */

3267 3268
static PyObject *
xmlparser_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3269
{
3270 3271 3272 3273 3274 3275
    XMLParserObject *self = (XMLParserObject *)type->tp_alloc(type, 0);
    if (self) {
        self->parser = NULL;
        self->target = self->entity = self->names = NULL;
        self->handle_start = self->handle_data = self->handle_end = NULL;
        self->handle_comment = self->handle_pi = self->handle_close = NULL;
3276
        self->handle_doctype = NULL;
3277
    }
3278 3279
    return (PyObject *)self;
}
3280

3281 3282 3283 3284 3285 3286
static int
xmlparser_init(PyObject *self, PyObject *args, PyObject *kwds)
{
    XMLParserObject *self_xp = (XMLParserObject *)self;
    PyObject *target = NULL, *html = NULL;
    char *encoding = NULL;
3287
    static char *kwlist[] = {"html", "target", "encoding", 0};
3288

3289 3290 3291
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOz:XMLParser", kwlist,
                                     &html, &target, &encoding)) {
        return -1;
3292
    }
3293

3294 3295 3296
    self_xp->entity = PyDict_New();
    if (!self_xp->entity)
        return -1;
3297

3298 3299
    self_xp->names = PyDict_New();
    if (!self_xp->names) {
3300
        Py_CLEAR(self_xp->entity);
3301 3302
        return -1;
    }
3303

3304 3305
    self_xp->parser = EXPAT(ParserCreate_MM)(encoding, &ExpatMemoryHandler, "}");
    if (!self_xp->parser) {
3306 3307
        Py_CLEAR(self_xp->entity);
        Py_CLEAR(self_xp->names);
3308
        PyErr_NoMemory();
3309
        return -1;
3310 3311
    }

3312 3313 3314
    if (target) {
        Py_INCREF(target);
    } else {
3315
        target = treebuilder_new(&TreeBuilder_Type, NULL, NULL);
3316
        if (!target) {
3317 3318
            Py_CLEAR(self_xp->entity);
            Py_CLEAR(self_xp->names);
3319 3320
            EXPAT(ParserFree)(self_xp->parser);
            return -1;
3321
        }
3322 3323
    }
    self_xp->target = target;
3324

3325 3326 3327 3328 3329 3330
    self_xp->handle_start = PyObject_GetAttrString(target, "start");
    self_xp->handle_data = PyObject_GetAttrString(target, "data");
    self_xp->handle_end = PyObject_GetAttrString(target, "end");
    self_xp->handle_comment = PyObject_GetAttrString(target, "comment");
    self_xp->handle_pi = PyObject_GetAttrString(target, "pi");
    self_xp->handle_close = PyObject_GetAttrString(target, "close");
3331
    self_xp->handle_doctype = PyObject_GetAttrString(target, "doctype");
3332 3333

    PyErr_Clear();
3334

3335
    /* configure parser */
3336
    EXPAT(SetUserData)(self_xp->parser, self_xp);
3337
    EXPAT(SetElementHandler)(
3338
        self_xp->parser,
3339 3340 3341 3342
        (XML_StartElementHandler) expat_start_handler,
        (XML_EndElementHandler) expat_end_handler
        );
    EXPAT(SetDefaultHandlerExpand)(
3343
        self_xp->parser,
3344 3345 3346
        (XML_DefaultHandler) expat_default_handler
        );
    EXPAT(SetCharacterDataHandler)(
3347
        self_xp->parser,
3348 3349
        (XML_CharacterDataHandler) expat_data_handler
        );
3350
    if (self_xp->handle_comment)
3351
        EXPAT(SetCommentHandler)(
3352
            self_xp->parser,
3353 3354
            (XML_CommentHandler) expat_comment_handler
            );
3355
    if (self_xp->handle_pi)
3356
        EXPAT(SetProcessingInstructionHandler)(
3357
            self_xp->parser,
3358 3359
            (XML_ProcessingInstructionHandler) expat_pi_handler
            );
3360 3361 3362 3363
    EXPAT(SetStartDoctypeDeclHandler)(
        self_xp->parser,
        (XML_StartDoctypeDeclHandler) expat_start_doctype_handler
        );
3364
    EXPAT(SetUnknownEncodingHandler)(
3365
        self_xp->parser,
3366
        EXPAT(DefaultUnknownEncodingHandler), NULL
3367 3368
        );

3369 3370
    return 0;
}
3371

3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386
static int
xmlparser_gc_traverse(XMLParserObject *self, visitproc visit, void *arg)
{
    Py_VISIT(self->handle_close);
    Py_VISIT(self->handle_pi);
    Py_VISIT(self->handle_comment);
    Py_VISIT(self->handle_end);
    Py_VISIT(self->handle_data);
    Py_VISIT(self->handle_start);

    Py_VISIT(self->target);
    Py_VISIT(self->entity);
    Py_VISIT(self->names);

    return 0;
3387 3388
}

3389 3390
static int
xmlparser_gc_clear(XMLParserObject *self)
3391 3392 3393
{
    EXPAT(ParserFree)(self->parser);

3394 3395 3396 3397 3398 3399 3400
    Py_CLEAR(self->handle_close);
    Py_CLEAR(self->handle_pi);
    Py_CLEAR(self->handle_comment);
    Py_CLEAR(self->handle_end);
    Py_CLEAR(self->handle_data);
    Py_CLEAR(self->handle_start);
    Py_CLEAR(self->handle_doctype);
3401

3402 3403 3404
    Py_CLEAR(self->target);
    Py_CLEAR(self->entity);
    Py_CLEAR(self->names);
3405

3406
    return 0;
3407 3408
}

3409 3410 3411 3412 3413 3414 3415
static void
xmlparser_dealloc(XMLParserObject* self)
{
    PyObject_GC_UnTrack(self);
    xmlparser_gc_clear(self);
    Py_TYPE(self)->tp_free((PyObject *)self);
}
3416 3417

LOCAL(PyObject*)
3418
expat_parse(XMLParserObject* self, const char* data, int data_len, int final)
3419 3420 3421
{
    int ok;

3422
    assert(!PyErr_Occurred());
3423 3424 3425 3426 3427 3428
    ok = EXPAT(Parse)(self->parser, data, data_len, final);

    if (PyErr_Occurred())
        return NULL;

    if (!ok) {
3429
        expat_set_error(
3430
            EXPAT(GetErrorCode)(self->parser),
3431
            EXPAT(GetErrorLineNumber)(self->parser),
3432 3433
            EXPAT(GetErrorColumnNumber)(self->parser),
            NULL
3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450
            );
        return NULL;
    }

    Py_RETURN_NONE;
}

static PyObject*
xmlparser_close(XMLParserObject* self, PyObject* args)
{
    /* end feeding data to parser */

    PyObject* res;
    if (!PyArg_ParseTuple(args, ":close"))
        return NULL;

    res = expat_parse(self, "", 0, 1);
3451 3452
    if (!res)
        return NULL;
3453

3454
    if (TreeBuilder_CheckExact(self->target)) {
3455 3456
        Py_DECREF(res);
        return treebuilder_done((TreeBuilderObject*) self->target);
3457 3458
    }
    else if (self->handle_close) {
3459 3460
        Py_DECREF(res);
        return PyObject_CallFunction(self->handle_close, "");
3461 3462
    }
    else {
3463
        return res;
3464
    }
3465 3466 3467
}

static PyObject*
3468
xmlparser_feed(XMLParserObject* self, PyObject* arg)
3469 3470 3471
{
    /* feed data to parser */

3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498
    if (PyUnicode_Check(arg)) {
        Py_ssize_t data_len;
        const char *data = PyUnicode_AsUTF8AndSize(arg, &data_len);
        if (data == NULL)
            return NULL;
        if (data_len > INT_MAX) {
            PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
            return NULL;
        }
        /* Explicitly set UTF-8 encoding. Return code ignored. */
        (void)EXPAT(SetEncoding)(self->parser, "utf-8");
        return expat_parse(self, data, (int)data_len, 0);
    }
    else {
        Py_buffer view;
        PyObject *res;
        if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) < 0)
            return NULL;
        if (view.len > INT_MAX) {
            PyBuffer_Release(&view);
            PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
            return NULL;
        }
        res = expat_parse(self, view.buf, (int)view.len, 0);
        PyBuffer_Release(&view);
        return res;
    }
3499 3500 3501
}

static PyObject*
3502
xmlparser_parse_whole(XMLParserObject* self, PyObject* args)
3503
{
3504
    /* (internal) parse the whole input, until end of stream */
3505 3506
    PyObject* reader;
    PyObject* buffer;
3507
    PyObject* temp;
3508 3509 3510 3511 3512 3513 3514 3515 3516
    PyObject* res;

    PyObject* fileobj;
    if (!PyArg_ParseTuple(args, "O:_parse", &fileobj))
        return NULL;

    reader = PyObject_GetAttrString(fileobj, "read");
    if (!reader)
        return NULL;
3517

3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528
    /* read from open file object */
    for (;;) {

        buffer = PyObject_CallFunction(reader, "i", 64*1024);

        if (!buffer) {
            /* read failed (e.g. due to KeyboardInterrupt) */
            Py_DECREF(reader);
            return NULL;
        }

3529 3530
        if (PyUnicode_CheckExact(buffer)) {
            /* A unicode object is encoded into bytes using UTF-8 */
3531
            if (PyUnicode_GET_LENGTH(buffer) == 0) {
3532 3533 3534 3535
                Py_DECREF(buffer);
                break;
            }
            temp = PyUnicode_AsEncodedString(buffer, "utf-8", "surrogatepass");
3536
            Py_DECREF(buffer);
3537 3538 3539 3540 3541 3542 3543 3544
            if (!temp) {
                /* Propagate exception from PyUnicode_AsEncodedString */
                Py_DECREF(reader);
                return NULL;
            }
            buffer = temp;
        }
        else if (!PyBytes_CheckExact(buffer) || PyBytes_GET_SIZE(buffer) == 0) {
3545 3546 3547 3548
            Py_DECREF(buffer);
            break;
        }

3549 3550 3551 3552 3553 3554
        if (PyBytes_GET_SIZE(buffer) > INT_MAX) {
            Py_DECREF(buffer);
            Py_DECREF(reader);
            PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
            return NULL;
        }
3555
        res = expat_parse(
3556
            self, PyBytes_AS_STRING(buffer), (int)PyBytes_GET_SIZE(buffer), 0
3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581
            );

        Py_DECREF(buffer);

        if (!res) {
            Py_DECREF(reader);
            return NULL;
        }
        Py_DECREF(res);

    }

    Py_DECREF(reader);

    res = expat_parse(self, "", 0, 1);

    if (res && TreeBuilder_CheckExact(self->target)) {
        Py_DECREF(res);
        return treebuilder_done((TreeBuilderObject*) self->target);
    }

    return res;
}

static PyObject*
3582 3583
xmlparser_doctype(XMLParserObject *self, PyObject *args)
{
3584 3585 3586 3587 3588 3589
    if (PyErr_WarnEx(PyExc_DeprecationWarning,
                     "This method of XMLParser is deprecated.  Define"
                     " doctype() method on the TreeBuilder target.",
                     1) < 0) {
        return NULL;
    }
3590 3591 3592 3593 3594
    Py_RETURN_NONE;
}

static PyObject*
xmlparser_setevents(XMLParserObject *self, PyObject* args)
3595 3596
{
    /* activate element event reporting */
3597 3598
    Py_ssize_t i, seqlen;
    TreeBuilderObject *target;
3599

3600 3601 3602 3603 3604
    PyObject *events_queue;
    PyObject *events_to_report = Py_None;
    PyObject *events_seq;
    if (!PyArg_ParseTuple(args, "O!|O:_setevents",  &PyList_Type, &events_queue,
                          &events_to_report))
3605 3606 3607 3608 3609
        return NULL;

    if (!TreeBuilder_CheckExact(self->target)) {
        PyErr_SetString(
            PyExc_TypeError,
3610
            "event handling only supported for ElementTree.TreeBuilder "
3611 3612 3613 3614 3615 3616 3617
            "targets"
            );
        return NULL;
    }

    target = (TreeBuilderObject*) self->target;

3618
    Py_INCREF(events_queue);
3619
    Py_XDECREF(target->events);
3620
    target->events = events_queue;
3621 3622

    /* clear out existing events */
3623 3624 3625 3626
    Py_CLEAR(target->start_event_obj);
    Py_CLEAR(target->end_event_obj);
    Py_CLEAR(target->start_ns_event_obj);
    Py_CLEAR(target->end_ns_event_obj);
3627

3628
    if (events_to_report == Py_None) {
3629
        /* default is "end" only */
3630
        target->end_event_obj = PyUnicode_FromString("end");
3631 3632 3633
        Py_RETURN_NONE;
    }

3634 3635 3636 3637
    if (!(events_seq = PySequence_Fast(events_to_report,
                                       "events must be a sequence"))) {
        return NULL;
    }
3638

3639 3640 3641 3642 3643 3644 3645 3646
    seqlen = PySequence_Size(events_seq);
    for (i = 0; i < seqlen; ++i) {
        PyObject *event_name_obj = PySequence_Fast_GET_ITEM(events_seq, i);
        char *event_name = NULL;
        if (PyUnicode_Check(event_name_obj)) {
            event_name = _PyUnicode_AsString(event_name_obj);
        } else if (PyBytes_Check(event_name_obj)) {
            event_name = PyBytes_AS_STRING(event_name_obj);
3647
        }
3648 3649 3650 3651 3652 3653 3654 3655 3656 3657

        if (event_name == NULL) {
            Py_DECREF(events_seq);
            PyErr_Format(PyExc_ValueError, "invalid events sequence");
            return NULL;
        } else if (strcmp(event_name, "start") == 0) {
            Py_INCREF(event_name_obj);
            target->start_event_obj = event_name_obj;
        } else if (strcmp(event_name, "end") == 0) {
            Py_INCREF(event_name_obj);
3658
            Py_XDECREF(target->end_event_obj);
3659 3660 3661
            target->end_event_obj = event_name_obj;
        } else if (strcmp(event_name, "start-ns") == 0) {
            Py_INCREF(event_name_obj);
3662
            Py_XDECREF(target->start_ns_event_obj);
3663
            target->start_ns_event_obj = event_name_obj;
3664 3665 3666 3667 3668
            EXPAT(SetNamespaceDeclHandler)(
                self->parser,
                (XML_StartNamespaceDeclHandler) expat_start_ns_handler,
                (XML_EndNamespaceDeclHandler) expat_end_ns_handler
                );
3669 3670
        } else if (strcmp(event_name, "end-ns") == 0) {
            Py_INCREF(event_name_obj);
3671
            Py_XDECREF(target->end_ns_event_obj);
3672
            target->end_ns_event_obj = event_name_obj;
3673 3674 3675 3676 3677 3678
            EXPAT(SetNamespaceDeclHandler)(
                self->parser,
                (XML_StartNamespaceDeclHandler) expat_start_ns_handler,
                (XML_EndNamespaceDeclHandler) expat_end_ns_handler
                );
        } else {
3679 3680
            Py_DECREF(events_seq);
            PyErr_Format(PyExc_ValueError, "unknown event '%s'", event_name);
3681 3682 3683 3684
            return NULL;
        }
    }

3685
    Py_DECREF(events_seq);
3686 3687 3688 3689
    Py_RETURN_NONE;
}

static PyMethodDef xmlparser_methods[] = {
3690
    {"feed", (PyCFunction) xmlparser_feed, METH_O},
3691
    {"close", (PyCFunction) xmlparser_close, METH_VARARGS},
3692
    {"_parse_whole", (PyCFunction) xmlparser_parse_whole, METH_VARARGS},
3693
    {"_setevents", (PyCFunction) xmlparser_setevents, METH_VARARGS},
3694
    {"doctype", (PyCFunction) xmlparser_doctype, METH_VARARGS},
3695 3696 3697
    {NULL, NULL}
};

3698
static PyObject*
3699
xmlparser_getattro(XMLParserObject* self, PyObject* nameobj)
3700
{
3701 3702 3703 3704 3705 3706 3707 3708 3709
    if (PyUnicode_Check(nameobj)) {
        PyObject* res;
        if (PyUnicode_CompareWithASCIIString(nameobj, "entity") == 0)
            res = self->entity;
        else if (PyUnicode_CompareWithASCIIString(nameobj, "target") == 0)
            res = self->target;
        else if (PyUnicode_CompareWithASCIIString(nameobj, "version") == 0) {
            return PyUnicode_FromFormat(
                "Expat %d.%d.%d", XML_MAJOR_VERSION,
3710
                XML_MINOR_VERSION, XML_MICRO_VERSION);
3711 3712 3713
        }
        else
            goto generic;
3714

3715 3716 3717 3718 3719
        Py_INCREF(res);
        return res;
    }
  generic:
    return PyObject_GenericGetAttr((PyObject*) self, nameobj);
3720 3721
}

3722
static PyTypeObject XMLParser_Type = {
3723
    PyVarObject_HEAD_INIT(NULL, 0)
3724
    "xml.etree.ElementTree.XMLParser", sizeof(XMLParserObject), 0,
3725
    /* methods */
3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761
    (destructor)xmlparser_dealloc,                  /* tp_dealloc */
    0,                                              /* tp_print */
    0,                                              /* tp_getattr */
    0,                                              /* tp_setattr */
    0,                                              /* tp_reserved */
    0,                                              /* tp_repr */
    0,                                              /* tp_as_number */
    0,                                              /* tp_as_sequence */
    0,                                              /* tp_as_mapping */
    0,                                              /* tp_hash */
    0,                                              /* tp_call */
    0,                                              /* tp_str */
    (getattrofunc)xmlparser_getattro,               /* tp_getattro */
    0,                                              /* tp_setattro */
    0,                                              /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
                                                    /* tp_flags */
    0,                                              /* tp_doc */
    (traverseproc)xmlparser_gc_traverse,            /* tp_traverse */
    (inquiry)xmlparser_gc_clear,                    /* tp_clear */
    0,                                              /* tp_richcompare */
    0,                                              /* tp_weaklistoffset */
    0,                                              /* tp_iter */
    0,                                              /* tp_iternext */
    xmlparser_methods,                              /* tp_methods */
    0,                                              /* tp_members */
    0,                                              /* tp_getset */
    0,                                              /* tp_base */
    0,                                              /* tp_dict */
    0,                                              /* tp_descr_get */
    0,                                              /* tp_descr_set */
    0,                                              /* tp_dictoffset */
    (initproc)xmlparser_init,                       /* tp_init */
    PyType_GenericAlloc,                            /* tp_alloc */
    xmlparser_new,                                  /* tp_new */
    0,                                              /* tp_free */
3762 3763 3764 3765 3766 3767
};

/* ==================================================================== */
/* python module interface */

static PyMethodDef _functions[] = {
3768
    {"SubElement", (PyCFunction) subelement, METH_VARARGS | METH_KEYWORDS},
3769 3770 3771
    {NULL, NULL}
};

3772

3773 3774 3775 3776 3777 3778 3779 3780 3781 3782
static struct PyModuleDef elementtreemodule = {
    PyModuleDef_HEAD_INIT,
    "_elementtree",
    NULL,
    sizeof(elementtreestate),
    _functions,
    NULL,
    elementtree_traverse,
    elementtree_clear,
    elementtree_free
3783 3784
};

Neal Norwitz's avatar
Neal Norwitz committed
3785
PyMODINIT_FUNC
3786
PyInit__elementtree(void)
3787
{
3788
    PyObject *m, *temp;
3789 3790 3791 3792 3793 3794 3795
    elementtreestate *st;

    m = PyState_FindModule(&elementtreemodule);
    if (m) {
        Py_INCREF(m);
        return m;
    }
3796

3797
    /* Initialize object types */
3798 3799
    if (PyType_Ready(&ElementIter_Type) < 0)
        return NULL;
3800
    if (PyType_Ready(&TreeBuilder_Type) < 0)
3801
        return NULL;
3802
    if (PyType_Ready(&Element_Type) < 0)
3803
        return NULL;
3804
    if (PyType_Ready(&XMLParser_Type) < 0)
3805
        return NULL;
3806

3807
    m = PyModule_Create(&elementtreemodule);
3808
    if (!m)
3809
        return NULL;
3810
    st = ET_STATE(m);
3811

3812 3813
    if (!(temp = PyImport_ImportModule("copy")))
        return NULL;
3814
    st->deepcopy_obj = PyObject_GetAttrString(temp, "deepcopy");
3815 3816
    Py_XDECREF(temp);

3817
    if (!(st->elementpath_obj = PyImport_ImportModule("xml.etree.ElementPath")))
3818 3819
        return NULL;

3820
    /* link against pyexpat */
3821 3822 3823 3824 3825 3826 3827
    expat_capi = PyCapsule_Import(PyExpat_CAPSULE_NAME, 0);
    if (expat_capi) {
        /* check that it's usable */
        if (strcmp(expat_capi->magic, PyExpat_CAPI_MAGIC) != 0 ||
            expat_capi->size < sizeof(struct PyExpat_CAPI) ||
            expat_capi->MAJOR_VERSION != XML_MAJOR_VERSION ||
            expat_capi->MINOR_VERSION != XML_MINOR_VERSION ||
3828
            expat_capi->MICRO_VERSION != XML_MICRO_VERSION) {
3829 3830 3831
            PyErr_SetString(PyExc_ImportError,
                            "pyexpat version is incompatible");
            return NULL;
3832
        }
3833
    } else {
3834
        return NULL;
3835
    }
3836

3837
    st->parseerror_obj = PyErr_NewException(
3838
        "xml.etree.ElementTree.ParseError", PyExc_SyntaxError, NULL
3839
        );
3840 3841
    Py_INCREF(st->parseerror_obj);
    PyModule_AddObject(m, "ParseError", st->parseerror_obj);
3842

3843 3844 3845
    Py_INCREF((PyObject *)&Element_Type);
    PyModule_AddObject(m, "Element", (PyObject *)&Element_Type);

3846 3847 3848
    Py_INCREF((PyObject *)&TreeBuilder_Type);
    PyModule_AddObject(m, "TreeBuilder", (PyObject *)&TreeBuilder_Type);

3849 3850 3851
    Py_INCREF((PyObject *)&XMLParser_Type);
    PyModule_AddObject(m, "XMLParser", (PyObject *)&XMLParser_Type);

3852
    return m;
3853
}