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.

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