You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1226 lines
27 KiB

  1. #include "Python.h"
  2. #include "structmember.h"
  3. #include "internal/pystate.h"
  4. #include "internal/context.h"
  5. #include "internal/hamt.h"
  6. #define CONTEXT_FREELIST_MAXLEN 255
  7. static PyContext *ctx_freelist = NULL;
  8. static Py_ssize_t ctx_freelist_len = 0;
  9. #include "clinic/context.c.h"
  10. /*[clinic input]
  11. module _contextvars
  12. [clinic start generated code]*/
  13. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=a0955718c8b8cea6]*/
  14. /////////////////////////// Context API
  15. static PyContext *
  16. context_new_empty(void);
  17. static PyContext *
  18. context_new_from_vars(PyHamtObject *vars);
  19. static inline PyContext *
  20. context_get(void);
  21. static PyContextToken *
  22. token_new(PyContext *ctx, PyContextVar *var, PyObject *val);
  23. static PyContextVar *
  24. contextvar_new(PyObject *name, PyObject *def);
  25. static int
  26. contextvar_set(PyContextVar *var, PyObject *val);
  27. static int
  28. contextvar_del(PyContextVar *var);
  29. PyObject *
  30. _PyContext_NewHamtForTests(void)
  31. {
  32. return (PyObject *)_PyHamt_New();
  33. }
  34. PyContext *
  35. PyContext_New(void)
  36. {
  37. return context_new_empty();
  38. }
  39. PyContext *
  40. PyContext_Copy(PyContext * ctx)
  41. {
  42. return context_new_from_vars(ctx->ctx_vars);
  43. }
  44. PyContext *
  45. PyContext_CopyCurrent(void)
  46. {
  47. PyContext *ctx = context_get();
  48. if (ctx == NULL) {
  49. return NULL;
  50. }
  51. return context_new_from_vars(ctx->ctx_vars);
  52. }
  53. int
  54. PyContext_Enter(PyContext *ctx)
  55. {
  56. if (ctx->ctx_entered) {
  57. PyErr_Format(PyExc_RuntimeError,
  58. "cannot enter context: %R is already entered", ctx);
  59. return -1;
  60. }
  61. PyThreadState *ts = PyThreadState_GET();
  62. assert(ts != NULL);
  63. ctx->ctx_prev = (PyContext *)ts->context; /* borrow */
  64. ctx->ctx_entered = 1;
  65. Py_INCREF(ctx);
  66. ts->context = (PyObject *)ctx;
  67. ts->context_ver++;
  68. return 0;
  69. }
  70. int
  71. PyContext_Exit(PyContext *ctx)
  72. {
  73. if (!ctx->ctx_entered) {
  74. PyErr_Format(PyExc_RuntimeError,
  75. "cannot exit context: %R has not been entered", ctx);
  76. return -1;
  77. }
  78. PyThreadState *ts = PyThreadState_GET();
  79. assert(ts != NULL);
  80. if (ts->context != (PyObject *)ctx) {
  81. /* Can only happen if someone misuses the C API */
  82. PyErr_SetString(PyExc_RuntimeError,
  83. "cannot exit context: thread state references "
  84. "a different context object");
  85. return -1;
  86. }
  87. Py_SETREF(ts->context, (PyObject *)ctx->ctx_prev);
  88. ts->context_ver++;
  89. ctx->ctx_prev = NULL;
  90. ctx->ctx_entered = 0;
  91. return 0;
  92. }
  93. PyContextVar *
  94. PyContextVar_New(const char *name, PyObject *def)
  95. {
  96. PyObject *pyname = PyUnicode_FromString(name);
  97. if (pyname == NULL) {
  98. return NULL;
  99. }
  100. PyContextVar *var = contextvar_new(pyname, def);
  101. Py_DECREF(pyname);
  102. return var;
  103. }
  104. int
  105. PyContextVar_Get(PyContextVar *var, PyObject *def, PyObject **val)
  106. {
  107. assert(PyContextVar_CheckExact(var));
  108. PyThreadState *ts = PyThreadState_GET();
  109. assert(ts != NULL);
  110. if (ts->context == NULL) {
  111. goto not_found;
  112. }
  113. if (var->var_cached != NULL &&
  114. var->var_cached_tsid == ts->id &&
  115. var->var_cached_tsver == ts->context_ver)
  116. {
  117. *val = var->var_cached;
  118. goto found;
  119. }
  120. assert(PyContext_CheckExact(ts->context));
  121. PyHamtObject *vars = ((PyContext *)ts->context)->ctx_vars;
  122. PyObject *found = NULL;
  123. int res = _PyHamt_Find(vars, (PyObject*)var, &found);
  124. if (res < 0) {
  125. goto error;
  126. }
  127. if (res == 1) {
  128. assert(found != NULL);
  129. var->var_cached = found; /* borrow */
  130. var->var_cached_tsid = ts->id;
  131. var->var_cached_tsver = ts->context_ver;
  132. *val = found;
  133. goto found;
  134. }
  135. not_found:
  136. if (def == NULL) {
  137. if (var->var_default != NULL) {
  138. *val = var->var_default;
  139. goto found;
  140. }
  141. *val = NULL;
  142. goto found;
  143. }
  144. else {
  145. *val = def;
  146. goto found;
  147. }
  148. found:
  149. Py_XINCREF(*val);
  150. return 0;
  151. error:
  152. *val = NULL;
  153. return -1;
  154. }
  155. PyContextToken *
  156. PyContextVar_Set(PyContextVar *var, PyObject *val)
  157. {
  158. if (!PyContextVar_CheckExact(var)) {
  159. PyErr_SetString(
  160. PyExc_TypeError, "an instance of ContextVar was expected");
  161. return NULL;
  162. }
  163. PyContext *ctx = context_get();
  164. if (ctx == NULL) {
  165. return NULL;
  166. }
  167. PyObject *old_val = NULL;
  168. int found = _PyHamt_Find(ctx->ctx_vars, (PyObject *)var, &old_val);
  169. if (found < 0) {
  170. return NULL;
  171. }
  172. Py_XINCREF(old_val);
  173. PyContextToken *tok = token_new(ctx, var, old_val);
  174. Py_XDECREF(old_val);
  175. if (contextvar_set(var, val)) {
  176. Py_DECREF(tok);
  177. return NULL;
  178. }
  179. return tok;
  180. }
  181. int
  182. PyContextVar_Reset(PyContextVar *var, PyContextToken *tok)
  183. {
  184. if (tok->tok_used) {
  185. PyErr_Format(PyExc_RuntimeError,
  186. "%R has already been used once", tok);
  187. return -1;
  188. }
  189. if (var != tok->tok_var) {
  190. PyErr_Format(PyExc_ValueError,
  191. "%R was created by a different ContextVar", tok);
  192. return -1;
  193. }
  194. PyContext *ctx = context_get();
  195. if (ctx != tok->tok_ctx) {
  196. PyErr_Format(PyExc_ValueError,
  197. "%R was created in a different Context", tok);
  198. return -1;
  199. }
  200. tok->tok_used = 1;
  201. if (tok->tok_oldval == NULL) {
  202. return contextvar_del(var);
  203. }
  204. else {
  205. return contextvar_set(var, tok->tok_oldval);
  206. }
  207. }
  208. /////////////////////////// PyContext
  209. /*[clinic input]
  210. class _contextvars.Context "PyContext *" "&PyContext_Type"
  211. [clinic start generated code]*/
  212. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdf87f8e0cb580e8]*/
  213. static inline PyContext *
  214. _context_alloc(void)
  215. {
  216. PyContext *ctx;
  217. if (ctx_freelist_len) {
  218. ctx_freelist_len--;
  219. ctx = ctx_freelist;
  220. ctx_freelist = (PyContext *)ctx->ctx_weakreflist;
  221. ctx->ctx_weakreflist = NULL;
  222. _Py_NewReference((PyObject *)ctx);
  223. }
  224. else {
  225. ctx = PyObject_GC_New(PyContext, &PyContext_Type);
  226. if (ctx == NULL) {
  227. return NULL;
  228. }
  229. }
  230. ctx->ctx_vars = NULL;
  231. ctx->ctx_prev = NULL;
  232. ctx->ctx_entered = 0;
  233. ctx->ctx_weakreflist = NULL;
  234. return ctx;
  235. }
  236. static PyContext *
  237. context_new_empty(void)
  238. {
  239. PyContext *ctx = _context_alloc();
  240. if (ctx == NULL) {
  241. return NULL;
  242. }
  243. ctx->ctx_vars = _PyHamt_New();
  244. if (ctx->ctx_vars == NULL) {
  245. Py_DECREF(ctx);
  246. return NULL;
  247. }
  248. _PyObject_GC_TRACK(ctx);
  249. return ctx;
  250. }
  251. static PyContext *
  252. context_new_from_vars(PyHamtObject *vars)
  253. {
  254. PyContext *ctx = _context_alloc();
  255. if (ctx == NULL) {
  256. return NULL;
  257. }
  258. Py_INCREF(vars);
  259. ctx->ctx_vars = vars;
  260. _PyObject_GC_TRACK(ctx);
  261. return ctx;
  262. }
  263. static inline PyContext *
  264. context_get(void)
  265. {
  266. PyThreadState *ts = PyThreadState_GET();
  267. assert(ts != NULL);
  268. PyContext *current_ctx = (PyContext *)ts->context;
  269. if (current_ctx == NULL) {
  270. current_ctx = context_new_empty();
  271. if (current_ctx == NULL) {
  272. return NULL;
  273. }
  274. ts->context = (PyObject *)current_ctx;
  275. }
  276. return current_ctx;
  277. }
  278. static int
  279. context_check_key_type(PyObject *key)
  280. {
  281. if (!PyContextVar_CheckExact(key)) {
  282. // abort();
  283. PyErr_Format(PyExc_TypeError,
  284. "a ContextVar key was expected, got %R", key);
  285. return -1;
  286. }
  287. return 0;
  288. }
  289. static PyObject *
  290. context_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  291. {
  292. if (PyTuple_Size(args) || (kwds != NULL && PyDict_Size(kwds))) {
  293. PyErr_SetString(
  294. PyExc_TypeError, "Context() does not accept any arguments");
  295. return NULL;
  296. }
  297. return (PyObject *)PyContext_New();
  298. }
  299. static int
  300. context_tp_clear(PyContext *self)
  301. {
  302. Py_CLEAR(self->ctx_prev);
  303. Py_CLEAR(self->ctx_vars);
  304. return 0;
  305. }
  306. static int
  307. context_tp_traverse(PyContext *self, visitproc visit, void *arg)
  308. {
  309. Py_VISIT(self->ctx_prev);
  310. Py_VISIT(self->ctx_vars);
  311. return 0;
  312. }
  313. static void
  314. context_tp_dealloc(PyContext *self)
  315. {
  316. _PyObject_GC_UNTRACK(self);
  317. if (self->ctx_weakreflist != NULL) {
  318. PyObject_ClearWeakRefs((PyObject*)self);
  319. }
  320. (void)context_tp_clear(self);
  321. if (ctx_freelist_len < CONTEXT_FREELIST_MAXLEN) {
  322. ctx_freelist_len++;
  323. self->ctx_weakreflist = (PyObject *)ctx_freelist;
  324. ctx_freelist = self;
  325. }
  326. else {
  327. Py_TYPE(self)->tp_free(self);
  328. }
  329. }
  330. static PyObject *
  331. context_tp_iter(PyContext *self)
  332. {
  333. return _PyHamt_NewIterKeys(self->ctx_vars);
  334. }
  335. static PyObject *
  336. context_tp_richcompare(PyObject *v, PyObject *w, int op)
  337. {
  338. if (!PyContext_CheckExact(v) || !PyContext_CheckExact(w) ||
  339. (op != Py_EQ && op != Py_NE))
  340. {
  341. Py_RETURN_NOTIMPLEMENTED;
  342. }
  343. int res = _PyHamt_Eq(
  344. ((PyContext *)v)->ctx_vars, ((PyContext *)w)->ctx_vars);
  345. if (res < 0) {
  346. return NULL;
  347. }
  348. if (op == Py_NE) {
  349. res = !res;
  350. }
  351. if (res) {
  352. Py_RETURN_TRUE;
  353. }
  354. else {
  355. Py_RETURN_FALSE;
  356. }
  357. }
  358. static Py_ssize_t
  359. context_tp_len(PyContext *self)
  360. {
  361. return _PyHamt_Len(self->ctx_vars);
  362. }
  363. static PyObject *
  364. context_tp_subscript(PyContext *self, PyObject *key)
  365. {
  366. if (context_check_key_type(key)) {
  367. return NULL;
  368. }
  369. PyObject *val = NULL;
  370. int found = _PyHamt_Find(self->ctx_vars, key, &val);
  371. if (found < 0) {
  372. return NULL;
  373. }
  374. if (found == 0) {
  375. PyErr_SetObject(PyExc_KeyError, key);
  376. return NULL;
  377. }
  378. Py_INCREF(val);
  379. return val;
  380. }
  381. static int
  382. context_tp_contains(PyContext *self, PyObject *key)
  383. {
  384. if (context_check_key_type(key)) {
  385. return -1;
  386. }
  387. PyObject *val = NULL;
  388. return _PyHamt_Find(self->ctx_vars, key, &val);
  389. }
  390. /*[clinic input]
  391. _contextvars.Context.get
  392. key: object
  393. default: object = None
  394. /
  395. [clinic start generated code]*/
  396. static PyObject *
  397. _contextvars_Context_get_impl(PyContext *self, PyObject *key,
  398. PyObject *default_value)
  399. /*[clinic end generated code: output=0c54aa7664268189 input=8d4c33c8ecd6d769]*/
  400. {
  401. if (context_check_key_type(key)) {
  402. return NULL;
  403. }
  404. PyObject *val = NULL;
  405. int found = _PyHamt_Find(self->ctx_vars, key, &val);
  406. if (found < 0) {
  407. return NULL;
  408. }
  409. if (found == 0) {
  410. Py_INCREF(default_value);
  411. return default_value;
  412. }
  413. Py_INCREF(val);
  414. return val;
  415. }
  416. /*[clinic input]
  417. _contextvars.Context.items
  418. [clinic start generated code]*/
  419. static PyObject *
  420. _contextvars_Context_items_impl(PyContext *self)
  421. /*[clinic end generated code: output=fa1655c8a08502af input=2d570d1455004979]*/
  422. {
  423. return _PyHamt_NewIterItems(self->ctx_vars);
  424. }
  425. /*[clinic input]
  426. _contextvars.Context.keys
  427. [clinic start generated code]*/
  428. static PyObject *
  429. _contextvars_Context_keys_impl(PyContext *self)
  430. /*[clinic end generated code: output=177227c6b63ec0e2 input=13005e142fbbf37d]*/
  431. {
  432. return _PyHamt_NewIterKeys(self->ctx_vars);
  433. }
  434. /*[clinic input]
  435. _contextvars.Context.values
  436. [clinic start generated code]*/
  437. static PyObject *
  438. _contextvars_Context_values_impl(PyContext *self)
  439. /*[clinic end generated code: output=d286dabfc8db6dde input=c2cbc40a4470e905]*/
  440. {
  441. return _PyHamt_NewIterValues(self->ctx_vars);
  442. }
  443. /*[clinic input]
  444. _contextvars.Context.copy
  445. [clinic start generated code]*/
  446. static PyObject *
  447. _contextvars_Context_copy_impl(PyContext *self)
  448. /*[clinic end generated code: output=30ba8896c4707a15 input=3e3fd72d598653ab]*/
  449. {
  450. return (PyObject *)context_new_from_vars(self->ctx_vars);
  451. }
  452. static PyObject *
  453. context_run(PyContext *self, PyObject *const *args,
  454. Py_ssize_t nargs, PyObject *kwnames)
  455. {
  456. if (nargs < 1) {
  457. PyErr_SetString(PyExc_TypeError,
  458. "run() missing 1 required positional argument");
  459. return NULL;
  460. }
  461. if (PyContext_Enter(self)) {
  462. return NULL;
  463. }
  464. PyObject *call_result = _PyObject_FastCallKeywords(
  465. args[0], args + 1, nargs - 1, kwnames);
  466. if (PyContext_Exit(self)) {
  467. return NULL;
  468. }
  469. return call_result;
  470. }
  471. static PyMethodDef PyContext_methods[] = {
  472. _CONTEXTVARS_CONTEXT_GET_METHODDEF
  473. _CONTEXTVARS_CONTEXT_ITEMS_METHODDEF
  474. _CONTEXTVARS_CONTEXT_KEYS_METHODDEF
  475. _CONTEXTVARS_CONTEXT_VALUES_METHODDEF
  476. _CONTEXTVARS_CONTEXT_COPY_METHODDEF
  477. {"run", (PyCFunction)context_run, METH_FASTCALL | METH_KEYWORDS, NULL},
  478. {NULL, NULL}
  479. };
  480. static PySequenceMethods PyContext_as_sequence = {
  481. 0, /* sq_length */
  482. 0, /* sq_concat */
  483. 0, /* sq_repeat */
  484. 0, /* sq_item */
  485. 0, /* sq_slice */
  486. 0, /* sq_ass_item */
  487. 0, /* sq_ass_slice */
  488. (objobjproc)context_tp_contains, /* sq_contains */
  489. 0, /* sq_inplace_concat */
  490. 0, /* sq_inplace_repeat */
  491. };
  492. static PyMappingMethods PyContext_as_mapping = {
  493. (lenfunc)context_tp_len, /* mp_length */
  494. (binaryfunc)context_tp_subscript, /* mp_subscript */
  495. };
  496. PyTypeObject PyContext_Type = {
  497. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  498. "Context",
  499. sizeof(PyContext),
  500. .tp_methods = PyContext_methods,
  501. .tp_as_mapping = &PyContext_as_mapping,
  502. .tp_as_sequence = &PyContext_as_sequence,
  503. .tp_iter = (getiterfunc)context_tp_iter,
  504. .tp_dealloc = (destructor)context_tp_dealloc,
  505. .tp_getattro = PyObject_GenericGetAttr,
  506. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  507. .tp_richcompare = context_tp_richcompare,
  508. .tp_traverse = (traverseproc)context_tp_traverse,
  509. .tp_clear = (inquiry)context_tp_clear,
  510. .tp_new = context_tp_new,
  511. .tp_weaklistoffset = offsetof(PyContext, ctx_weakreflist),
  512. .tp_hash = PyObject_HashNotImplemented,
  513. };
  514. /////////////////////////// ContextVar
  515. static int
  516. contextvar_set(PyContextVar *var, PyObject *val)
  517. {
  518. var->var_cached = NULL;
  519. PyThreadState *ts = PyThreadState_Get();
  520. PyContext *ctx = context_get();
  521. if (ctx == NULL) {
  522. return -1;
  523. }
  524. PyHamtObject *new_vars = _PyHamt_Assoc(
  525. ctx->ctx_vars, (PyObject *)var, val);
  526. if (new_vars == NULL) {
  527. return -1;
  528. }
  529. Py_SETREF(ctx->ctx_vars, new_vars);
  530. var->var_cached = val; /* borrow */
  531. var->var_cached_tsid = ts->id;
  532. var->var_cached_tsver = ts->context_ver;
  533. return 0;
  534. }
  535. static int
  536. contextvar_del(PyContextVar *var)
  537. {
  538. var->var_cached = NULL;
  539. PyContext *ctx = context_get();
  540. if (ctx == NULL) {
  541. return -1;
  542. }
  543. PyHamtObject *vars = ctx->ctx_vars;
  544. PyHamtObject *new_vars = _PyHamt_Without(vars, (PyObject *)var);
  545. if (new_vars == NULL) {
  546. return -1;
  547. }
  548. if (vars == new_vars) {
  549. Py_DECREF(new_vars);
  550. PyErr_SetObject(PyExc_LookupError, (PyObject *)var);
  551. return -1;
  552. }
  553. Py_SETREF(ctx->ctx_vars, new_vars);
  554. return 0;
  555. }
  556. static Py_hash_t
  557. contextvar_generate_hash(void *addr, PyObject *name)
  558. {
  559. /* Take hash of `name` and XOR it with the object's addr.
  560. The structure of the tree is encoded in objects' hashes, which
  561. means that sufficiently similar hashes would result in tall trees
  562. with many Collision nodes. Which would, in turn, result in slower
  563. get and set operations.
  564. The XORing helps to ensure that:
  565. (1) sequentially allocated ContextVar objects have
  566. different hashes;
  567. (2) context variables with equal names have
  568. different hashes.
  569. */
  570. Py_hash_t name_hash = PyObject_Hash(name);
  571. if (name_hash == -1) {
  572. return -1;
  573. }
  574. Py_hash_t res = _Py_HashPointer(addr) ^ name_hash;
  575. return res == -1 ? -2 : res;
  576. }
  577. static PyContextVar *
  578. contextvar_new(PyObject *name, PyObject *def)
  579. {
  580. if (!PyUnicode_Check(name)) {
  581. PyErr_SetString(PyExc_TypeError,
  582. "context variable name must be a str");
  583. return NULL;
  584. }
  585. PyContextVar *var = PyObject_GC_New(PyContextVar, &PyContextVar_Type);
  586. if (var == NULL) {
  587. return NULL;
  588. }
  589. var->var_hash = contextvar_generate_hash(var, name);
  590. if (var->var_hash == -1) {
  591. Py_DECREF(var);
  592. return NULL;
  593. }
  594. Py_INCREF(name);
  595. var->var_name = name;
  596. Py_XINCREF(def);
  597. var->var_default = def;
  598. var->var_cached = NULL;
  599. var->var_cached_tsid = 0;
  600. var->var_cached_tsver = 0;
  601. if (_PyObject_GC_MAY_BE_TRACKED(name) ||
  602. (def != NULL && _PyObject_GC_MAY_BE_TRACKED(def)))
  603. {
  604. PyObject_GC_Track(var);
  605. }
  606. return var;
  607. }
  608. /*[clinic input]
  609. class _contextvars.ContextVar "PyContextVar *" "&PyContextVar_Type"
  610. [clinic start generated code]*/
  611. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=445da935fa8883c3]*/
  612. static PyObject *
  613. contextvar_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  614. {
  615. static char *kwlist[] = {"", "default", NULL};
  616. PyObject *name;
  617. PyObject *def = NULL;
  618. if (!PyArg_ParseTupleAndKeywords(
  619. args, kwds, "O|$O:ContextVar", kwlist, &name, &def))
  620. {
  621. return NULL;
  622. }
  623. return (PyObject *)contextvar_new(name, def);
  624. }
  625. static int
  626. contextvar_tp_clear(PyContextVar *self)
  627. {
  628. Py_CLEAR(self->var_name);
  629. Py_CLEAR(self->var_default);
  630. self->var_cached = NULL;
  631. self->var_cached_tsid = 0;
  632. self->var_cached_tsver = 0;
  633. return 0;
  634. }
  635. static int
  636. contextvar_tp_traverse(PyContextVar *self, visitproc visit, void *arg)
  637. {
  638. Py_VISIT(self->var_name);
  639. Py_VISIT(self->var_default);
  640. return 0;
  641. }
  642. static void
  643. contextvar_tp_dealloc(PyContextVar *self)
  644. {
  645. PyObject_GC_UnTrack(self);
  646. (void)contextvar_tp_clear(self);
  647. Py_TYPE(self)->tp_free(self);
  648. }
  649. static Py_hash_t
  650. contextvar_tp_hash(PyContextVar *self)
  651. {
  652. return self->var_hash;
  653. }
  654. static PyObject *
  655. contextvar_tp_repr(PyContextVar *self)
  656. {
  657. _PyUnicodeWriter writer;
  658. _PyUnicodeWriter_Init(&writer);
  659. if (_PyUnicodeWriter_WriteASCIIString(
  660. &writer, "<ContextVar name=", 17) < 0)
  661. {
  662. goto error;
  663. }
  664. PyObject *name = PyObject_Repr(self->var_name);
  665. if (name == NULL) {
  666. goto error;
  667. }
  668. if (_PyUnicodeWriter_WriteStr(&writer, name) < 0) {
  669. Py_DECREF(name);
  670. goto error;
  671. }
  672. Py_DECREF(name);
  673. if (self->var_default != NULL) {
  674. if (_PyUnicodeWriter_WriteASCIIString(&writer, " default=", 9) < 0) {
  675. goto error;
  676. }
  677. PyObject *def = PyObject_Repr(self->var_default);
  678. if (def == NULL) {
  679. goto error;
  680. }
  681. if (_PyUnicodeWriter_WriteStr(&writer, def) < 0) {
  682. Py_DECREF(def);
  683. goto error;
  684. }
  685. Py_DECREF(def);
  686. }
  687. PyObject *addr = PyUnicode_FromFormat(" at %p>", self);
  688. if (addr == NULL) {
  689. goto error;
  690. }
  691. if (_PyUnicodeWriter_WriteStr(&writer, addr) < 0) {
  692. Py_DECREF(addr);
  693. goto error;
  694. }
  695. Py_DECREF(addr);
  696. return _PyUnicodeWriter_Finish(&writer);
  697. error:
  698. _PyUnicodeWriter_Dealloc(&writer);
  699. return NULL;
  700. }
  701. /*[clinic input]
  702. _contextvars.ContextVar.get
  703. default: object = NULL
  704. /
  705. [clinic start generated code]*/
  706. static PyObject *
  707. _contextvars_ContextVar_get_impl(PyContextVar *self, PyObject *default_value)
  708. /*[clinic end generated code: output=0746bd0aa2ced7bf input=8d002b02eebbb247]*/
  709. {
  710. if (!PyContextVar_CheckExact(self)) {
  711. PyErr_SetString(
  712. PyExc_TypeError, "an instance of ContextVar was expected");
  713. return NULL;
  714. }
  715. PyObject *val;
  716. if (PyContextVar_Get(self, default_value, &val) < 0) {
  717. return NULL;
  718. }
  719. if (val == NULL) {
  720. PyErr_SetObject(PyExc_LookupError, (PyObject *)self);
  721. return NULL;
  722. }
  723. return val;
  724. }
  725. /*[clinic input]
  726. _contextvars.ContextVar.set
  727. value: object
  728. /
  729. [clinic start generated code]*/
  730. static PyObject *
  731. _contextvars_ContextVar_set(PyContextVar *self, PyObject *value)
  732. /*[clinic end generated code: output=446ed5e820d6d60b input=a2d88f57c6d86f7c]*/
  733. {
  734. return (PyObject *)PyContextVar_Set(self, value);
  735. }
  736. /*[clinic input]
  737. _contextvars.ContextVar.reset
  738. token: object
  739. /
  740. [clinic start generated code]*/
  741. static PyObject *
  742. _contextvars_ContextVar_reset(PyContextVar *self, PyObject *token)
  743. /*[clinic end generated code: output=d4ee34d0742d62ee input=4c871b6f1f31a65f]*/
  744. {
  745. if (!PyContextToken_CheckExact(token)) {
  746. PyErr_Format(PyExc_TypeError,
  747. "expected an instance of Token, got %R", token);
  748. return NULL;
  749. }
  750. if (PyContextVar_Reset(self, (PyContextToken *)token)) {
  751. return NULL;
  752. }
  753. Py_RETURN_NONE;
  754. }
  755. static PyObject *
  756. contextvar_cls_getitem(PyObject *self, PyObject *args)
  757. {
  758. Py_RETURN_NONE;
  759. }
  760. static PyMethodDef PyContextVar_methods[] = {
  761. _CONTEXTVARS_CONTEXTVAR_GET_METHODDEF
  762. _CONTEXTVARS_CONTEXTVAR_SET_METHODDEF
  763. _CONTEXTVARS_CONTEXTVAR_RESET_METHODDEF
  764. {"__class_getitem__", contextvar_cls_getitem,
  765. METH_VARARGS | METH_STATIC, NULL},
  766. {NULL, NULL}
  767. };
  768. PyTypeObject PyContextVar_Type = {
  769. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  770. "ContextVar",
  771. sizeof(PyContextVar),
  772. .tp_methods = PyContextVar_methods,
  773. .tp_dealloc = (destructor)contextvar_tp_dealloc,
  774. .tp_getattro = PyObject_GenericGetAttr,
  775. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  776. .tp_traverse = (traverseproc)contextvar_tp_traverse,
  777. .tp_clear = (inquiry)contextvar_tp_clear,
  778. .tp_new = contextvar_tp_new,
  779. .tp_free = PyObject_GC_Del,
  780. .tp_hash = (hashfunc)contextvar_tp_hash,
  781. .tp_repr = (reprfunc)contextvar_tp_repr,
  782. };
  783. /////////////////////////// Token
  784. static PyObject * get_token_missing(void);
  785. /*[clinic input]
  786. class _contextvars.Token "PyContextToken *" "&PyContextToken_Type"
  787. [clinic start generated code]*/
  788. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=338a5e2db13d3f5b]*/
  789. static PyObject *
  790. token_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  791. {
  792. PyErr_SetString(PyExc_RuntimeError,
  793. "Tokens can only be created by ContextVars");
  794. return NULL;
  795. }
  796. static int
  797. token_tp_clear(PyContextToken *self)
  798. {
  799. Py_CLEAR(self->tok_ctx);
  800. Py_CLEAR(self->tok_var);
  801. Py_CLEAR(self->tok_oldval);
  802. return 0;
  803. }
  804. static int
  805. token_tp_traverse(PyContextToken *self, visitproc visit, void *arg)
  806. {
  807. Py_VISIT(self->tok_ctx);
  808. Py_VISIT(self->tok_var);
  809. Py_VISIT(self->tok_oldval);
  810. return 0;
  811. }
  812. static void
  813. token_tp_dealloc(PyContextToken *self)
  814. {
  815. PyObject_GC_UnTrack(self);
  816. (void)token_tp_clear(self);
  817. Py_TYPE(self)->tp_free(self);
  818. }
  819. static PyObject *
  820. token_tp_repr(PyContextToken *self)
  821. {
  822. _PyUnicodeWriter writer;
  823. _PyUnicodeWriter_Init(&writer);
  824. if (_PyUnicodeWriter_WriteASCIIString(&writer, "<Token", 6) < 0) {
  825. goto error;
  826. }
  827. if (self->tok_used) {
  828. if (_PyUnicodeWriter_WriteASCIIString(&writer, " used", 5) < 0) {
  829. goto error;
  830. }
  831. }
  832. if (_PyUnicodeWriter_WriteASCIIString(&writer, " var=", 5) < 0) {
  833. goto error;
  834. }
  835. PyObject *var = PyObject_Repr((PyObject *)self->tok_var);
  836. if (var == NULL) {
  837. goto error;
  838. }
  839. if (_PyUnicodeWriter_WriteStr(&writer, var) < 0) {
  840. Py_DECREF(var);
  841. goto error;
  842. }
  843. Py_DECREF(var);
  844. PyObject *addr = PyUnicode_FromFormat(" at %p>", self);
  845. if (addr == NULL) {
  846. goto error;
  847. }
  848. if (_PyUnicodeWriter_WriteStr(&writer, addr) < 0) {
  849. Py_DECREF(addr);
  850. goto error;
  851. }
  852. Py_DECREF(addr);
  853. return _PyUnicodeWriter_Finish(&writer);
  854. error:
  855. _PyUnicodeWriter_Dealloc(&writer);
  856. return NULL;
  857. }
  858. static PyObject *
  859. token_get_var(PyContextToken *self)
  860. {
  861. Py_INCREF(self->tok_var);
  862. return (PyObject *)self->tok_var;
  863. }
  864. static PyObject *
  865. token_get_old_value(PyContextToken *self)
  866. {
  867. if (self->tok_oldval == NULL) {
  868. return get_token_missing();
  869. }
  870. Py_INCREF(self->tok_oldval);
  871. return self->tok_oldval;
  872. }
  873. static PyGetSetDef PyContextTokenType_getsetlist[] = {
  874. {"var", (getter)token_get_var, NULL, NULL},
  875. {"old_value", (getter)token_get_old_value, NULL, NULL},
  876. {NULL}
  877. };
  878. PyTypeObject PyContextToken_Type = {
  879. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  880. "Token",
  881. sizeof(PyContextToken),
  882. .tp_getset = PyContextTokenType_getsetlist,
  883. .tp_dealloc = (destructor)token_tp_dealloc,
  884. .tp_getattro = PyObject_GenericGetAttr,
  885. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  886. .tp_traverse = (traverseproc)token_tp_traverse,
  887. .tp_clear = (inquiry)token_tp_clear,
  888. .tp_new = token_tp_new,
  889. .tp_free = PyObject_GC_Del,
  890. .tp_hash = PyObject_HashNotImplemented,
  891. .tp_repr = (reprfunc)token_tp_repr,
  892. };
  893. static PyContextToken *
  894. token_new(PyContext *ctx, PyContextVar *var, PyObject *val)
  895. {
  896. PyContextToken *tok = PyObject_GC_New(PyContextToken, &PyContextToken_Type);
  897. if (tok == NULL) {
  898. return NULL;
  899. }
  900. Py_INCREF(ctx);
  901. tok->tok_ctx = ctx;
  902. Py_INCREF(var);
  903. tok->tok_var = var;
  904. Py_XINCREF(val);
  905. tok->tok_oldval = val;
  906. tok->tok_used = 0;
  907. PyObject_GC_Track(tok);
  908. return tok;
  909. }
  910. /////////////////////////// Token.MISSING
  911. static PyObject *_token_missing;
  912. typedef struct {
  913. PyObject_HEAD
  914. } PyContextTokenMissing;
  915. static PyObject *
  916. context_token_missing_tp_repr(PyObject *self)
  917. {
  918. return PyUnicode_FromString("<Token.MISSING>");
  919. }
  920. PyTypeObject PyContextTokenMissing_Type = {
  921. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  922. "Token.MISSING",
  923. sizeof(PyContextTokenMissing),
  924. .tp_getattro = PyObject_GenericGetAttr,
  925. .tp_flags = Py_TPFLAGS_DEFAULT,
  926. .tp_repr = context_token_missing_tp_repr,
  927. };
  928. static PyObject *
  929. get_token_missing(void)
  930. {
  931. if (_token_missing != NULL) {
  932. Py_INCREF(_token_missing);
  933. return _token_missing;
  934. }
  935. _token_missing = (PyObject *)PyObject_New(
  936. PyContextTokenMissing, &PyContextTokenMissing_Type);
  937. if (_token_missing == NULL) {
  938. return NULL;
  939. }
  940. Py_INCREF(_token_missing);
  941. return _token_missing;
  942. }
  943. ///////////////////////////
  944. int
  945. PyContext_ClearFreeList(void)
  946. {
  947. Py_ssize_t size = ctx_freelist_len;
  948. while (ctx_freelist_len) {
  949. PyContext *ctx = ctx_freelist;
  950. ctx_freelist = (PyContext *)ctx->ctx_weakreflist;
  951. ctx->ctx_weakreflist = NULL;
  952. PyObject_GC_Del(ctx);
  953. ctx_freelist_len--;
  954. }
  955. return size;
  956. }
  957. void
  958. _PyContext_Fini(void)
  959. {
  960. Py_CLEAR(_token_missing);
  961. (void)PyContext_ClearFreeList();
  962. (void)_PyHamt_Fini();
  963. }
  964. int
  965. _PyContext_Init(void)
  966. {
  967. if (!_PyHamt_Init()) {
  968. return 0;
  969. }
  970. if ((PyType_Ready(&PyContext_Type) < 0) ||
  971. (PyType_Ready(&PyContextVar_Type) < 0) ||
  972. (PyType_Ready(&PyContextToken_Type) < 0) ||
  973. (PyType_Ready(&PyContextTokenMissing_Type) < 0))
  974. {
  975. return 0;
  976. }
  977. PyObject *missing = get_token_missing();
  978. if (PyDict_SetItemString(
  979. PyContextToken_Type.tp_dict, "MISSING", missing))
  980. {
  981. Py_DECREF(missing);
  982. return 0;
  983. }
  984. Py_DECREF(missing);
  985. return 1;
  986. }