• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "Python.h"
2 #include "pycore_moduleobject.h"  // _PyModule_GetState()
3 #include "clinic/_operator.c.h"
4 
5 typedef struct {
6     PyObject *itemgetter_type;
7     PyObject *attrgetter_type;
8     PyObject *methodcaller_type;
9 } _operator_state;
10 
11 static inline _operator_state*
get_operator_state(PyObject * module)12 get_operator_state(PyObject *module)
13 {
14     void *state = _PyModule_GetState(module);
15     assert(state != NULL);
16     return (_operator_state *)state;
17 }
18 
19 /*[clinic input]
20 module _operator
21 [clinic start generated code]*/
22 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=672ecf48487521e7]*/
23 
24 PyDoc_STRVAR(operator_doc,
25 "Operator interface.\n\
26 \n\
27 This module exports a set of functions implemented in C corresponding\n\
28 to the intrinsic operators of Python.  For example, operator.add(x, y)\n\
29 is equivalent to the expression x+y.  The function names are those\n\
30 used for special methods; variants without leading and trailing\n\
31 '__' are also provided for convenience.");
32 
33 
34 /*[clinic input]
35 _operator.truth -> bool
36 
37     a: object
38     /
39 
40 Return True if a is true, False otherwise.
41 [clinic start generated code]*/
42 
43 static int
_operator_truth_impl(PyObject * module,PyObject * a)44 _operator_truth_impl(PyObject *module, PyObject *a)
45 /*[clinic end generated code: output=eaf87767234fa5d7 input=bc74a4cd90235875]*/
46 {
47     return PyObject_IsTrue(a);
48 }
49 
50 /*[clinic input]
51 _operator.add
52 
53     a: object
54     b: object
55     /
56 
57 Same as a + b.
58 [clinic start generated code]*/
59 
60 static PyObject *
_operator_add_impl(PyObject * module,PyObject * a,PyObject * b)61 _operator_add_impl(PyObject *module, PyObject *a, PyObject *b)
62 /*[clinic end generated code: output=8292984204f45164 input=5efe3bff856ac215]*/
63 {
64     return PyNumber_Add(a, b);
65 }
66 
67 /*[clinic input]
68 _operator.sub = _operator.add
69 
70 Same as a - b.
71 [clinic start generated code]*/
72 
73 static PyObject *
_operator_sub_impl(PyObject * module,PyObject * a,PyObject * b)74 _operator_sub_impl(PyObject *module, PyObject *a, PyObject *b)
75 /*[clinic end generated code: output=4adfc3b888c1ee2e input=6494c6b100b8e795]*/
76 {
77     return PyNumber_Subtract(a, b);
78 }
79 
80 /*[clinic input]
81 _operator.mul = _operator.add
82 
83 Same as a * b.
84 [clinic start generated code]*/
85 
86 static PyObject *
_operator_mul_impl(PyObject * module,PyObject * a,PyObject * b)87 _operator_mul_impl(PyObject *module, PyObject *a, PyObject *b)
88 /*[clinic end generated code: output=d24d66f55a01944c input=2368615b4358b70d]*/
89 {
90     return PyNumber_Multiply(a, b);
91 }
92 
93 /*[clinic input]
94 _operator.matmul = _operator.add
95 
96 Same as a @ b.
97 [clinic start generated code]*/
98 
99 static PyObject *
_operator_matmul_impl(PyObject * module,PyObject * a,PyObject * b)100 _operator_matmul_impl(PyObject *module, PyObject *a, PyObject *b)
101 /*[clinic end generated code: output=a20d917eb35d0101 input=9ab304e37fb42dd4]*/
102 {
103     return PyNumber_MatrixMultiply(a, b);
104 }
105 
106 /*[clinic input]
107 _operator.floordiv = _operator.add
108 
109 Same as a // b.
110 [clinic start generated code]*/
111 
112 static PyObject *
_operator_floordiv_impl(PyObject * module,PyObject * a,PyObject * b)113 _operator_floordiv_impl(PyObject *module, PyObject *a, PyObject *b)
114 /*[clinic end generated code: output=df26b71a60589f99 input=bb2e88ba446c612c]*/
115 {
116     return PyNumber_FloorDivide(a, b);
117 }
118 
119 /*[clinic input]
120 _operator.truediv = _operator.add
121 
122 Same as a / b.
123 [clinic start generated code]*/
124 
125 static PyObject *
_operator_truediv_impl(PyObject * module,PyObject * a,PyObject * b)126 _operator_truediv_impl(PyObject *module, PyObject *a, PyObject *b)
127 /*[clinic end generated code: output=0e6a959944d77719 input=ecbb947673f4eb1f]*/
128 {
129     return PyNumber_TrueDivide(a, b);
130 }
131 
132 /*[clinic input]
133 _operator.mod = _operator.add
134 
135 Same as a % b.
136 [clinic start generated code]*/
137 
138 static PyObject *
_operator_mod_impl(PyObject * module,PyObject * a,PyObject * b)139 _operator_mod_impl(PyObject *module, PyObject *a, PyObject *b)
140 /*[clinic end generated code: output=9519822f0bbec166 input=102e19b422342ac1]*/
141 {
142     return PyNumber_Remainder(a, b);
143 }
144 
145 /*[clinic input]
146 _operator.neg
147 
148     a: object
149     /
150 
151 Same as -a.
152 [clinic start generated code]*/
153 
154 static PyObject *
_operator_neg(PyObject * module,PyObject * a)155 _operator_neg(PyObject *module, PyObject *a)
156 /*[clinic end generated code: output=36e08ecfc6a1c08c input=84f09bdcf27c96ec]*/
157 {
158     return PyNumber_Negative(a);
159 }
160 
161 /*[clinic input]
162 _operator.pos = _operator.neg
163 
164 Same as +a.
165 [clinic start generated code]*/
166 
167 static PyObject *
_operator_pos(PyObject * module,PyObject * a)168 _operator_pos(PyObject *module, PyObject *a)
169 /*[clinic end generated code: output=dad7a126221dd091 input=b6445b63fddb8772]*/
170 {
171     return PyNumber_Positive(a);
172 }
173 
174 /*[clinic input]
175 _operator.abs = _operator.neg
176 
177 Same as abs(a).
178 [clinic start generated code]*/
179 
180 static PyObject *
_operator_abs(PyObject * module,PyObject * a)181 _operator_abs(PyObject *module, PyObject *a)
182 /*[clinic end generated code: output=1389a93ba053ea3e input=341d07ba86f58039]*/
183 {
184     return PyNumber_Absolute(a);
185 }
186 
187 /*[clinic input]
188 _operator.inv = _operator.neg
189 
190 Same as ~a.
191 [clinic start generated code]*/
192 
193 static PyObject *
_operator_inv(PyObject * module,PyObject * a)194 _operator_inv(PyObject *module, PyObject *a)
195 /*[clinic end generated code: output=a56875ba075ee06d input=b01a4677739f6eb2]*/
196 {
197     return PyNumber_Invert(a);
198 }
199 
200 /*[clinic input]
201 _operator.invert = _operator.neg
202 
203 Same as ~a.
204 [clinic start generated code]*/
205 
206 static PyObject *
_operator_invert(PyObject * module,PyObject * a)207 _operator_invert(PyObject *module, PyObject *a)
208 /*[clinic end generated code: output=406b5aa030545fcc input=7f2d607176672e55]*/
209 {
210     return PyNumber_Invert(a);
211 }
212 
213 /*[clinic input]
214 _operator.lshift = _operator.add
215 
216 Same as a << b.
217 [clinic start generated code]*/
218 
219 static PyObject *
_operator_lshift_impl(PyObject * module,PyObject * a,PyObject * b)220 _operator_lshift_impl(PyObject *module, PyObject *a, PyObject *b)
221 /*[clinic end generated code: output=37f7e52c41435bd8 input=746e8a160cbbc9eb]*/
222 {
223     return PyNumber_Lshift(a, b);
224 }
225 
226 /*[clinic input]
227 _operator.rshift = _operator.add
228 
229 Same as a >> b.
230 [clinic start generated code]*/
231 
232 static PyObject *
_operator_rshift_impl(PyObject * module,PyObject * a,PyObject * b)233 _operator_rshift_impl(PyObject *module, PyObject *a, PyObject *b)
234 /*[clinic end generated code: output=4593c7ef30ec2ee3 input=d2c85bb5a64504c2]*/
235 {
236     return PyNumber_Rshift(a, b);
237 }
238 
239 /*[clinic input]
240 _operator.not_ = _operator.truth
241 
242 Same as not a.
243 [clinic start generated code]*/
244 
245 static int
_operator_not__impl(PyObject * module,PyObject * a)246 _operator_not__impl(PyObject *module, PyObject *a)
247 /*[clinic end generated code: output=743f9c24a09759ef input=854156d50804d9b8]*/
248 {
249     return PyObject_Not(a);
250 }
251 
252 /*[clinic input]
253 _operator.and_ = _operator.add
254 
255 Same as a & b.
256 [clinic start generated code]*/
257 
258 static PyObject *
_operator_and__impl(PyObject * module,PyObject * a,PyObject * b)259 _operator_and__impl(PyObject *module, PyObject *a, PyObject *b)
260 /*[clinic end generated code: output=93c4fe88f7b76d9e input=4f3057c90ec4c99f]*/
261 {
262     return PyNumber_And(a, b);
263 }
264 
265 /*[clinic input]
266 _operator.xor = _operator.add
267 
268 Same as a ^ b.
269 [clinic start generated code]*/
270 
271 static PyObject *
_operator_xor_impl(PyObject * module,PyObject * a,PyObject * b)272 _operator_xor_impl(PyObject *module, PyObject *a, PyObject *b)
273 /*[clinic end generated code: output=b24cd8b79fde0004 input=3c5cfa7253d808dd]*/
274 {
275     return PyNumber_Xor(a, b);
276 }
277 
278 /*[clinic input]
279 _operator.or_ = _operator.add
280 
281 Same as a | b.
282 [clinic start generated code]*/
283 
284 static PyObject *
_operator_or__impl(PyObject * module,PyObject * a,PyObject * b)285 _operator_or__impl(PyObject *module, PyObject *a, PyObject *b)
286 /*[clinic end generated code: output=58024867b8d90461 input=b40c6c44f7c79c09]*/
287 {
288     return PyNumber_Or(a, b);
289 }
290 
291 /*[clinic input]
292 _operator.iadd = _operator.add
293 
294 Same as a += b.
295 [clinic start generated code]*/
296 
297 static PyObject *
_operator_iadd_impl(PyObject * module,PyObject * a,PyObject * b)298 _operator_iadd_impl(PyObject *module, PyObject *a, PyObject *b)
299 /*[clinic end generated code: output=07dc627832526eb5 input=d22a91c07ac69227]*/
300 {
301     return PyNumber_InPlaceAdd(a, b);
302 }
303 
304 /*[clinic input]
305 _operator.isub = _operator.add
306 
307 Same as a -= b.
308 [clinic start generated code]*/
309 
310 static PyObject *
_operator_isub_impl(PyObject * module,PyObject * a,PyObject * b)311 _operator_isub_impl(PyObject *module, PyObject *a, PyObject *b)
312 /*[clinic end generated code: output=4513467d23b5e0b1 input=4591b00d0a0ccafd]*/
313 {
314     return PyNumber_InPlaceSubtract(a, b);
315 }
316 
317 /*[clinic input]
318 _operator.imul = _operator.add
319 
320 Same as a *= b.
321 [clinic start generated code]*/
322 
323 static PyObject *
_operator_imul_impl(PyObject * module,PyObject * a,PyObject * b)324 _operator_imul_impl(PyObject *module, PyObject *a, PyObject *b)
325 /*[clinic end generated code: output=5e87dacd19a71eab input=0e01fb8631e1b76f]*/
326 {
327     return PyNumber_InPlaceMultiply(a, b);
328 }
329 
330 /*[clinic input]
331 _operator.imatmul = _operator.add
332 
333 Same as a @= b.
334 [clinic start generated code]*/
335 
336 static PyObject *
_operator_imatmul_impl(PyObject * module,PyObject * a,PyObject * b)337 _operator_imatmul_impl(PyObject *module, PyObject *a, PyObject *b)
338 /*[clinic end generated code: output=d603cbdf716ce519 input=bb614026372cd542]*/
339 {
340     return PyNumber_InPlaceMatrixMultiply(a, b);
341 }
342 
343 /*[clinic input]
344 _operator.ifloordiv = _operator.add
345 
346 Same as a //= b.
347 [clinic start generated code]*/
348 
349 static PyObject *
_operator_ifloordiv_impl(PyObject * module,PyObject * a,PyObject * b)350 _operator_ifloordiv_impl(PyObject *module, PyObject *a, PyObject *b)
351 /*[clinic end generated code: output=535336048c681794 input=9df3b5021cff4ca1]*/
352 {
353     return PyNumber_InPlaceFloorDivide(a, b);
354 }
355 
356 /*[clinic input]
357 _operator.itruediv = _operator.add
358 
359 Same as a /= b.
360 [clinic start generated code]*/
361 
362 static PyObject *
_operator_itruediv_impl(PyObject * module,PyObject * a,PyObject * b)363 _operator_itruediv_impl(PyObject *module, PyObject *a, PyObject *b)
364 /*[clinic end generated code: output=28017fbd3563952f input=9a1ee01608f5f590]*/
365 {
366     return PyNumber_InPlaceTrueDivide(a, b);
367 }
368 
369 /*[clinic input]
370 _operator.imod = _operator.add
371 
372 Same as a %= b.
373 [clinic start generated code]*/
374 
375 static PyObject *
_operator_imod_impl(PyObject * module,PyObject * a,PyObject * b)376 _operator_imod_impl(PyObject *module, PyObject *a, PyObject *b)
377 /*[clinic end generated code: output=f7c540ae0fc70904 input=d0c384a3ce38e1dd]*/
378 {
379     return PyNumber_InPlaceRemainder(a, b);
380 }
381 
382 /*[clinic input]
383 _operator.ilshift = _operator.add
384 
385 Same as a <<= b.
386 [clinic start generated code]*/
387 
388 static PyObject *
_operator_ilshift_impl(PyObject * module,PyObject * a,PyObject * b)389 _operator_ilshift_impl(PyObject *module, PyObject *a, PyObject *b)
390 /*[clinic end generated code: output=e73a8fee1ac18749 input=e21b6b310f54572e]*/
391 {
392     return PyNumber_InPlaceLshift(a, b);
393 }
394 
395 /*[clinic input]
396 _operator.irshift = _operator.add
397 
398 Same as a >>= b.
399 [clinic start generated code]*/
400 
401 static PyObject *
_operator_irshift_impl(PyObject * module,PyObject * a,PyObject * b)402 _operator_irshift_impl(PyObject *module, PyObject *a, PyObject *b)
403 /*[clinic end generated code: output=97f2af6b5ff2ed81 input=6778dbd0f6e1ec16]*/
404 {
405     return PyNumber_InPlaceRshift(a, b);
406 }
407 
408 /*[clinic input]
409 _operator.iand = _operator.add
410 
411 Same as a &= b.
412 [clinic start generated code]*/
413 
414 static PyObject *
_operator_iand_impl(PyObject * module,PyObject * a,PyObject * b)415 _operator_iand_impl(PyObject *module, PyObject *a, PyObject *b)
416 /*[clinic end generated code: output=4599e9d40cbf7d00 input=71dfd8e70c156a7b]*/
417 {
418     return PyNumber_InPlaceAnd(a, b);
419 }
420 
421 /*[clinic input]
422 _operator.ixor = _operator.add
423 
424 Same as a ^= b.
425 [clinic start generated code]*/
426 
427 static PyObject *
_operator_ixor_impl(PyObject * module,PyObject * a,PyObject * b)428 _operator_ixor_impl(PyObject *module, PyObject *a, PyObject *b)
429 /*[clinic end generated code: output=5ff881766872be03 input=695c32bec0604d86]*/
430 {
431     return PyNumber_InPlaceXor(a, b);
432 }
433 
434 /*[clinic input]
435 _operator.ior = _operator.add
436 
437 Same as a |= b.
438 [clinic start generated code]*/
439 
440 static PyObject *
_operator_ior_impl(PyObject * module,PyObject * a,PyObject * b)441 _operator_ior_impl(PyObject *module, PyObject *a, PyObject *b)
442 /*[clinic end generated code: output=48aac319445bf759 input=8f01d03eda9920cf]*/
443 {
444     return PyNumber_InPlaceOr(a, b);
445 }
446 
447 /*[clinic input]
448 _operator.concat = _operator.add
449 
450 Same as a + b, for a and b sequences.
451 [clinic start generated code]*/
452 
453 static PyObject *
_operator_concat_impl(PyObject * module,PyObject * a,PyObject * b)454 _operator_concat_impl(PyObject *module, PyObject *a, PyObject *b)
455 /*[clinic end generated code: output=80028390942c5f11 input=8544ccd5341a3658]*/
456 {
457     return PySequence_Concat(a, b);
458 }
459 
460 /*[clinic input]
461 _operator.iconcat = _operator.add
462 
463 Same as a += b, for a and b sequences.
464 [clinic start generated code]*/
465 
466 static PyObject *
_operator_iconcat_impl(PyObject * module,PyObject * a,PyObject * b)467 _operator_iconcat_impl(PyObject *module, PyObject *a, PyObject *b)
468 /*[clinic end generated code: output=3ea0a162ebb2e26d input=8f5fe5722fcd837e]*/
469 {
470     return PySequence_InPlaceConcat(a, b);
471 }
472 
473 /*[clinic input]
474 _operator.contains -> bool
475 
476     a: object
477     b: object
478     /
479 
480 Same as b in a (note reversed operands).
481 [clinic start generated code]*/
482 
483 static int
_operator_contains_impl(PyObject * module,PyObject * a,PyObject * b)484 _operator_contains_impl(PyObject *module, PyObject *a, PyObject *b)
485 /*[clinic end generated code: output=413b4dbe82b6ffc1 input=9122a69b505fde13]*/
486 {
487     return PySequence_Contains(a, b);
488 }
489 
490 /*[clinic input]
491 _operator.indexOf -> Py_ssize_t
492 
493     a: object
494     b: object
495     /
496 
497 Return the first index of b in a.
498 [clinic start generated code]*/
499 
500 static Py_ssize_t
_operator_indexOf_impl(PyObject * module,PyObject * a,PyObject * b)501 _operator_indexOf_impl(PyObject *module, PyObject *a, PyObject *b)
502 /*[clinic end generated code: output=c6226d8e0fb60fa6 input=8be2e43b6a6fffe3]*/
503 {
504     return PySequence_Index(a, b);
505 }
506 
507 /*[clinic input]
508 _operator.countOf = _operator.indexOf
509 
510 Return the number of items in a which are, or which equal, b.
511 [clinic start generated code]*/
512 
513 static Py_ssize_t
_operator_countOf_impl(PyObject * module,PyObject * a,PyObject * b)514 _operator_countOf_impl(PyObject *module, PyObject *a, PyObject *b)
515 /*[clinic end generated code: output=9e1623197daf3382 input=93ea57f170f3f0bb]*/
516 {
517     return PySequence_Count(a, b);
518 }
519 
520 /*[clinic input]
521 _operator.getitem
522 
523     a: object
524     b: object
525     /
526 
527 Same as a[b].
528 [clinic start generated code]*/
529 
530 static PyObject *
_operator_getitem_impl(PyObject * module,PyObject * a,PyObject * b)531 _operator_getitem_impl(PyObject *module, PyObject *a, PyObject *b)
532 /*[clinic end generated code: output=6c8d8101a676e594 input=6682797320e48845]*/
533 {
534     return PyObject_GetItem(a, b);
535 }
536 
537 /*[clinic input]
538 _operator.setitem
539 
540     a: object
541     b: object
542     c: object
543     /
544 
545 Same as a[b] = c.
546 [clinic start generated code]*/
547 
548 static PyObject *
_operator_setitem_impl(PyObject * module,PyObject * a,PyObject * b,PyObject * c)549 _operator_setitem_impl(PyObject *module, PyObject *a, PyObject *b,
550                        PyObject *c)
551 /*[clinic end generated code: output=1324f9061ae99e25 input=ceaf453c4d3a58df]*/
552 {
553     if (-1 == PyObject_SetItem(a, b, c))
554         return NULL;
555     Py_RETURN_NONE;
556 }
557 
558 /*[clinic input]
559 _operator.delitem = _operator.getitem
560 
561 Same as del a[b].
562 [clinic start generated code]*/
563 
564 static PyObject *
_operator_delitem_impl(PyObject * module,PyObject * a,PyObject * b)565 _operator_delitem_impl(PyObject *module, PyObject *a, PyObject *b)
566 /*[clinic end generated code: output=db18f61506295799 input=991bec56a0d3ec7f]*/
567 {
568     if (-1 == PyObject_DelItem(a, b))
569         return NULL;
570     Py_RETURN_NONE;
571 }
572 
573 /*[clinic input]
574 _operator.eq
575 
576     a: object
577     b: object
578     /
579 
580 Same as a == b.
581 [clinic start generated code]*/
582 
583 static PyObject *
_operator_eq_impl(PyObject * module,PyObject * a,PyObject * b)584 _operator_eq_impl(PyObject *module, PyObject *a, PyObject *b)
585 /*[clinic end generated code: output=8d7d46ed4135677c input=586fca687a95a83f]*/
586 {
587     return PyObject_RichCompare(a, b, Py_EQ);
588 }
589 
590 /*[clinic input]
591 _operator.ne = _operator.eq
592 
593 Same as a != b.
594 [clinic start generated code]*/
595 
596 static PyObject *
_operator_ne_impl(PyObject * module,PyObject * a,PyObject * b)597 _operator_ne_impl(PyObject *module, PyObject *a, PyObject *b)
598 /*[clinic end generated code: output=c99bd0c3a4c01297 input=5d88f23d35e9abac]*/
599 {
600     return PyObject_RichCompare(a, b, Py_NE);
601 }
602 
603 /*[clinic input]
604 _operator.lt = _operator.eq
605 
606 Same as a < b.
607 [clinic start generated code]*/
608 
609 static PyObject *
_operator_lt_impl(PyObject * module,PyObject * a,PyObject * b)610 _operator_lt_impl(PyObject *module, PyObject *a, PyObject *b)
611 /*[clinic end generated code: output=082d7c45c440e535 input=34a59ad6d39d3a2b]*/
612 {
613     return PyObject_RichCompare(a, b, Py_LT);
614 }
615 
616 /*[clinic input]
617 _operator.le = _operator.eq
618 
619 Same as a <= b.
620 [clinic start generated code]*/
621 
622 static PyObject *
_operator_le_impl(PyObject * module,PyObject * a,PyObject * b)623 _operator_le_impl(PyObject *module, PyObject *a, PyObject *b)
624 /*[clinic end generated code: output=00970a2923d0ae17 input=b812a7860a0bef44]*/
625 {
626     return PyObject_RichCompare(a, b, Py_LE);
627 }
628 
629 /*[clinic input]
630 _operator.gt = _operator.eq
631 
632 Same as a > b.
633 [clinic start generated code]*/
634 
635 static PyObject *
_operator_gt_impl(PyObject * module,PyObject * a,PyObject * b)636 _operator_gt_impl(PyObject *module, PyObject *a, PyObject *b)
637 /*[clinic end generated code: output=8d373349ecf25641 input=9bdb45b995ada35b]*/
638 {
639     return PyObject_RichCompare(a, b, Py_GT);
640 }
641 
642 /*[clinic input]
643 _operator.ge = _operator.eq
644 
645 Same as a >= b.
646 [clinic start generated code]*/
647 
648 static PyObject *
_operator_ge_impl(PyObject * module,PyObject * a,PyObject * b)649 _operator_ge_impl(PyObject *module, PyObject *a, PyObject *b)
650 /*[clinic end generated code: output=7ce3882256d4b137 input=cf1dc4a5ca9c35f5]*/
651 {
652     return PyObject_RichCompare(a, b, Py_GE);
653 }
654 
655 /*[clinic input]
656 _operator.pow = _operator.add
657 
658 Same as a ** b.
659 [clinic start generated code]*/
660 
661 static PyObject *
_operator_pow_impl(PyObject * module,PyObject * a,PyObject * b)662 _operator_pow_impl(PyObject *module, PyObject *a, PyObject *b)
663 /*[clinic end generated code: output=09e668ad50036120 input=690b40f097ab1637]*/
664 {
665     return PyNumber_Power(a, b, Py_None);
666 }
667 
668 /*[clinic input]
669 _operator.ipow = _operator.add
670 
671 Same as a **= b.
672 [clinic start generated code]*/
673 
674 static PyObject *
_operator_ipow_impl(PyObject * module,PyObject * a,PyObject * b)675 _operator_ipow_impl(PyObject *module, PyObject *a, PyObject *b)
676 /*[clinic end generated code: output=7189ff4d4367c808 input=f00623899d07499a]*/
677 {
678     return PyNumber_InPlacePower(a, b, Py_None);
679 }
680 
681 /*[clinic input]
682 _operator.index
683 
684     a: object
685     /
686 
687 Same as a.__index__()
688 [clinic start generated code]*/
689 
690 static PyObject *
_operator_index(PyObject * module,PyObject * a)691 _operator_index(PyObject *module, PyObject *a)
692 /*[clinic end generated code: output=d972b0764ac305fc input=6f54d50ea64a579c]*/
693 {
694     return PyNumber_Index(a);
695 }
696 
697 /*[clinic input]
698 _operator.is_ = _operator.add
699 
700 Same as a is b.
701 [clinic start generated code]*/
702 
703 static PyObject *
_operator_is__impl(PyObject * module,PyObject * a,PyObject * b)704 _operator_is__impl(PyObject *module, PyObject *a, PyObject *b)
705 /*[clinic end generated code: output=bcd47a402e482e1d input=5fa9b97df03c427f]*/
706 {
707     PyObject *result;
708     result = (a == b) ? Py_True : Py_False;
709     Py_INCREF(result);
710     return result;
711 }
712 
713 /*[clinic input]
714 _operator.is_not = _operator.add
715 
716 Same as a is not b.
717 [clinic start generated code]*/
718 
719 static PyObject *
_operator_is_not_impl(PyObject * module,PyObject * a,PyObject * b)720 _operator_is_not_impl(PyObject *module, PyObject *a, PyObject *b)
721 /*[clinic end generated code: output=491a1f2f81f6c7f9 input=5a93f7e1a93535f1]*/
722 {
723     PyObject *result;
724     result = (a != b) ? Py_True : Py_False;
725     Py_INCREF(result);
726     return result;
727 }
728 
729 /* compare_digest **********************************************************/
730 
731 /*
732  * timing safe compare
733  *
734  * Returns 1 of the strings are equal.
735  * In case of len(a) != len(b) the function tries to keep the timing
736  * dependent on the length of b. CPU cache locally may still alter timing
737  * a bit.
738  */
739 static int
_tscmp(const unsigned char * a,const unsigned char * b,Py_ssize_t len_a,Py_ssize_t len_b)740 _tscmp(const unsigned char *a, const unsigned char *b,
741         Py_ssize_t len_a, Py_ssize_t len_b)
742 {
743     /* The volatile type declarations make sure that the compiler has no
744      * chance to optimize and fold the code in any way that may change
745      * the timing.
746      */
747     volatile Py_ssize_t length;
748     volatile const unsigned char *left;
749     volatile const unsigned char *right;
750     Py_ssize_t i;
751     volatile unsigned char result;
752 
753     /* loop count depends on length of b */
754     length = len_b;
755     left = NULL;
756     right = b;
757 
758     /* don't use else here to keep the amount of CPU instructions constant,
759      * volatile forces re-evaluation
760      *  */
761     if (len_a == length) {
762         left = *((volatile const unsigned char**)&a);
763         result = 0;
764     }
765     if (len_a != length) {
766         left = b;
767         result = 1;
768     }
769 
770     for (i=0; i < length; i++) {
771         result |= *left++ ^ *right++;
772     }
773 
774     return (result == 0);
775 }
776 
777 /*[clinic input]
778 _operator.length_hint -> Py_ssize_t
779 
780     obj: object
781     default: Py_ssize_t = 0
782     /
783 
784 Return an estimate of the number of items in obj.
785 
786 This is useful for presizing containers when building from an iterable.
787 
788 If the object supports len(), the result will be exact.
789 Otherwise, it may over- or under-estimate by an arbitrary amount.
790 The result will be an integer >= 0.
791 [clinic start generated code]*/
792 
793 static Py_ssize_t
_operator_length_hint_impl(PyObject * module,PyObject * obj,Py_ssize_t default_value)794 _operator_length_hint_impl(PyObject *module, PyObject *obj,
795                            Py_ssize_t default_value)
796 /*[clinic end generated code: output=01d469edc1d612ad input=65ed29f04401e96a]*/
797 {
798     return PyObject_LengthHint(obj, default_value);
799 }
800 
801 /* NOTE: Keep in sync with _hashopenssl.c implementation. */
802 
803 /*[clinic input]
804 _operator._compare_digest = _operator.eq
805 
806 Return 'a == b'.
807 
808 This function uses an approach designed to prevent
809 timing analysis, making it appropriate for cryptography.
810 
811 a and b must both be of the same type: either str (ASCII only),
812 or any bytes-like object.
813 
814 Note: If a and b are of different lengths, or if an error occurs,
815 a timing attack could theoretically reveal information about the
816 types and lengths of a and b--but not their values.
817 [clinic start generated code]*/
818 
819 static PyObject *
_operator__compare_digest_impl(PyObject * module,PyObject * a,PyObject * b)820 _operator__compare_digest_impl(PyObject *module, PyObject *a, PyObject *b)
821 /*[clinic end generated code: output=11d452bdd3a23cbc input=9ac7e2c4e30bc356]*/
822 {
823     int rc;
824 
825     /* ASCII unicode string */
826     if(PyUnicode_Check(a) && PyUnicode_Check(b)) {
827         if (PyUnicode_READY(a) == -1 || PyUnicode_READY(b) == -1) {
828             return NULL;
829         }
830         if (!PyUnicode_IS_ASCII(a) || !PyUnicode_IS_ASCII(b)) {
831             PyErr_SetString(PyExc_TypeError,
832                             "comparing strings with non-ASCII characters is "
833                             "not supported");
834             return NULL;
835         }
836 
837         rc = _tscmp(PyUnicode_DATA(a),
838                     PyUnicode_DATA(b),
839                     PyUnicode_GET_LENGTH(a),
840                     PyUnicode_GET_LENGTH(b));
841     }
842     /* fallback to buffer interface for bytes, bytesarray and other */
843     else {
844         Py_buffer view_a;
845         Py_buffer view_b;
846 
847         if (PyObject_CheckBuffer(a) == 0 && PyObject_CheckBuffer(b) == 0) {
848             PyErr_Format(PyExc_TypeError,
849                          "unsupported operand types(s) or combination of types: "
850                          "'%.100s' and '%.100s'",
851                          Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
852             return NULL;
853         }
854 
855         if (PyObject_GetBuffer(a, &view_a, PyBUF_SIMPLE) == -1) {
856             return NULL;
857         }
858         if (view_a.ndim > 1) {
859             PyErr_SetString(PyExc_BufferError,
860                             "Buffer must be single dimension");
861             PyBuffer_Release(&view_a);
862             return NULL;
863         }
864 
865         if (PyObject_GetBuffer(b, &view_b, PyBUF_SIMPLE) == -1) {
866             PyBuffer_Release(&view_a);
867             return NULL;
868         }
869         if (view_b.ndim > 1) {
870             PyErr_SetString(PyExc_BufferError,
871                             "Buffer must be single dimension");
872             PyBuffer_Release(&view_a);
873             PyBuffer_Release(&view_b);
874             return NULL;
875         }
876 
877         rc = _tscmp((const unsigned char*)view_a.buf,
878                     (const unsigned char*)view_b.buf,
879                     view_a.len,
880                     view_b.len);
881 
882         PyBuffer_Release(&view_a);
883         PyBuffer_Release(&view_b);
884     }
885 
886     return PyBool_FromLong(rc);
887 }
888 
889 /* operator methods **********************************************************/
890 
891 static struct PyMethodDef operator_methods[] = {
892 
893     _OPERATOR_TRUTH_METHODDEF
894     _OPERATOR_CONTAINS_METHODDEF
895     _OPERATOR_INDEXOF_METHODDEF
896     _OPERATOR_COUNTOF_METHODDEF
897     _OPERATOR_IS__METHODDEF
898     _OPERATOR_IS_NOT_METHODDEF
899     _OPERATOR_INDEX_METHODDEF
900     _OPERATOR_ADD_METHODDEF
901     _OPERATOR_SUB_METHODDEF
902     _OPERATOR_MUL_METHODDEF
903     _OPERATOR_MATMUL_METHODDEF
904     _OPERATOR_FLOORDIV_METHODDEF
905     _OPERATOR_TRUEDIV_METHODDEF
906     _OPERATOR_MOD_METHODDEF
907     _OPERATOR_NEG_METHODDEF
908     _OPERATOR_POS_METHODDEF
909     _OPERATOR_ABS_METHODDEF
910     _OPERATOR_INV_METHODDEF
911     _OPERATOR_INVERT_METHODDEF
912     _OPERATOR_LSHIFT_METHODDEF
913     _OPERATOR_RSHIFT_METHODDEF
914     _OPERATOR_NOT__METHODDEF
915     _OPERATOR_AND__METHODDEF
916     _OPERATOR_XOR_METHODDEF
917     _OPERATOR_OR__METHODDEF
918     _OPERATOR_IADD_METHODDEF
919     _OPERATOR_ISUB_METHODDEF
920     _OPERATOR_IMUL_METHODDEF
921     _OPERATOR_IMATMUL_METHODDEF
922     _OPERATOR_IFLOORDIV_METHODDEF
923     _OPERATOR_ITRUEDIV_METHODDEF
924     _OPERATOR_IMOD_METHODDEF
925     _OPERATOR_ILSHIFT_METHODDEF
926     _OPERATOR_IRSHIFT_METHODDEF
927     _OPERATOR_IAND_METHODDEF
928     _OPERATOR_IXOR_METHODDEF
929     _OPERATOR_IOR_METHODDEF
930     _OPERATOR_CONCAT_METHODDEF
931     _OPERATOR_ICONCAT_METHODDEF
932     _OPERATOR_GETITEM_METHODDEF
933     _OPERATOR_SETITEM_METHODDEF
934     _OPERATOR_DELITEM_METHODDEF
935     _OPERATOR_POW_METHODDEF
936     _OPERATOR_IPOW_METHODDEF
937     _OPERATOR_EQ_METHODDEF
938     _OPERATOR_NE_METHODDEF
939     _OPERATOR_LT_METHODDEF
940     _OPERATOR_LE_METHODDEF
941     _OPERATOR_GT_METHODDEF
942     _OPERATOR_GE_METHODDEF
943     _OPERATOR__COMPARE_DIGEST_METHODDEF
944     _OPERATOR_LENGTH_HINT_METHODDEF
945     {NULL,              NULL}           /* sentinel */
946 
947 };
948 
949 /* itemgetter object **********************************************************/
950 
951 typedef struct {
952     PyObject_HEAD
953     Py_ssize_t nitems;
954     PyObject *item;
955     Py_ssize_t index; // -1 unless *item* is a single non-negative integer index
956 } itemgetterobject;
957 
958 /* AC 3.5: treats first argument as an iterable, otherwise uses *args */
959 static PyObject *
itemgetter_new(PyTypeObject * type,PyObject * args,PyObject * kwds)960 itemgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
961 {
962     itemgetterobject *ig;
963     PyObject *item;
964     Py_ssize_t nitems;
965     Py_ssize_t index;
966 
967     if (!_PyArg_NoKeywords("itemgetter", kwds))
968         return NULL;
969 
970     nitems = PyTuple_GET_SIZE(args);
971     if (nitems <= 1) {
972         if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item))
973             return NULL;
974     } else {
975         item = args;
976     }
977     _operator_state *state = PyType_GetModuleState(type);
978     /* create itemgetterobject structure */
979     ig = PyObject_GC_New(itemgetterobject, (PyTypeObject *) state->itemgetter_type);
980     if (ig == NULL) {
981         return NULL;
982     }
983 
984     Py_INCREF(item);
985     ig->item = item;
986     ig->nitems = nitems;
987     ig->index = -1;
988     if (PyLong_CheckExact(item)) {
989         index = PyLong_AsSsize_t(item);
990         if (index < 0) {
991             /* If we get here, then either the index conversion failed
992              * due to being out of range, or the index was a negative
993              * integer.  Either way, we clear any possible exception
994              * and fall back to the slow path, where ig->index is -1.
995              */
996             PyErr_Clear();
997         }
998         else {
999             ig->index = index;
1000         }
1001     }
1002 
1003     PyObject_GC_Track(ig);
1004     return (PyObject *)ig;
1005 }
1006 
1007 static int
itemgetter_clear(itemgetterobject * ig)1008 itemgetter_clear(itemgetterobject *ig)
1009 {
1010     Py_CLEAR(ig->item);
1011     return 0;
1012 }
1013 
1014 static void
itemgetter_dealloc(itemgetterobject * ig)1015 itemgetter_dealloc(itemgetterobject *ig)
1016 {
1017     PyTypeObject *tp = Py_TYPE(ig);
1018     PyObject_GC_UnTrack(ig);
1019     (void)itemgetter_clear(ig);
1020     tp->tp_free(ig);
1021     Py_DECREF(tp);
1022 }
1023 
1024 static int
itemgetter_traverse(itemgetterobject * ig,visitproc visit,void * arg)1025 itemgetter_traverse(itemgetterobject *ig, visitproc visit, void *arg)
1026 {
1027     Py_VISIT(Py_TYPE(ig));
1028     Py_VISIT(ig->item);
1029     return 0;
1030 }
1031 
1032 static PyObject *
itemgetter_call(itemgetterobject * ig,PyObject * args,PyObject * kw)1033 itemgetter_call(itemgetterobject *ig, PyObject *args, PyObject *kw)
1034 {
1035     PyObject *obj, *result;
1036     Py_ssize_t i, nitems=ig->nitems;
1037 
1038     assert(PyTuple_CheckExact(args));
1039     if (!_PyArg_NoKeywords("itemgetter", kw))
1040         return NULL;
1041     if (!_PyArg_CheckPositional("itemgetter", PyTuple_GET_SIZE(args), 1, 1))
1042         return NULL;
1043 
1044     obj = PyTuple_GET_ITEM(args, 0);
1045     if (nitems == 1) {
1046         if (ig->index >= 0
1047             && PyTuple_CheckExact(obj)
1048             && ig->index < PyTuple_GET_SIZE(obj))
1049         {
1050             result = PyTuple_GET_ITEM(obj, ig->index);
1051             Py_INCREF(result);
1052             return result;
1053         }
1054         return PyObject_GetItem(obj, ig->item);
1055     }
1056 
1057     assert(PyTuple_Check(ig->item));
1058     assert(PyTuple_GET_SIZE(ig->item) == nitems);
1059 
1060     result = PyTuple_New(nitems);
1061     if (result == NULL)
1062         return NULL;
1063 
1064     for (i=0 ; i < nitems ; i++) {
1065         PyObject *item, *val;
1066         item = PyTuple_GET_ITEM(ig->item, i);
1067         val = PyObject_GetItem(obj, item);
1068         if (val == NULL) {
1069             Py_DECREF(result);
1070             return NULL;
1071         }
1072         PyTuple_SET_ITEM(result, i, val);
1073     }
1074     return result;
1075 }
1076 
1077 static PyObject *
itemgetter_repr(itemgetterobject * ig)1078 itemgetter_repr(itemgetterobject *ig)
1079 {
1080     PyObject *repr;
1081     const char *reprfmt;
1082 
1083     int status = Py_ReprEnter((PyObject *)ig);
1084     if (status != 0) {
1085         if (status < 0)
1086             return NULL;
1087         return PyUnicode_FromFormat("%s(...)", Py_TYPE(ig)->tp_name);
1088     }
1089 
1090     reprfmt = ig->nitems == 1 ? "%s(%R)" : "%s%R";
1091     repr = PyUnicode_FromFormat(reprfmt, Py_TYPE(ig)->tp_name, ig->item);
1092     Py_ReprLeave((PyObject *)ig);
1093     return repr;
1094 }
1095 
1096 static PyObject *
itemgetter_reduce(itemgetterobject * ig,PyObject * Py_UNUSED (ignored))1097 itemgetter_reduce(itemgetterobject *ig, PyObject *Py_UNUSED(ignored))
1098 {
1099     if (ig->nitems == 1)
1100         return Py_BuildValue("O(O)", Py_TYPE(ig), ig->item);
1101     return PyTuple_Pack(2, Py_TYPE(ig), ig->item);
1102 }
1103 
1104 PyDoc_STRVAR(reduce_doc, "Return state information for pickling");
1105 
1106 static PyMethodDef itemgetter_methods[] = {
1107     {"__reduce__", (PyCFunction)itemgetter_reduce, METH_NOARGS,
1108      reduce_doc},
1109     {NULL}
1110 };
1111 
1112 PyDoc_STRVAR(itemgetter_doc,
1113 "itemgetter(item, ...) --> itemgetter object\n\
1114 \n\
1115 Return a callable object that fetches the given item(s) from its operand.\n\
1116 After f = itemgetter(2), the call f(r) returns r[2].\n\
1117 After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])");
1118 
1119 static PyType_Slot itemgetter_type_slots[] = {
1120     {Py_tp_doc, (void *)itemgetter_doc},
1121     {Py_tp_dealloc, itemgetter_dealloc},
1122     {Py_tp_call, itemgetter_call},
1123     {Py_tp_traverse, itemgetter_traverse},
1124     {Py_tp_clear, itemgetter_clear},
1125     {Py_tp_methods, itemgetter_methods},
1126     {Py_tp_new, itemgetter_new},
1127     {Py_tp_getattro, PyObject_GenericGetAttr},
1128     {Py_tp_repr, itemgetter_repr},
1129     {0, 0}
1130 };
1131 
1132 static PyType_Spec itemgetter_type_spec = {
1133     .name = "operator.itemgetter",
1134     .basicsize = sizeof(itemgetterobject),
1135     .itemsize = 0,
1136     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1137               Py_TPFLAGS_IMMUTABLETYPE),
1138     .slots = itemgetter_type_slots,
1139 };
1140 
1141 /* attrgetter object **********************************************************/
1142 
1143 typedef struct {
1144     PyObject_HEAD
1145     Py_ssize_t nattrs;
1146     PyObject *attr;
1147 } attrgetterobject;
1148 
1149 /* AC 3.5: treats first argument as an iterable, otherwise uses *args */
1150 static PyObject *
attrgetter_new(PyTypeObject * type,PyObject * args,PyObject * kwds)1151 attrgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1152 {
1153     attrgetterobject *ag;
1154     PyObject *attr;
1155     Py_ssize_t nattrs, idx, char_idx;
1156 
1157     if (!_PyArg_NoKeywords("attrgetter", kwds))
1158         return NULL;
1159 
1160     nattrs = PyTuple_GET_SIZE(args);
1161     if (nattrs <= 1) {
1162         if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr))
1163             return NULL;
1164     }
1165 
1166     attr = PyTuple_New(nattrs);
1167     if (attr == NULL)
1168         return NULL;
1169 
1170     /* prepare attr while checking args */
1171     for (idx = 0; idx < nattrs; ++idx) {
1172         PyObject *item = PyTuple_GET_ITEM(args, idx);
1173         Py_ssize_t item_len;
1174         const void *data;
1175         unsigned int kind;
1176         int dot_count;
1177 
1178         if (!PyUnicode_Check(item)) {
1179             PyErr_SetString(PyExc_TypeError,
1180                             "attribute name must be a string");
1181             Py_DECREF(attr);
1182             return NULL;
1183         }
1184         if (PyUnicode_READY(item)) {
1185             Py_DECREF(attr);
1186             return NULL;
1187         }
1188         item_len = PyUnicode_GET_LENGTH(item);
1189         kind = PyUnicode_KIND(item);
1190         data = PyUnicode_DATA(item);
1191 
1192         /* check whethere the string is dotted */
1193         dot_count = 0;
1194         for (char_idx = 0; char_idx < item_len; ++char_idx) {
1195             if (PyUnicode_READ(kind, data, char_idx) == '.')
1196                 ++dot_count;
1197         }
1198 
1199         if (dot_count == 0) {
1200             Py_INCREF(item);
1201             PyUnicode_InternInPlace(&item);
1202             PyTuple_SET_ITEM(attr, idx, item);
1203         } else { /* make it a tuple of non-dotted attrnames */
1204             PyObject *attr_chain = PyTuple_New(dot_count + 1);
1205             PyObject *attr_chain_item;
1206             Py_ssize_t unibuff_from = 0;
1207             Py_ssize_t unibuff_till = 0;
1208             Py_ssize_t attr_chain_idx = 0;
1209 
1210             if (attr_chain == NULL) {
1211                 Py_DECREF(attr);
1212                 return NULL;
1213             }
1214 
1215             for (; dot_count > 0; --dot_count) {
1216                 while (PyUnicode_READ(kind, data, unibuff_till) != '.') {
1217                     ++unibuff_till;
1218                 }
1219                 attr_chain_item = PyUnicode_Substring(item,
1220                                       unibuff_from,
1221                                       unibuff_till);
1222                 if (attr_chain_item == NULL) {
1223                     Py_DECREF(attr_chain);
1224                     Py_DECREF(attr);
1225                     return NULL;
1226                 }
1227                 PyUnicode_InternInPlace(&attr_chain_item);
1228                 PyTuple_SET_ITEM(attr_chain, attr_chain_idx, attr_chain_item);
1229                 ++attr_chain_idx;
1230                 unibuff_till = unibuff_from = unibuff_till + 1;
1231             }
1232 
1233             /* now add the last dotless name */
1234             attr_chain_item = PyUnicode_Substring(item,
1235                                                   unibuff_from, item_len);
1236             if (attr_chain_item == NULL) {
1237                 Py_DECREF(attr_chain);
1238                 Py_DECREF(attr);
1239                 return NULL;
1240             }
1241             PyUnicode_InternInPlace(&attr_chain_item);
1242             PyTuple_SET_ITEM(attr_chain, attr_chain_idx, attr_chain_item);
1243 
1244             PyTuple_SET_ITEM(attr, idx, attr_chain);
1245         }
1246     }
1247 
1248     _operator_state *state = PyType_GetModuleState(type);
1249     /* create attrgetterobject structure */
1250     ag = PyObject_GC_New(attrgetterobject, (PyTypeObject *)state->attrgetter_type);
1251     if (ag == NULL) {
1252         Py_DECREF(attr);
1253         return NULL;
1254     }
1255 
1256     ag->attr = attr;
1257     ag->nattrs = nattrs;
1258 
1259     PyObject_GC_Track(ag);
1260     return (PyObject *)ag;
1261 }
1262 
1263 static int
attrgetter_clear(attrgetterobject * ag)1264 attrgetter_clear(attrgetterobject *ag)
1265 {
1266     Py_CLEAR(ag->attr);
1267     return 0;
1268 }
1269 
1270 static void
attrgetter_dealloc(attrgetterobject * ag)1271 attrgetter_dealloc(attrgetterobject *ag)
1272 {
1273     PyTypeObject *tp = Py_TYPE(ag);
1274     PyObject_GC_UnTrack(ag);
1275     (void)attrgetter_clear(ag);
1276     tp->tp_free(ag);
1277     Py_DECREF(tp);
1278 }
1279 
1280 static int
attrgetter_traverse(attrgetterobject * ag,visitproc visit,void * arg)1281 attrgetter_traverse(attrgetterobject *ag, visitproc visit, void *arg)
1282 {
1283     Py_VISIT(ag->attr);
1284     Py_VISIT(Py_TYPE(ag));
1285     return 0;
1286 }
1287 
1288 static PyObject *
dotted_getattr(PyObject * obj,PyObject * attr)1289 dotted_getattr(PyObject *obj, PyObject *attr)
1290 {
1291     PyObject *newobj;
1292 
1293     /* attr is either a tuple or instance of str.
1294        Ensured by the setup code of attrgetter_new */
1295     if (PyTuple_CheckExact(attr)) { /* chained getattr */
1296         Py_ssize_t name_idx = 0, name_count;
1297         PyObject *attr_name;
1298 
1299         name_count = PyTuple_GET_SIZE(attr);
1300         Py_INCREF(obj);
1301         for (name_idx = 0; name_idx < name_count; ++name_idx) {
1302             attr_name = PyTuple_GET_ITEM(attr, name_idx);
1303             newobj = PyObject_GetAttr(obj, attr_name);
1304             Py_DECREF(obj);
1305             if (newobj == NULL) {
1306                 return NULL;
1307             }
1308             /* here */
1309             obj = newobj;
1310         }
1311     } else { /* single getattr */
1312         newobj = PyObject_GetAttr(obj, attr);
1313         if (newobj == NULL)
1314             return NULL;
1315         obj = newobj;
1316     }
1317 
1318     return obj;
1319 }
1320 
1321 static PyObject *
attrgetter_call(attrgetterobject * ag,PyObject * args,PyObject * kw)1322 attrgetter_call(attrgetterobject *ag, PyObject *args, PyObject *kw)
1323 {
1324     PyObject *obj, *result;
1325     Py_ssize_t i, nattrs=ag->nattrs;
1326 
1327     if (!_PyArg_NoKeywords("attrgetter", kw))
1328         return NULL;
1329     if (!_PyArg_CheckPositional("attrgetter", PyTuple_GET_SIZE(args), 1, 1))
1330         return NULL;
1331     obj = PyTuple_GET_ITEM(args, 0);
1332     if (ag->nattrs == 1) /* ag->attr is always a tuple */
1333         return dotted_getattr(obj, PyTuple_GET_ITEM(ag->attr, 0));
1334 
1335     assert(PyTuple_Check(ag->attr));
1336     assert(PyTuple_GET_SIZE(ag->attr) == nattrs);
1337 
1338     result = PyTuple_New(nattrs);
1339     if (result == NULL)
1340         return NULL;
1341 
1342     for (i=0 ; i < nattrs ; i++) {
1343         PyObject *attr, *val;
1344         attr = PyTuple_GET_ITEM(ag->attr, i);
1345         val = dotted_getattr(obj, attr);
1346         if (val == NULL) {
1347             Py_DECREF(result);
1348             return NULL;
1349         }
1350         PyTuple_SET_ITEM(result, i, val);
1351     }
1352     return result;
1353 }
1354 
1355 static PyObject *
dotjoinattr(PyObject * attr,PyObject ** attrsep)1356 dotjoinattr(PyObject *attr, PyObject **attrsep)
1357 {
1358     if (PyTuple_CheckExact(attr)) {
1359         if (*attrsep == NULL) {
1360             *attrsep = PyUnicode_FromString(".");
1361             if (*attrsep == NULL)
1362                 return NULL;
1363         }
1364         return PyUnicode_Join(*attrsep, attr);
1365     } else {
1366         Py_INCREF(attr);
1367         return attr;
1368     }
1369 }
1370 
1371 static PyObject *
attrgetter_args(attrgetterobject * ag)1372 attrgetter_args(attrgetterobject *ag)
1373 {
1374     Py_ssize_t i;
1375     PyObject *attrsep = NULL;
1376     PyObject *attrstrings = PyTuple_New(ag->nattrs);
1377     if (attrstrings == NULL)
1378         return NULL;
1379 
1380     for (i = 0; i < ag->nattrs; ++i) {
1381         PyObject *attr = PyTuple_GET_ITEM(ag->attr, i);
1382         PyObject *attrstr = dotjoinattr(attr, &attrsep);
1383         if (attrstr == NULL) {
1384             Py_XDECREF(attrsep);
1385             Py_DECREF(attrstrings);
1386             return NULL;
1387         }
1388         PyTuple_SET_ITEM(attrstrings, i, attrstr);
1389     }
1390     Py_XDECREF(attrsep);
1391     return attrstrings;
1392 }
1393 
1394 static PyObject *
attrgetter_repr(attrgetterobject * ag)1395 attrgetter_repr(attrgetterobject *ag)
1396 {
1397     PyObject *repr = NULL;
1398     int status = Py_ReprEnter((PyObject *)ag);
1399     if (status != 0) {
1400         if (status < 0)
1401             return NULL;
1402         return PyUnicode_FromFormat("%s(...)", Py_TYPE(ag)->tp_name);
1403     }
1404 
1405     if (ag->nattrs == 1) {
1406         PyObject *attrsep = NULL;
1407         PyObject *attr = dotjoinattr(PyTuple_GET_ITEM(ag->attr, 0), &attrsep);
1408         if (attr != NULL) {
1409             repr = PyUnicode_FromFormat("%s(%R)", Py_TYPE(ag)->tp_name, attr);
1410             Py_DECREF(attr);
1411         }
1412         Py_XDECREF(attrsep);
1413     }
1414     else {
1415         PyObject *attrstrings = attrgetter_args(ag);
1416         if (attrstrings != NULL) {
1417             repr = PyUnicode_FromFormat("%s%R",
1418                                         Py_TYPE(ag)->tp_name, attrstrings);
1419             Py_DECREF(attrstrings);
1420         }
1421     }
1422     Py_ReprLeave((PyObject *)ag);
1423     return repr;
1424 }
1425 
1426 static PyObject *
attrgetter_reduce(attrgetterobject * ag,PyObject * Py_UNUSED (ignored))1427 attrgetter_reduce(attrgetterobject *ag, PyObject *Py_UNUSED(ignored))
1428 {
1429     PyObject *attrstrings = attrgetter_args(ag);
1430     if (attrstrings == NULL)
1431         return NULL;
1432 
1433     return Py_BuildValue("ON", Py_TYPE(ag), attrstrings);
1434 }
1435 
1436 static PyMethodDef attrgetter_methods[] = {
1437     {"__reduce__", (PyCFunction)attrgetter_reduce, METH_NOARGS,
1438      reduce_doc},
1439     {NULL}
1440 };
1441 
1442 PyDoc_STRVAR(attrgetter_doc,
1443 "attrgetter(attr, ...) --> attrgetter object\n\
1444 \n\
1445 Return a callable object that fetches the given attribute(s) from its operand.\n\
1446 After f = attrgetter('name'), the call f(r) returns r.name.\n\
1447 After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date).\n\
1448 After h = attrgetter('name.first', 'name.last'), the call h(r) returns\n\
1449 (r.name.first, r.name.last).");
1450 
1451 static PyType_Slot attrgetter_type_slots[] = {
1452     {Py_tp_doc, (void *)attrgetter_doc},
1453     {Py_tp_dealloc, attrgetter_dealloc},
1454     {Py_tp_call, attrgetter_call},
1455     {Py_tp_traverse, attrgetter_traverse},
1456     {Py_tp_clear, attrgetter_clear},
1457     {Py_tp_methods, attrgetter_methods},
1458     {Py_tp_new, attrgetter_new},
1459     {Py_tp_getattro, PyObject_GenericGetAttr},
1460     {Py_tp_repr, attrgetter_repr},
1461     {0, 0}
1462 };
1463 
1464 static PyType_Spec attrgetter_type_spec = {
1465     .name = "operator.attrgetter",
1466     .basicsize = sizeof(attrgetterobject),
1467     .itemsize = 0,
1468     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1469               Py_TPFLAGS_IMMUTABLETYPE),
1470     .slots = attrgetter_type_slots,
1471 };
1472 
1473 
1474 /* methodcaller object **********************************************************/
1475 
1476 typedef struct {
1477     PyObject_HEAD
1478     PyObject *name;
1479     PyObject *args;
1480     PyObject *kwds;
1481 } methodcallerobject;
1482 
1483 /* AC 3.5: variable number of arguments, not currently support by AC */
1484 static PyObject *
methodcaller_new(PyTypeObject * type,PyObject * args,PyObject * kwds)1485 methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1486 {
1487     methodcallerobject *mc;
1488     PyObject *name;
1489 
1490     if (PyTuple_GET_SIZE(args) < 1) {
1491         PyErr_SetString(PyExc_TypeError, "methodcaller needs at least "
1492                         "one argument, the method name");
1493         return NULL;
1494     }
1495 
1496     name = PyTuple_GET_ITEM(args, 0);
1497     if (!PyUnicode_Check(name)) {
1498         PyErr_SetString(PyExc_TypeError,
1499                         "method name must be a string");
1500         return NULL;
1501     }
1502 
1503     _operator_state *state = PyType_GetModuleState(type);
1504     /* create methodcallerobject structure */
1505     mc = PyObject_GC_New(methodcallerobject, (PyTypeObject *)state->methodcaller_type);
1506     if (mc == NULL) {
1507         return NULL;
1508     }
1509 
1510     name = PyTuple_GET_ITEM(args, 0);
1511     Py_INCREF(name);
1512     PyUnicode_InternInPlace(&name);
1513     mc->name = name;
1514 
1515     Py_XINCREF(kwds);
1516     mc->kwds = kwds;
1517 
1518     mc->args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
1519     if (mc->args == NULL) {
1520         Py_DECREF(mc);
1521         return NULL;
1522     }
1523 
1524     PyObject_GC_Track(mc);
1525     return (PyObject *)mc;
1526 }
1527 
1528 static int
methodcaller_clear(methodcallerobject * mc)1529 methodcaller_clear(methodcallerobject *mc)
1530 {
1531     Py_CLEAR(mc->name);
1532     Py_CLEAR(mc->args);
1533     Py_CLEAR(mc->kwds);
1534     return 0;
1535 }
1536 
1537 static void
methodcaller_dealloc(methodcallerobject * mc)1538 methodcaller_dealloc(methodcallerobject *mc)
1539 {
1540     PyTypeObject *tp = Py_TYPE(mc);
1541     PyObject_GC_UnTrack(mc);
1542     (void)methodcaller_clear(mc);
1543     tp->tp_free(mc);
1544     Py_DECREF(tp);
1545 }
1546 
1547 static int
methodcaller_traverse(methodcallerobject * mc,visitproc visit,void * arg)1548 methodcaller_traverse(methodcallerobject *mc, visitproc visit, void *arg)
1549 {
1550     Py_VISIT(mc->name);
1551     Py_VISIT(mc->args);
1552     Py_VISIT(mc->kwds);
1553     Py_VISIT(Py_TYPE(mc));
1554     return 0;
1555 }
1556 
1557 static PyObject *
methodcaller_call(methodcallerobject * mc,PyObject * args,PyObject * kw)1558 methodcaller_call(methodcallerobject *mc, PyObject *args, PyObject *kw)
1559 {
1560     PyObject *method, *obj, *result;
1561 
1562     if (!_PyArg_NoKeywords("methodcaller", kw))
1563         return NULL;
1564     if (!_PyArg_CheckPositional("methodcaller", PyTuple_GET_SIZE(args), 1, 1))
1565         return NULL;
1566     obj = PyTuple_GET_ITEM(args, 0);
1567     method = PyObject_GetAttr(obj, mc->name);
1568     if (method == NULL)
1569         return NULL;
1570     result = PyObject_Call(method, mc->args, mc->kwds);
1571     Py_DECREF(method);
1572     return result;
1573 }
1574 
1575 static PyObject *
methodcaller_repr(methodcallerobject * mc)1576 methodcaller_repr(methodcallerobject *mc)
1577 {
1578     PyObject *argreprs, *repr = NULL, *sep, *joinedargreprs;
1579     Py_ssize_t numtotalargs, numposargs, numkwdargs, i;
1580     int status = Py_ReprEnter((PyObject *)mc);
1581     if (status != 0) {
1582         if (status < 0)
1583             return NULL;
1584         return PyUnicode_FromFormat("%s(...)", Py_TYPE(mc)->tp_name);
1585     }
1586 
1587     numkwdargs = mc->kwds != NULL ? PyDict_GET_SIZE(mc->kwds) : 0;
1588     numposargs = PyTuple_GET_SIZE(mc->args);
1589     numtotalargs = numposargs + numkwdargs;
1590 
1591     if (numtotalargs == 0) {
1592         repr = PyUnicode_FromFormat("%s(%R)", Py_TYPE(mc)->tp_name, mc->name);
1593         Py_ReprLeave((PyObject *)mc);
1594         return repr;
1595     }
1596 
1597     argreprs = PyTuple_New(numtotalargs);
1598     if (argreprs == NULL) {
1599         Py_ReprLeave((PyObject *)mc);
1600         return NULL;
1601     }
1602 
1603     for (i = 0; i < numposargs; ++i) {
1604         PyObject *onerepr = PyObject_Repr(PyTuple_GET_ITEM(mc->args, i));
1605         if (onerepr == NULL)
1606             goto done;
1607         PyTuple_SET_ITEM(argreprs, i, onerepr);
1608     }
1609 
1610     if (numkwdargs != 0) {
1611         PyObject *key, *value;
1612         Py_ssize_t pos = 0;
1613         while (PyDict_Next(mc->kwds, &pos, &key, &value)) {
1614             PyObject *onerepr = PyUnicode_FromFormat("%U=%R", key, value);
1615             if (onerepr == NULL)
1616                 goto done;
1617             if (i >= numtotalargs) {
1618                 i = -1;
1619                 Py_DECREF(onerepr);
1620                 break;
1621             }
1622             PyTuple_SET_ITEM(argreprs, i, onerepr);
1623             ++i;
1624         }
1625         if (i != numtotalargs) {
1626             PyErr_SetString(PyExc_RuntimeError,
1627                             "keywords dict changed size during iteration");
1628             goto done;
1629         }
1630     }
1631 
1632     sep = PyUnicode_FromString(", ");
1633     if (sep == NULL)
1634         goto done;
1635 
1636     joinedargreprs = PyUnicode_Join(sep, argreprs);
1637     Py_DECREF(sep);
1638     if (joinedargreprs == NULL)
1639         goto done;
1640 
1641     repr = PyUnicode_FromFormat("%s(%R, %U)", Py_TYPE(mc)->tp_name,
1642                                 mc->name, joinedargreprs);
1643     Py_DECREF(joinedargreprs);
1644 
1645 done:
1646     Py_DECREF(argreprs);
1647     Py_ReprLeave((PyObject *)mc);
1648     return repr;
1649 }
1650 
1651 static PyObject *
methodcaller_reduce(methodcallerobject * mc,PyObject * Py_UNUSED (ignored))1652 methodcaller_reduce(methodcallerobject *mc, PyObject *Py_UNUSED(ignored))
1653 {
1654     PyObject *newargs;
1655     if (!mc->kwds || PyDict_GET_SIZE(mc->kwds) == 0) {
1656         Py_ssize_t i;
1657         Py_ssize_t callargcount = PyTuple_GET_SIZE(mc->args);
1658         newargs = PyTuple_New(1 + callargcount);
1659         if (newargs == NULL)
1660             return NULL;
1661         Py_INCREF(mc->name);
1662         PyTuple_SET_ITEM(newargs, 0, mc->name);
1663         for (i = 0; i < callargcount; ++i) {
1664             PyObject *arg = PyTuple_GET_ITEM(mc->args, i);
1665             Py_INCREF(arg);
1666             PyTuple_SET_ITEM(newargs, i + 1, arg);
1667         }
1668         return Py_BuildValue("ON", Py_TYPE(mc), newargs);
1669     }
1670     else {
1671         PyObject *functools;
1672         PyObject *partial;
1673         PyObject *constructor;
1674         PyObject *newargs[2];
1675 
1676         _Py_IDENTIFIER(partial);
1677         functools = PyImport_ImportModule("functools");
1678         if (!functools)
1679             return NULL;
1680         partial = _PyObject_GetAttrId(functools, &PyId_partial);
1681         Py_DECREF(functools);
1682         if (!partial)
1683             return NULL;
1684 
1685         newargs[0] = (PyObject *)Py_TYPE(mc);
1686         newargs[1] = mc->name;
1687         constructor = PyObject_VectorcallDict(partial, newargs, 2, mc->kwds);
1688 
1689         Py_DECREF(partial);
1690         return Py_BuildValue("NO", constructor, mc->args);
1691     }
1692 }
1693 
1694 static PyMethodDef methodcaller_methods[] = {
1695     {"__reduce__", (PyCFunction)methodcaller_reduce, METH_NOARGS,
1696      reduce_doc},
1697     {NULL}
1698 };
1699 PyDoc_STRVAR(methodcaller_doc,
1700 "methodcaller(name, ...) --> methodcaller object\n\
1701 \n\
1702 Return a callable object that calls the given method on its operand.\n\
1703 After f = methodcaller('name'), the call f(r) returns r.name().\n\
1704 After g = methodcaller('name', 'date', foo=1), the call g(r) returns\n\
1705 r.name('date', foo=1).");
1706 
1707 static PyType_Slot methodcaller_type_slots[] = {
1708     {Py_tp_doc, (void *)methodcaller_doc},
1709     {Py_tp_dealloc, methodcaller_dealloc},
1710     {Py_tp_call, methodcaller_call},
1711     {Py_tp_traverse, methodcaller_traverse},
1712     {Py_tp_clear, methodcaller_clear},
1713     {Py_tp_methods, methodcaller_methods},
1714     {Py_tp_new, methodcaller_new},
1715     {Py_tp_getattro, PyObject_GenericGetAttr},
1716     {Py_tp_repr, methodcaller_repr},
1717     {0, 0}
1718 };
1719 
1720 static PyType_Spec methodcaller_type_spec = {
1721     .name = "operator.methodcaller",
1722     .basicsize = sizeof(methodcallerobject),
1723     .itemsize = 0,
1724     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1725               Py_TPFLAGS_IMMUTABLETYPE),
1726     .slots = methodcaller_type_slots,
1727 };
1728 
1729 static int
operator_exec(PyObject * module)1730 operator_exec(PyObject *module)
1731 {
1732     _operator_state *state = get_operator_state(module);
1733     state->attrgetter_type = PyType_FromModuleAndSpec(module, &attrgetter_type_spec, NULL);
1734     if (state->attrgetter_type == NULL) {
1735         return -1;
1736     }
1737     if (PyModule_AddType(module, (PyTypeObject *)state->attrgetter_type) < 0) {
1738         return -1;
1739     }
1740 
1741     state->itemgetter_type = PyType_FromModuleAndSpec(module, &itemgetter_type_spec, NULL);
1742     if (state->itemgetter_type == NULL) {
1743         return -1;
1744     }
1745     if (PyModule_AddType(module, (PyTypeObject *)state->itemgetter_type) < 0) {
1746         return -1;
1747     }
1748 
1749     state->methodcaller_type = PyType_FromModuleAndSpec(module, &methodcaller_type_spec, NULL);
1750     if (state->methodcaller_type == NULL) {
1751         return -1;
1752     }
1753     if (PyModule_AddType(module, (PyTypeObject *)state->methodcaller_type) < 0) {
1754         return -1;
1755     }
1756 
1757     return 0;
1758 }
1759 
1760 
1761 static struct PyModuleDef_Slot operator_slots[] = {
1762     {Py_mod_exec, operator_exec},
1763     {0, NULL}
1764 };
1765 
1766 static int
operator_traverse(PyObject * module,visitproc visit,void * arg)1767 operator_traverse(PyObject *module, visitproc visit, void *arg)
1768 {
1769     _operator_state *state = get_operator_state(module);
1770     Py_VISIT(state->attrgetter_type);
1771     Py_VISIT(state->itemgetter_type);
1772     Py_VISIT(state->methodcaller_type);
1773     return 0;
1774 }
1775 
1776 static int
operator_clear(PyObject * module)1777 operator_clear(PyObject *module)
1778 {
1779     _operator_state *state = get_operator_state(module);
1780     Py_CLEAR(state->attrgetter_type);
1781     Py_CLEAR(state->itemgetter_type);
1782     Py_CLEAR(state->methodcaller_type);
1783     return 0;
1784 }
1785 
1786 static void
operator_free(void * module)1787 operator_free(void *module)
1788 {
1789     operator_clear((PyObject *)module);
1790 }
1791 
1792 static struct PyModuleDef operatormodule = {
1793     PyModuleDef_HEAD_INIT,
1794     .m_name = "_operator",
1795     .m_doc = operator_doc,
1796     .m_size = sizeof(_operator_state),
1797     .m_methods = operator_methods,
1798     .m_slots = operator_slots,
1799     .m_traverse = operator_traverse,
1800     .m_clear = operator_clear,
1801     .m_free = operator_free,
1802 };
1803 
1804 PyMODINIT_FUNC
PyInit__operator(void)1805 PyInit__operator(void)
1806 {
1807     return PyModuleDef_Init(&operatormodule);
1808 }
1809