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.

1342 lines
31 KiB

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