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.

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