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.

1266 lines
28 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 int 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. Return the value for `key` if `key` has the value in the context object.
  396. If `key` does not exist, return `default`. If `default` is not given,
  397. return None.
  398. [clinic start generated code]*/
  399. static PyObject *
  400. _contextvars_Context_get_impl(PyContext *self, PyObject *key,
  401. PyObject *default_value)
  402. /*[clinic end generated code: output=0c54aa7664268189 input=c8eeb81505023995]*/
  403. {
  404. if (context_check_key_type(key)) {
  405. return NULL;
  406. }
  407. PyObject *val = NULL;
  408. int found = _PyHamt_Find(self->ctx_vars, key, &val);
  409. if (found < 0) {
  410. return NULL;
  411. }
  412. if (found == 0) {
  413. Py_INCREF(default_value);
  414. return default_value;
  415. }
  416. Py_INCREF(val);
  417. return val;
  418. }
  419. /*[clinic input]
  420. _contextvars.Context.items
  421. Return all variables and their values in the context object.
  422. The result is returned as a list of 2-tuples (variable, value).
  423. [clinic start generated code]*/
  424. static PyObject *
  425. _contextvars_Context_items_impl(PyContext *self)
  426. /*[clinic end generated code: output=fa1655c8a08502af input=00db64ae379f9f42]*/
  427. {
  428. return _PyHamt_NewIterItems(self->ctx_vars);
  429. }
  430. /*[clinic input]
  431. _contextvars.Context.keys
  432. Return a list of all variables in the context object.
  433. [clinic start generated code]*/
  434. static PyObject *
  435. _contextvars_Context_keys_impl(PyContext *self)
  436. /*[clinic end generated code: output=177227c6b63ec0e2 input=114b53aebca3449c]*/
  437. {
  438. return _PyHamt_NewIterKeys(self->ctx_vars);
  439. }
  440. /*[clinic input]
  441. _contextvars.Context.values
  442. Return a list of all variables values in the context object.
  443. [clinic start generated code]*/
  444. static PyObject *
  445. _contextvars_Context_values_impl(PyContext *self)
  446. /*[clinic end generated code: output=d286dabfc8db6dde input=6c3d08639ba3bf67]*/
  447. {
  448. return _PyHamt_NewIterValues(self->ctx_vars);
  449. }
  450. /*[clinic input]
  451. _contextvars.Context.copy
  452. Return a shallow copy of the context object.
  453. [clinic start generated code]*/
  454. static PyObject *
  455. _contextvars_Context_copy_impl(PyContext *self)
  456. /*[clinic end generated code: output=30ba8896c4707a15 input=ebafdbdd9c72d592]*/
  457. {
  458. return (PyObject *)context_new_from_vars(self->ctx_vars);
  459. }
  460. static PyObject *
  461. context_run(PyContext *self, PyObject *const *args,
  462. Py_ssize_t nargs, PyObject *kwnames)
  463. {
  464. if (nargs < 1) {
  465. PyErr_SetString(PyExc_TypeError,
  466. "run() missing 1 required positional argument");
  467. return NULL;
  468. }
  469. if (PyContext_Enter(self)) {
  470. return NULL;
  471. }
  472. PyObject *call_result = _PyObject_FastCallKeywords(
  473. args[0], args + 1, nargs - 1, kwnames);
  474. if (PyContext_Exit(self)) {
  475. return NULL;
  476. }
  477. return call_result;
  478. }
  479. static PyMethodDef PyContext_methods[] = {
  480. _CONTEXTVARS_CONTEXT_GET_METHODDEF
  481. _CONTEXTVARS_CONTEXT_ITEMS_METHODDEF
  482. _CONTEXTVARS_CONTEXT_KEYS_METHODDEF
  483. _CONTEXTVARS_CONTEXT_VALUES_METHODDEF
  484. _CONTEXTVARS_CONTEXT_COPY_METHODDEF
  485. {"run", (PyCFunction)context_run, METH_FASTCALL | METH_KEYWORDS, NULL},
  486. {NULL, NULL}
  487. };
  488. static PySequenceMethods PyContext_as_sequence = {
  489. 0, /* sq_length */
  490. 0, /* sq_concat */
  491. 0, /* sq_repeat */
  492. 0, /* sq_item */
  493. 0, /* sq_slice */
  494. 0, /* sq_ass_item */
  495. 0, /* sq_ass_slice */
  496. (objobjproc)context_tp_contains, /* sq_contains */
  497. 0, /* sq_inplace_concat */
  498. 0, /* sq_inplace_repeat */
  499. };
  500. static PyMappingMethods PyContext_as_mapping = {
  501. (lenfunc)context_tp_len, /* mp_length */
  502. (binaryfunc)context_tp_subscript, /* mp_subscript */
  503. };
  504. PyTypeObject PyContext_Type = {
  505. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  506. "Context",
  507. sizeof(PyContext),
  508. .tp_methods = PyContext_methods,
  509. .tp_as_mapping = &PyContext_as_mapping,
  510. .tp_as_sequence = &PyContext_as_sequence,
  511. .tp_iter = (getiterfunc)context_tp_iter,
  512. .tp_dealloc = (destructor)context_tp_dealloc,
  513. .tp_getattro = PyObject_GenericGetAttr,
  514. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  515. .tp_richcompare = context_tp_richcompare,
  516. .tp_traverse = (traverseproc)context_tp_traverse,
  517. .tp_clear = (inquiry)context_tp_clear,
  518. .tp_new = context_tp_new,
  519. .tp_weaklistoffset = offsetof(PyContext, ctx_weakreflist),
  520. .tp_hash = PyObject_HashNotImplemented,
  521. };
  522. /////////////////////////// ContextVar
  523. static int
  524. contextvar_set(PyContextVar *var, PyObject *val)
  525. {
  526. var->var_cached = NULL;
  527. PyThreadState *ts = PyThreadState_Get();
  528. PyContext *ctx = context_get();
  529. if (ctx == NULL) {
  530. return -1;
  531. }
  532. PyHamtObject *new_vars = _PyHamt_Assoc(
  533. ctx->ctx_vars, (PyObject *)var, val);
  534. if (new_vars == NULL) {
  535. return -1;
  536. }
  537. Py_SETREF(ctx->ctx_vars, new_vars);
  538. var->var_cached = val; /* borrow */
  539. var->var_cached_tsid = ts->id;
  540. var->var_cached_tsver = ts->context_ver;
  541. return 0;
  542. }
  543. static int
  544. contextvar_del(PyContextVar *var)
  545. {
  546. var->var_cached = NULL;
  547. PyContext *ctx = context_get();
  548. if (ctx == NULL) {
  549. return -1;
  550. }
  551. PyHamtObject *vars = ctx->ctx_vars;
  552. PyHamtObject *new_vars = _PyHamt_Without(vars, (PyObject *)var);
  553. if (new_vars == NULL) {
  554. return -1;
  555. }
  556. if (vars == new_vars) {
  557. Py_DECREF(new_vars);
  558. PyErr_SetObject(PyExc_LookupError, (PyObject *)var);
  559. return -1;
  560. }
  561. Py_SETREF(ctx->ctx_vars, new_vars);
  562. return 0;
  563. }
  564. static Py_hash_t
  565. contextvar_generate_hash(void *addr, PyObject *name)
  566. {
  567. /* Take hash of `name` and XOR it with the object's addr.
  568. The structure of the tree is encoded in objects' hashes, which
  569. means that sufficiently similar hashes would result in tall trees
  570. with many Collision nodes. Which would, in turn, result in slower
  571. get and set operations.
  572. The XORing helps to ensure that:
  573. (1) sequentially allocated ContextVar objects have
  574. different hashes;
  575. (2) context variables with equal names have
  576. different hashes.
  577. */
  578. Py_hash_t name_hash = PyObject_Hash(name);
  579. if (name_hash == -1) {
  580. return -1;
  581. }
  582. Py_hash_t res = _Py_HashPointer(addr) ^ name_hash;
  583. return res == -1 ? -2 : res;
  584. }
  585. static PyContextVar *
  586. contextvar_new(PyObject *name, PyObject *def)
  587. {
  588. if (!PyUnicode_Check(name)) {
  589. PyErr_SetString(PyExc_TypeError,
  590. "context variable name must be a str");
  591. return NULL;
  592. }
  593. PyContextVar *var = PyObject_GC_New(PyContextVar, &PyContextVar_Type);
  594. if (var == NULL) {
  595. return NULL;
  596. }
  597. var->var_hash = contextvar_generate_hash(var, name);
  598. if (var->var_hash == -1) {
  599. Py_DECREF(var);
  600. return NULL;
  601. }
  602. Py_INCREF(name);
  603. var->var_name = name;
  604. Py_XINCREF(def);
  605. var->var_default = def;
  606. var->var_cached = NULL;
  607. var->var_cached_tsid = 0;
  608. var->var_cached_tsver = 0;
  609. if (_PyObject_GC_MAY_BE_TRACKED(name) ||
  610. (def != NULL && _PyObject_GC_MAY_BE_TRACKED(def)))
  611. {
  612. PyObject_GC_Track(var);
  613. }
  614. return var;
  615. }
  616. /*[clinic input]
  617. class _contextvars.ContextVar "PyContextVar *" "&PyContextVar_Type"
  618. [clinic start generated code]*/
  619. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=445da935fa8883c3]*/
  620. static PyObject *
  621. contextvar_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  622. {
  623. static char *kwlist[] = {"", "default", NULL};
  624. PyObject *name;
  625. PyObject *def = NULL;
  626. if (!PyArg_ParseTupleAndKeywords(
  627. args, kwds, "O|$O:ContextVar", kwlist, &name, &def))
  628. {
  629. return NULL;
  630. }
  631. return (PyObject *)contextvar_new(name, def);
  632. }
  633. static int
  634. contextvar_tp_clear(PyContextVar *self)
  635. {
  636. Py_CLEAR(self->var_name);
  637. Py_CLEAR(self->var_default);
  638. self->var_cached = NULL;
  639. self->var_cached_tsid = 0;
  640. self->var_cached_tsver = 0;
  641. return 0;
  642. }
  643. static int
  644. contextvar_tp_traverse(PyContextVar *self, visitproc visit, void *arg)
  645. {
  646. Py_VISIT(self->var_name);
  647. Py_VISIT(self->var_default);
  648. return 0;
  649. }
  650. static void
  651. contextvar_tp_dealloc(PyContextVar *self)
  652. {
  653. PyObject_GC_UnTrack(self);
  654. (void)contextvar_tp_clear(self);
  655. Py_TYPE(self)->tp_free(self);
  656. }
  657. static Py_hash_t
  658. contextvar_tp_hash(PyContextVar *self)
  659. {
  660. return self->var_hash;
  661. }
  662. static PyObject *
  663. contextvar_tp_repr(PyContextVar *self)
  664. {
  665. _PyUnicodeWriter writer;
  666. _PyUnicodeWriter_Init(&writer);
  667. if (_PyUnicodeWriter_WriteASCIIString(
  668. &writer, "<ContextVar name=", 17) < 0)
  669. {
  670. goto error;
  671. }
  672. PyObject *name = PyObject_Repr(self->var_name);
  673. if (name == NULL) {
  674. goto error;
  675. }
  676. if (_PyUnicodeWriter_WriteStr(&writer, name) < 0) {
  677. Py_DECREF(name);
  678. goto error;
  679. }
  680. Py_DECREF(name);
  681. if (self->var_default != NULL) {
  682. if (_PyUnicodeWriter_WriteASCIIString(&writer, " default=", 9) < 0) {
  683. goto error;
  684. }
  685. PyObject *def = PyObject_Repr(self->var_default);
  686. if (def == NULL) {
  687. goto error;
  688. }
  689. if (_PyUnicodeWriter_WriteStr(&writer, def) < 0) {
  690. Py_DECREF(def);
  691. goto error;
  692. }
  693. Py_DECREF(def);
  694. }
  695. PyObject *addr = PyUnicode_FromFormat(" at %p>", self);
  696. if (addr == NULL) {
  697. goto error;
  698. }
  699. if (_PyUnicodeWriter_WriteStr(&writer, addr) < 0) {
  700. Py_DECREF(addr);
  701. goto error;
  702. }
  703. Py_DECREF(addr);
  704. return _PyUnicodeWriter_Finish(&writer);
  705. error:
  706. _PyUnicodeWriter_Dealloc(&writer);
  707. return NULL;
  708. }
  709. /*[clinic input]
  710. _contextvars.ContextVar.get
  711. default: object = NULL
  712. /
  713. Return a value for the context variable for the current context.
  714. If there is no value for the variable in the current context, the method will:
  715. * return the value of the default argument of the method, if provided; or
  716. * return the default value for the context variable, if it was created
  717. with one; or
  718. * raise a LookupError.
  719. [clinic start generated code]*/
  720. static PyObject *
  721. _contextvars_ContextVar_get_impl(PyContextVar *self, PyObject *default_value)
  722. /*[clinic end generated code: output=0746bd0aa2ced7bf input=30aa2ab9e433e401]*/
  723. {
  724. if (!PyContextVar_CheckExact(self)) {
  725. PyErr_SetString(
  726. PyExc_TypeError, "an instance of ContextVar was expected");
  727. return NULL;
  728. }
  729. PyObject *val;
  730. if (PyContextVar_Get(self, default_value, &val) < 0) {
  731. return NULL;
  732. }
  733. if (val == NULL) {
  734. PyErr_SetObject(PyExc_LookupError, (PyObject *)self);
  735. return NULL;
  736. }
  737. return val;
  738. }
  739. /*[clinic input]
  740. _contextvars.ContextVar.set
  741. value: object
  742. /
  743. Call to set a new value for the context variable in the current context.
  744. The required value argument is the new value for the context variable.
  745. Returns a Token object that can be used to restore the variable to its previous
  746. value via the `ContextVar.reset()` method.
  747. [clinic start generated code]*/
  748. static PyObject *
  749. _contextvars_ContextVar_set(PyContextVar *self, PyObject *value)
  750. /*[clinic end generated code: output=446ed5e820d6d60b input=c0a6887154227453]*/
  751. {
  752. return (PyObject *)PyContextVar_Set(self, value);
  753. }
  754. /*[clinic input]
  755. _contextvars.ContextVar.reset
  756. token: object
  757. /
  758. Reset the context variable.
  759. The variable is reset to the value it had before the `ContextVar.set()` that
  760. created the token was used.
  761. [clinic start generated code]*/
  762. static PyObject *
  763. _contextvars_ContextVar_reset(PyContextVar *self, PyObject *token)
  764. /*[clinic end generated code: output=d4ee34d0742d62ee input=ebe2881e5af4ffda]*/
  765. {
  766. if (!PyContextToken_CheckExact(token)) {
  767. PyErr_Format(PyExc_TypeError,
  768. "expected an instance of Token, got %R", token);
  769. return NULL;
  770. }
  771. if (PyContextVar_Reset(self, (PyContextToken *)token)) {
  772. return NULL;
  773. }
  774. Py_RETURN_NONE;
  775. }
  776. static PyObject *
  777. contextvar_cls_getitem(PyObject *self, PyObject *args)
  778. {
  779. Py_RETURN_NONE;
  780. }
  781. static PyMemberDef PyContextVar_members[] = {
  782. {"name", T_OBJECT, offsetof(PyContextVar, var_name), READONLY},
  783. {NULL}
  784. };
  785. static PyMethodDef PyContextVar_methods[] = {
  786. _CONTEXTVARS_CONTEXTVAR_GET_METHODDEF
  787. _CONTEXTVARS_CONTEXTVAR_SET_METHODDEF
  788. _CONTEXTVARS_CONTEXTVAR_RESET_METHODDEF
  789. {"__class_getitem__", contextvar_cls_getitem,
  790. METH_VARARGS | METH_STATIC, NULL},
  791. {NULL, NULL}
  792. };
  793. PyTypeObject PyContextVar_Type = {
  794. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  795. "ContextVar",
  796. sizeof(PyContextVar),
  797. .tp_methods = PyContextVar_methods,
  798. .tp_members = PyContextVar_members,
  799. .tp_dealloc = (destructor)contextvar_tp_dealloc,
  800. .tp_getattro = PyObject_GenericGetAttr,
  801. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  802. .tp_traverse = (traverseproc)contextvar_tp_traverse,
  803. .tp_clear = (inquiry)contextvar_tp_clear,
  804. .tp_new = contextvar_tp_new,
  805. .tp_free = PyObject_GC_Del,
  806. .tp_hash = (hashfunc)contextvar_tp_hash,
  807. .tp_repr = (reprfunc)contextvar_tp_repr,
  808. };
  809. /////////////////////////// Token
  810. static PyObject * get_token_missing(void);
  811. /*[clinic input]
  812. class _contextvars.Token "PyContextToken *" "&PyContextToken_Type"
  813. [clinic start generated code]*/
  814. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=338a5e2db13d3f5b]*/
  815. static PyObject *
  816. token_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  817. {
  818. PyErr_SetString(PyExc_RuntimeError,
  819. "Tokens can only be created by ContextVars");
  820. return NULL;
  821. }
  822. static int
  823. token_tp_clear(PyContextToken *self)
  824. {
  825. Py_CLEAR(self->tok_ctx);
  826. Py_CLEAR(self->tok_var);
  827. Py_CLEAR(self->tok_oldval);
  828. return 0;
  829. }
  830. static int
  831. token_tp_traverse(PyContextToken *self, visitproc visit, void *arg)
  832. {
  833. Py_VISIT(self->tok_ctx);
  834. Py_VISIT(self->tok_var);
  835. Py_VISIT(self->tok_oldval);
  836. return 0;
  837. }
  838. static void
  839. token_tp_dealloc(PyContextToken *self)
  840. {
  841. PyObject_GC_UnTrack(self);
  842. (void)token_tp_clear(self);
  843. Py_TYPE(self)->tp_free(self);
  844. }
  845. static PyObject *
  846. token_tp_repr(PyContextToken *self)
  847. {
  848. _PyUnicodeWriter writer;
  849. _PyUnicodeWriter_Init(&writer);
  850. if (_PyUnicodeWriter_WriteASCIIString(&writer, "<Token", 6) < 0) {
  851. goto error;
  852. }
  853. if (self->tok_used) {
  854. if (_PyUnicodeWriter_WriteASCIIString(&writer, " used", 5) < 0) {
  855. goto error;
  856. }
  857. }
  858. if (_PyUnicodeWriter_WriteASCIIString(&writer, " var=", 5) < 0) {
  859. goto error;
  860. }
  861. PyObject *var = PyObject_Repr((PyObject *)self->tok_var);
  862. if (var == NULL) {
  863. goto error;
  864. }
  865. if (_PyUnicodeWriter_WriteStr(&writer, var) < 0) {
  866. Py_DECREF(var);
  867. goto error;
  868. }
  869. Py_DECREF(var);
  870. PyObject *addr = PyUnicode_FromFormat(" at %p>", self);
  871. if (addr == NULL) {
  872. goto error;
  873. }
  874. if (_PyUnicodeWriter_WriteStr(&writer, addr) < 0) {
  875. Py_DECREF(addr);
  876. goto error;
  877. }
  878. Py_DECREF(addr);
  879. return _PyUnicodeWriter_Finish(&writer);
  880. error:
  881. _PyUnicodeWriter_Dealloc(&writer);
  882. return NULL;
  883. }
  884. static PyObject *
  885. token_get_var(PyContextToken *self)
  886. {
  887. Py_INCREF(self->tok_var);
  888. return (PyObject *)self->tok_var;
  889. }
  890. static PyObject *
  891. token_get_old_value(PyContextToken *self)
  892. {
  893. if (self->tok_oldval == NULL) {
  894. return get_token_missing();
  895. }
  896. Py_INCREF(self->tok_oldval);
  897. return self->tok_oldval;
  898. }
  899. static PyGetSetDef PyContextTokenType_getsetlist[] = {
  900. {"var", (getter)token_get_var, NULL, NULL},
  901. {"old_value", (getter)token_get_old_value, NULL, NULL},
  902. {NULL}
  903. };
  904. PyTypeObject PyContextToken_Type = {
  905. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  906. "Token",
  907. sizeof(PyContextToken),
  908. .tp_getset = PyContextTokenType_getsetlist,
  909. .tp_dealloc = (destructor)token_tp_dealloc,
  910. .tp_getattro = PyObject_GenericGetAttr,
  911. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  912. .tp_traverse = (traverseproc)token_tp_traverse,
  913. .tp_clear = (inquiry)token_tp_clear,
  914. .tp_new = token_tp_new,
  915. .tp_free = PyObject_GC_Del,
  916. .tp_hash = PyObject_HashNotImplemented,
  917. .tp_repr = (reprfunc)token_tp_repr,
  918. };
  919. static PyContextToken *
  920. token_new(PyContext *ctx, PyContextVar *var, PyObject *val)
  921. {
  922. PyContextToken *tok = PyObject_GC_New(PyContextToken, &PyContextToken_Type);
  923. if (tok == NULL) {
  924. return NULL;
  925. }
  926. Py_INCREF(ctx);
  927. tok->tok_ctx = ctx;
  928. Py_INCREF(var);
  929. tok->tok_var = var;
  930. Py_XINCREF(val);
  931. tok->tok_oldval = val;
  932. tok->tok_used = 0;
  933. PyObject_GC_Track(tok);
  934. return tok;
  935. }
  936. /////////////////////////// Token.MISSING
  937. static PyObject *_token_missing;
  938. typedef struct {
  939. PyObject_HEAD
  940. } PyContextTokenMissing;
  941. static PyObject *
  942. context_token_missing_tp_repr(PyObject *self)
  943. {
  944. return PyUnicode_FromString("<Token.MISSING>");
  945. }
  946. PyTypeObject PyContextTokenMissing_Type = {
  947. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  948. "Token.MISSING",
  949. sizeof(PyContextTokenMissing),
  950. .tp_getattro = PyObject_GenericGetAttr,
  951. .tp_flags = Py_TPFLAGS_DEFAULT,
  952. .tp_repr = context_token_missing_tp_repr,
  953. };
  954. static PyObject *
  955. get_token_missing(void)
  956. {
  957. if (_token_missing != NULL) {
  958. Py_INCREF(_token_missing);
  959. return _token_missing;
  960. }
  961. _token_missing = (PyObject *)PyObject_New(
  962. PyContextTokenMissing, &PyContextTokenMissing_Type);
  963. if (_token_missing == NULL) {
  964. return NULL;
  965. }
  966. Py_INCREF(_token_missing);
  967. return _token_missing;
  968. }
  969. ///////////////////////////
  970. int
  971. PyContext_ClearFreeList(void)
  972. {
  973. int size = ctx_freelist_len;
  974. while (ctx_freelist_len) {
  975. PyContext *ctx = ctx_freelist;
  976. ctx_freelist = (PyContext *)ctx->ctx_weakreflist;
  977. ctx->ctx_weakreflist = NULL;
  978. PyObject_GC_Del(ctx);
  979. ctx_freelist_len--;
  980. }
  981. return size;
  982. }
  983. void
  984. _PyContext_Fini(void)
  985. {
  986. Py_CLEAR(_token_missing);
  987. (void)PyContext_ClearFreeList();
  988. (void)_PyHamt_Fini();
  989. }
  990. int
  991. _PyContext_Init(void)
  992. {
  993. if (!_PyHamt_Init()) {
  994. return 0;
  995. }
  996. if ((PyType_Ready(&PyContext_Type) < 0) ||
  997. (PyType_Ready(&PyContextVar_Type) < 0) ||
  998. (PyType_Ready(&PyContextToken_Type) < 0) ||
  999. (PyType_Ready(&PyContextTokenMissing_Type) < 0))
  1000. {
  1001. return 0;
  1002. }
  1003. PyObject *missing = get_token_missing();
  1004. if (PyDict_SetItemString(
  1005. PyContextToken_Type.tp_dict, "MISSING", missing))
  1006. {
  1007. Py_DECREF(missing);
  1008. return 0;
  1009. }
  1010. Py_DECREF(missing);
  1011. return 1;
  1012. }