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.

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