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.

1306 lines
30 KiB

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